Search code examples
pythonpython-typing

How to check if an annotation is a ClassVar in Python?


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

Solution

  • I managed to solve this (apparently) by using __origin__:

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