繁体   English   中英

如何显示装饰器的原始参数

[英]How to show the original arguments for a decorator

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)

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

在此输入图像描述

但要表明这一点:

在此输入图像描述

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

from functools import wraps

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM