Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在运行时访问变量的Python3类型注释_Python_Python 3.x_Annotations - Fatal编程技术网

在运行时访问变量的Python3类型注释

在运行时访问变量的Python3类型注释,python,python-3.x,annotations,Python,Python 3.x,Annotations,我想知道是否可以在运行时访问变量的类型注释,方法和函数可以使用inspect.getmembers()中的\uuuuuuuu注释\uuuuu条目 > a:Optional[str]=None > type(a) <class 'NoneType'> > a:str=None > type(a) <class 'NoneType'> >a:可选[str]=无 >类型(a) >a:str=无 >类型(a) 谢谢。locals()和globals(

我想知道是否可以在运行时访问变量的类型注释,方法和函数可以使用
inspect.getmembers()
中的
\uuuuuuuu注释\uuuuu
条目

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

> a:str=None
> type(a)
<class 'NoneType'>
>a:可选[str]=无
>类型(a)
>a:str=无
>类型(a)
谢谢。

locals()
globals()
跟踪
\uuuuuuuuuuuuuu注释
键中变量的注释

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