Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

Preserve Signature in Decorator python 2

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...