Inspect params and return types

后端 未结 3 826
暖寄归人
暖寄归人 2021-01-13 21:26

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

相关标签:
3条回答
  • 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.

    0 讨论(0)
  • 2021-01-13 22:10
    def foo(name: str) -> int:
        pass
    
    foo.__annotations__
    # {'name': <class 'str'>, 'return': <class 'int'>}
    
    foo.__annotations__['return'].__name__
    # 'int'
    
    0 讨论(0)
  • 2021-01-13 22:12

    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.

    0 讨论(0)
提交回复
热议问题