检查参数和返回类型

use*_*414 2 python python-3.x

是否可以使用Python 3语法声明输入参数,返回值类型是否可以确定这些类型?与确定函数的参数数量类似?

def foo(name: str) -> int:
    ....
Run Code Online (Sandbox Code Playgroud)

我想获得strint分别.

vau*_*tah 9

typing模块具有以下便利功能:

>>> import typing
>>> typing.get_type_hints(foo)
{'name': <class 'str'>, 'return': <class 'int'>}
Run Code Online (Sandbox Code Playgroud)

(文件)

这不同于foo.__annotations__get_type_hints能够解决前进存储在字符串引用和其他注释,例如

>>> def foo(name: 'foo') -> 'int':
...     ...
... 
>>> foo.__annotations__
{'name': 'foo', 'return': 'int'}
>>> typing.get_type_hints(foo)
{'name': <function foo at 0x7f4c9cacb268>, 'return': <class 'int'>}
Run Code Online (Sandbox Code Playgroud)

它在Python 4.0中特别有用,因为所有注释都将以字符串形式存储.


Pau*_*zer 8

inspect可以使用:

>>> def foo(name: str) -> int:
...     return 0
>>> 
>>> import inspect
>>> 
>>> sig = inspect.signature(foo)
>>> [p.annotation for p in sig.parameters.values()]
[<class 'str'>]
>>> sig.return_annotation
<class 'int'>
Run Code Online (Sandbox Code Playgroud)

不过,@vaultah 的方法看起来更方便。