[英]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)
I asked another question awhile ago and it got answered splendidly. 我前一段时间问了另一个问题,得到了很好的回答。 But another different question popped up...how do I make it to not show this in interactive idle: 但是又出现了另一个不同的问题......如何让它在交互式空闲时不显示:
But to show this: 但要表明这一点:
What you are looking for here is functools.wraps
, this is a decorator located in the functools
module that makes sure the signature, name and pretty much all other metadata of the decorated function is retained after decoration: 你在这里寻找的是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.