如何显示装饰者

时间:2017-02-27 01:26:14

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

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)

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

enter image description here

但要表明这一点:

enter image description here

1 个答案:

答案 0 :(得分:2)

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

from functools import wraps

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