装饰器python库将args隐藏在args内部 [英] decorator python library hide the kwargs inside args

查看:85
本文介绍了装饰器python库将args隐藏在args内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的装饰器库有一个很奇怪的行为,在下一个代码中对此进行了解释:

I got a pretty weird behaviour with the decorator library which is explained in the next code:

from decorator import decorator    

@decorator
def wrap(f, a, *args, **kwargs):
    print 'Decorator:', a, args, kwargs
    return f(a, *args, **kwargs)

def mywrap(f):
    def new_f(a, *args, **kwargs):
        print 'Home made decorator:', a, args, kwargs
        return f(a, *args, **kwargs)
    return new_f

@wrap
def funcion(a, b, *args, **kwargs):
    pass

@mywrap
def myfuncion(a, b, *args, **kwargs):
    pass

funcion(1, b=2)
myfuncion(1, b=2)

此脚本的执行将打印:

$ python /tmp/test.py 
Decorator: 1 (2,) {}
Home made decorator: 1 () {'b': 2}

'decorator'将kwargs隐藏在args中,如何解决此问题而不使用 home

'decorator' hides the kwargs inside the args, how can I solve this without using a "home made" decorator.

谢谢。

推荐答案

只是因为您 call 具有 b = 2 的函数不会将 b 用作关键字参数; b 是原始函数中的位置参数。如果没有名为 b 的参数,而您指定了 b = 2 ,则然后 b 将成为关键字参数。

Just because you call the function with b=2 does not make b a keyword argument; b is a positional argument in the original function. If there were no argument named b and you specified b=2, then b would become a keyword argument.

装饰器的行为实际上是最正确的;它生成的包装与 funcion()具有相同的签名,而由自制装饰器制作的包装没有 b 作为命名参数。 自制包装器错误地将 b 放入 kwargs ,因为 myfuncion( ),这清楚地表明 b 不是关键字arg,对调用者隐藏。

decorator's behavior is actually the most correct; the wrapper it generates has the same signature as funcion(), whereas the wrapper made by your "homemade" decorator does not have b as a named argument. The "homemade" wrapper "incorrectly" puts b in kwargs because the signature of myfuncion(), which makes it clear that b is not a keyword arg, is hidden from the caller.

装饰器中保留功能签名是功能,而不是错误。

Preserving the function signature is a feature, not a bug, in decorator.

这篇关于装饰器python库将args隐藏在args内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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