Accessing Python 3 type annotations for variables at runtime

Viewed 1043

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'>

Thanks.

2 Answers

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]

Taking inspiration from @TrebledJ, here's a helper function for REPL use:

>>> def get_annot(var: str) -> str:
        if var in globals():
            return globals()["__annotations__"].get(var, "Un-annotated Variable")
        else:
            return "Undefined variable"

>>> var: int = 5
>>> get_annot(var)
int

Looks in the globals dict for the variable and returns annotation if it is both defined and annotated.

Related