【问题标题】:How to show the original arguments for a decorator如何显示装饰器的原始参数
【发布时间】:2017-07-17 12:21:39
【问题描述】:
from inspect import signature
from typing import get_type_hints

def check_range(f):
    def decorated(*args, **kwargs): #something should be modified here
        counter=0
        # use get_type_hints instead of __annotations__
        annotations = get_type_hints(f)
        # bind signature to arguments and get an 
        # ordered dictionary of the arguments
        b = signature(f).bind(*args, **kwargs).arguments            
        for name, value in b.items():
            if not isinstance(value, annotations[name]):
                msg = 'Not the valid type'
                raise ValueError(msg)
            counter+=1

        return f(*args, **kwargs) #something should be modified here
    return decorated

@check_range
def foo(a: int, b: list, c: str):
    print(a,b,c)

前段时间我又问了一个问题,得到了很好的回答。但是弹出了另一个不同的问题......我如何让它不在交互式空闲中显示:

但是要显示这个:

【问题讨论】:

    标签: python python-3.x python-decorators


    【解决方案1】:

    您在这里寻找的是functools.wraps,这是一个位于functools 模块中的装饰器,它确保装饰函数的签名、名称和几乎所有其他元数据在装饰后保留:

    from functools import wraps
    
    def check_range(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            counter=0
            # rest as before
    

    【讨论】:

    • 再次感谢您的帮助
    • 不客气@abccd。由于您正在执行一些类型检查,我想指出 Python 有一个 static 类型检查器可以为您进行类型检查。它叫mypy,有兴趣可以看看。
    • 我一定会调查的。再次感谢:)
    猜你喜欢
    • 2010-11-03
    • 2020-11-14
    • 2022-08-15
    • 1970-01-01
    • 2014-09-25
    • 2015-08-18
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多