Search code examples
python-3.xstrong-typing

How to introspect on PEP 484 type hints?


I have observed that for the following function

def foo(x: int) -> List[int]:
   return x + 1

it is possible to obtain the annotation information using the expression foo.__annotations__, which yields {'x': <class 'int'>, 'return': typing.List[int]}.

Is this an official API? If not, does there exist an official API to obtain the signature for an object, and if so what is it?


Solution

  • It is indeed part of the official API.

    For functions you may also see inspect.signature().