Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Python 3 type annotations for variables at runtime

Tags:

python

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'>
like image 496
Josep Valls Avatar asked Oct 27 '25 10:10

Josep Valls


1 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]
like image 90
TrebledJ Avatar answered Oct 29 '25 01:10

TrebledJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!