![](/img/trans.png)
[英]Can I use inspect.signature to interpret a decorator's (*args, **kwargs) as the decorated function's variables would be?
[英]Python's inspect.Signature's signature seems to violate python's signatures rules
inspect模块如何使它看起来像没有默认值(尽管有默认值),这样做的原因是什么(如果有的话)?
inspect.Signature的帮助显示了没有默认值的return_annotation
参数:
>>> import inspect
>>> help(inspect.Signature)
(...)
class Signature(builtins.object)
| Signature(parameters=None, *, return_annotation, __validate_parameters__=True)
(...)
但是,只有一个参数可以构造一个签名:
>>> sig = inspect.Signature(None)
>>> # Nothing bad happens
这似乎违反了规则。 因此,查看Signature
类的代码,我看到:
def __init__(self, parameters=None, *, return_annotation=_empty, __validate_parameters__=True)
好的, return_annotation
确实具有默认值(这就是为什么inspect.Signature(None)
起作用)。
所以问题是:
检查模块是如何做到这一点的? 是否有一个良好的理性这样做?
显然, help
inspect.signature(object)
调用了inspect.signature(object)
,其中object
是函数。 这将对inspect.Signature.empty
默认参数进行处理,以使其显示为根本没有默认值。
另一个例子:
>>> def thing(self, a=inspect.Signature.empty):
... ...
...
>>> help(thing)
Help on function thing in module __main__:
thing(self, a) # Here it is!
您可以通过运行以下命令查看help
功能的作用:
import trace
trace.Trace().runfunc(help, thing)
对我来说(Python 3.6)显示了这一点:
<snip>
pydoc.py(1357): try:
pydoc.py(1358): signature = inspect.signature(object)
--- modulename: inspect, funcname: signature
inspect.py(3002): return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
--- modulename: inspect, funcname: from_callable
inspect.py(2751): return _signature_from_callable(obj, sigcls=cls,
<snip>
pydoc.py(1361): if signature:
pydoc.py(1362): argspec = str(signature)
如果您在代码中复制此代码,则会得到以下信息:
>>> inspect.signature(thing)
<Signature (self, a)>
>>> str(_)
'(self, a)' # huh?!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.