假设我有以下代码:
from typing import ClassVar
class A:
a: ClassVar[str]
如何在运行时检查 a
是否已声明为 ClassVar
?
我尝试使用 isinstance
和 issubclass
但它们似乎不起作用:
>>> 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/