Suppose I have the following code:
from typing import ClassVar
class A:
a: ClassVar[str]
How do I check, at runtime, if a
has been declared as a ClassVar
?
I tried using isinstance
and issubclass
but they don't seem to work:
>>> 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()
I managed to solve this (apparently) by using __origin__
:
>>> x = A.__annotations__["a"]
>>> x.__origin__ is ClassVar
True