Inspect params and return types

后端 未结 3 827
暖寄归人
暖寄归人 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 22:12

    The typing module has a convenience function for that:

    >>> import typing
    >>> typing.get_type_hints(foo)
    {'name': , 'return': }
    

    (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': , 'return': }
    

    It will be especially useful in Python 4.0, because then all annotations will be stored in string form.

提交回复
热议问题