Is it possible using Python 3 syntax for declaring input parameters and return value types determine those types? Similarly to determining the number of parameters of a func
inspect
can be used:
>>> 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'>
@vaultah's method looks even more convenient, though.
def foo(name: str) -> int:
pass
foo.__annotations__
# {'name': <class 'str'>, 'return': <class 'int'>}
foo.__annotations__['return'].__name__
# 'int'
The typing
module has a convenience function for that:
>>> import typing
>>> typing.get_type_hints(foo)
{'name': <class 'str'>, 'return': <class 'int'>}
(the documentation)
This is different from foo.__annotations__
in that get_type_hints
can resolve forward references and other annotations stored in string, for instance
>>> def foo(name: 'foo') -> 'int':
... ...
...
>>> foo.__annotations__
{'name': 'foo', 'return': 'int'}
>>> typing.get_type_hints(foo)
{'name': <function foo at 0x7f4c9cacb268>, 'return': <class 'int'>}
It will be especially useful in Python 4.0, because then all annotations will be stored in string form.