问题
I am writing a decorator which will catch TypeError for incorrect number of arguments in a function call and will print a customised message. The code is here:
import inspect
def inspect_signature(f):
def decorate(*args, **kwargs):
try:
f(*args, **kwargs)
except TypeError as e:
print('Failed to call "{}" with signature {}. Provided args={} and kwargs={}.'.format(
f.__name__, inspect.getargspec(f).args, args, kwargs))
return f
return decorate
@inspect_signature
def func(foo, bar):
pass
func('a')
func('a', 'b')
I get the following output:
Failed to call "func" with signature ['foo', 'bar']. Provided args=('a',) and kwargs={}.
Called successfully with foo=a, bar=b
ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)
The function signature is empty. Please suggest me a solution how can I retain it?
PS: I am using python2 and cannot switch to python3.
回答1:
You missed this here. func(*foo, **bar)
In your case func('a')
was not working as you gave fixed arg for it.
You need to pass a variable number of arguments to your function
@inspect_signature
def func(*foo, **bar):
pass
回答2:
You can refer to Preserving signatures of decorated functions.
In a word, you can use decorator
module in Python2 and Python3. When you use Python3.4+, you can use inspect.wraps
to Preserving signatures of decorated functions.
If you don't want to use decorator
module, you can use eval
to make a decorator. In General, eval
is unpopular, so, decorator
module may be the best solution in Python2.
来源:https://stackoverflow.com/questions/42359024/preserve-signature-in-decorator-python-2