Search code examples
python

Accessing Python 3 type annotations for variables at runtime


I would like to know if it's possible to access type annotations for variables at runtime the same way you can use the __annotations__ entry in inspect.getmembers() for methods and functions.

>>> a: Optional[str] = None
>>> type(a)
<class 'NoneType'>

>>> a: str = None
>>> type(a)
<class 'NoneType'>

Solution

  • locals() and globals() keep track of annotations of variables in the __annotations__ key.

    >>> from typing import *
    >>> a: Optional[int] = None
    >>> locals()['__annotations__']
    {'a': typing.Union[int, NoneType]}
    >>> locals()['__annotations__']['a']
    typing.Union[int, NoneType]
    >>> 
    >>> foo = 0
    >>> bar: foo
    >>> locals()['__annotations__']['bar']
    0
    >>>
    >>> baz: List[str]
    >>> locals()['__annotations__']['baz']
    typing.List[str]