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

问题描述 投票:0回答:2

我想知道是否可以在运行时访问变量的类型注释,就像使用

__annotations__
中的
inspect.getmembers()
条目访问方法和函数一样。

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

>>> a: str = None
>>> type(a)
<class 'NoneType'>
python
2个回答
5
投票

locals()
globals()
跟踪
__annotations__
键中变量的注释。

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

0
投票

@TrebledJ 获得灵感,这里有一个用于 REPL 使用的辅助函数:

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

在全局字典中查找变量,如果它已定义且已注释,则返回注释。

© www.soinside.com 2019 - 2024. All rights reserved.