Inspect Params And Return Types
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 function? d
Solution 1:
The typing
module has a convenience function for that:
>>> import typing
>>> typing.get_type_hints(foo)
{'name': <class'str'>, 'return': <class'int'>}
This is different from foo.__annotations__
in that get_type_hints
can resolve forward references and other annotations stored in string, for instance
>>>deffoo(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.
Solution 2:
inspect
can be used:
>>>deffoo(name: str) -> int:...return0>>>>>>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.
Solution 3:
def foo(name: str) -> int:
pass
foo.__annotations__
# {'name': <class'str'>, 'return': <class'int'>}
foo.__annotations__['return'].__name__
# 'int'
Post a Comment for "Inspect Params And Return Types"