在PEP 3107和this SO answer中暗示Python3K函数注释和装饰器适合手和手套 - 我应该能够编写一个可以使用函数属性的装饰器。有功能注释的装饰器
我不知道如何让它们按照我的预期工作。
考虑:
def verbose(lcls):
def wrap(f):
print('inside wrap')
def wf(*args):
print('inside wf')
print('lcls in wf:',lcls)
print('locals in wf:',locals())
print('wf annotations:',wf.__annotations__)
print('xYx annotations:',xXy.__annotations__)
r=f(*args)
print('after f(*args)')
return r
return wf
return wrap
@verbose(locals())
def xXy(x: 'x in x\'s', y: 'y in Y\'s') -> ('x times y','in x and y units'):
print('locals in xXy:',locals())
return x*y
xy=xXy(10,3)
print(xy)
打印:
inside wrap
inside wf
lcls in wf: {'xXy': <function verbose.<locals>.wrap.<locals>.wf at 0x109767ef0>, '__doc__': None, 'verbose': <function verbose at 0x109767050>, '__cached__': None, '__builtins__': <module 'builtins'>, '__package__': None, '__file__': '/private/var/folders/gx/gqtmx9mn7b75pk1gfy0m9w3w0000gp/T/Cleanup At Startup/test-383453350.857.txt', '__loader__': <_frozen_importlib.SourceFileLoader object at 0x10959ac10>, '__name__': '__main__'}
locals in wf: {'f': <function xXy at 0x109767e60>, 'args': (10, 3), 'lcls': {'xXy': <function verbose.<locals>.wrap.<locals>.wf at 0x109767ef0>, '__doc__': None, 'verbose': <function verbose at 0x109767050>, '__cached__': None, '__builtins__': <module 'builtins'>, '__package__': None, '__file__': '/private/var/folders/gx/gqtmx9mn7b75pk1gfy0m9w3w0000gp/T/Cleanup At Startup/test-383453350.857.txt', '__loader__': <_frozen_importlib.SourceFileLoader object at 0x10959ac10>, '__name__': '__main__'}, 'wf': <function verbose.<locals>.wrap.<locals>.wf at 0x109767ef0>}
wf annotations: {}
xYx annotations: {}
locals in xXy: {'y': 3, 'x': 10}
after f(*args)
30
什么该组线显示的是,我不能看到如何访问x和y的值XXY的装饰或xXy的函数属性。
我会像要做的是1)有一个功能与注释在PEP 3107指定,2)能够有一个装饰器,可以访问函数的注释和函数调用的值,而不只是是xXy函数签名的克隆。
优秀!我正在玩检查,但我还没有弄明白。 – 2013-02-25 04:53:12
只是在Py3.3中添加了'inspect.signature',所以对提问者很有用。它在Py 3.0-3.2中不可用。 – cfi 2013-02-25 16:52:04
我正在使用3.3,所以这个工程太棒了!谢谢!! – 2013-02-25 18:16:42