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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…