是的,Python函数确实带有这些信息。
最容易的就是使用inspect.getfullargspec()
函数来提取这些信息,或者从Python 3.3开始,使用Signature
objects。
的inspect.getfullargspec()
返回值有.args
属性列出的参数顺序:
>>> import inspect
>>> def f(x: int, y: int) -> type(None):
... pass
...
>>> def g(a: object, b: int) -> type(None):
... pass
...
>>> inspect.getfullargspec(f)
FullArgSpec(args=['x', 'y'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'NoneType'>})
>>> inspect.getfullargspec(f).args
['x', 'y']
>>> inspect.getfullargspec(g).args
['a', 'b']
注解也都会显示:
>>> inspect.getfullargspec(f).annotations
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'NoneType'>}
>>> inspect.getfullargspec(g).annotations
{'return': <class 'NoneType'>, 'a': <class 'object'>, 'b': <class 'int'>}
签名的对象是富裕还是:
>>> sig_f = inspect.signature(f)
>>> sig_g = inspect.signature(g)
>>> sig_f.parameters
mappingproxy(OrderedDict([('x', <Parameter at 0x1031f1ea8 'x'>), ('y', <Parameter at 0x102e00228 'y'>)]))
>>> sig_f.parameters['x'].annotation
<class 'int'>
>>> sig_g.parameters['b'].annotation
<class 'int'>
>>> sig_f.return_annotation == sig_g.return_annotation
True
我们在那里Signature.parameters
es一个有序的字典,让您按照正确的顺序比较参数。
很棒,感谢您的快速响应!所以我不会让我接受它,直到再过10分钟,但这完全回答了我的问题。 – jcsmnt0