推荐添加用在装饰器上的自省函数 inspect.signature 的使用说明
linw1995 opened this issue · comments
inspect.signature
可以用来查看内层(被装饰的)函数的参数,提前检查传入外层函数传入的参数是否正确,还可以方便地访问特定参数。
import sys
import inspect
import functools
import traceback
def decorator(func):
sig = inspect.signature(func)
@functools.wraps(func)
def wrap(*args, **kwargs):
bound_arguments = sig.bind(*args, **kwargs)
bound_arguments.apply_defaults()
print(bound_arguments.arguments)
return func(*args, **kwargs)
return wrap
@decorator
def boo(a, b, c):
pass
boo(1, b=2, c=3)
try:
boo(1, b=2, c=3, d=4)
except TypeError:
traceback.print_exc(file=sys.stdout)
执行结果
{'a': 1, 'b': 2, 'c': 3}
Traceback (most recent call last):
File "<ipython-input-1-b43513683a33>", line 27, in <module>
boo(1, b=2, c=3, d=4)
File "<ipython-input-1-b43513683a33>", line 12, in wrap
bound_arguments = sig.bind(*args, **kwargs)
File "/usr/local/Cellar/python@3.9/3.9.1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/inspect.py", line 3062, in bind
return self._bind(args, kwargs)
File "/usr/local/Cellar/python@3.9/3.9.1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/inspect.py", line 3051, in _bind
raise TypeError(
TypeError: got an unexpected keyword argument 'd'