python - 如何检查注释是否是 Python 中的 ClassVar?

标签 python python-3.x

假设我有以下代码:

from typing import ClassVar

class A:
    a: ClassVar[str]

如何在运行时检查 a 是否已声明为 ClassVar

我尝试使用 isinstanceissubclass 但它们似乎不起作用:

>>> A.__annotations__
{'a': typing.ClassVar[str]}
>>> x = A.__annotations__["a"]
>>> isinstance(x, typing.ClassVar)
TypeError: typing.ClassVar cannot be used with isinstance()
>>> issubclass(x, typing.ClassVar)
TypeError: typing.ClassVar cannot be used with issubclass()

最佳答案

我设法(显然)通过使用 __origin__ 解决了这个问题:

>>> x = A.__annotations__["a"]
>>> x.__origin__ is ClassVar
True

关于python - 如何检查注释是否是 Python 中的 ClassVar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549193/

相关文章:

Python Matplotlib 如何只获取表格

python - 使用 Fig.update_layout Plotly 更新 Traces 的可见性

python - 如果我用re.findall 怎么注册才能不分开点

使用 aiohttp 的 Python 3.6 异步 GET 请求同步运行

python - 获取值错误: Columns must be same length as key

python - 如果你在 Python 中迭代一个列表或一个元组,它会有所不同吗?

python - Sendkeys 函数出现问题

python - 有效区分元组中不同可能的组合

python-3.x - df.copy() 方法不支持的操作数类型

python - 使用列表中的数据以唯一的索引顺序填充 Pandas 数据框?