python - 带函数注解的装饰器

标签 python python-3.x decorator

在 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

那组行告诉我的是,我看不到如何在装饰器中访问 xXy 中的 x 和 y 的值或 xXy 的函数属性。

喜欢做的是 1) 拥有一个带有 PEP 3107 中指定的注释的函数,2) 能够拥有一个可以访问函数注释和函数值的装饰器调用 with 而不仅仅是 xXy 函数签名的克隆。

最佳答案

3.3 版新功能,inspect.signature()将允许您在函数装饰器中获得所需的信息。下面是一个使用它来打印在每次调用装饰函数时传递的参数名称和值以及访问关联注释的示例:

import functools
import inspect

def verbose(wrapped):
    @functools.wraps(wrapped)  # optional - make wrapper look like wrapped
    def wrapper(*args):
        print('inside wrapper:')
        fsig = inspect.signature(wrapped)
        parameters = ', '.join('{}={}'.format(*pair)
                               for pair in zip(fsig.parameters, args))
        print('  wrapped call to {}({})'.format(wrapped.__name__, parameters))
        for parameter in fsig.parameters.values():
            print("  {} param's annotation: {!r}".format(parameter.name,
                                                         parameter.annotation))
        result = wrapped(*args)
        print('  returning {!r} with annotation: {!r}'.format(result,
                                                         fsig.return_annotation))
        return result
    return wrapper

@verbose
def xXy(x: 'x in X\'s', y: 'y in Y\'s') -> ('x times y','in X and Y units'):
    return x*y

xy = xXy(10, 3)
print('xXy(10, 3) -> {!r}'.format(xy))

输出:

inside wrapper:
  wrapped call to xXy(x=10, y=3)
  x param's annotation: "x in X's"
  y param's annotation: "y in Y's"
  returning 30 with annotation: ('x times y', 'in X and Y units')
xXy(10, 3) -> 30

关于python - 带函数注解的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15059397/

相关文章:

python - pyinstaller 捆绑 python 应用程序后如何修复 "ImportError: unable to find Qt5Core.dll on PATH"

python - 删除数组的维度?

python - Python3 While语法错误

用于刷新光标实例的 Python 装饰器

angular - TypeScript 装饰器 - 不在对象的属性上调用 Setter

javascript - typescript 类装饰器 : typing properties defined in decorator function

python - 以 csv 格式显示 Pandas DataFrame

python - ValueError : Axes instance argument was not found in a figure, 同名问题没有答案

python - 以可以在 Python 中排序的格式存储输出

python - 如何从图中删除 plotly logo ("Produced with plotly")