2017-02-27 43 views
2
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

回答

2

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

from functools import wraps 

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

再次感谢您的帮助 – abccd

+0

不客气@abccd。由于你正在执行一些类型检查,我想指出Python有一个* static *类型检查器,可以为你进行类型检查。这就是所谓的“mypy”,如果感兴趣的话可以查看一下。 –

+0

我一定会考虑它的。并再次感谢:) – abccd