在装饰器python 2中保留签名 [英] Preserve Signature in Decorator python 2

查看:67
本文介绍了在装饰器python 2中保留签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个装饰器,它将捕获函数调用中不正确数量的参数的 TypeError 并打印自定义消息.代码在这里:

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')

我得到以下输出:

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:我使用的是python2,无法切换到python3.

PS: I am using python2 and cannot switch to python3.

推荐答案

可以参考保留修饰函数的签名.

总之,你可以在 Python2 和 Python3 中使用 decorator 模块.当你使用 Python3.4+ 时,你可以使用 inspect.wraps 来保留装饰函数的签名.

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.

如果不想使用decorator模块,可以使用eval来制作装饰器.总的来说,eval 是不受欢迎的,所以 decorator 模块可能是 Python2 中最好的解决方案.

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.

这篇关于在装饰器python 2中保留签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆