Search code examples
pythonpython-typingclass-variables

How to inspect all ClassVar inside class?


I have a Python class like the below:

from typing import ClassVar

class Foo:
    bar: ClassVar[int] = 1
    
    def __init__(self):
        self.spam: int = 2

How can I inspect this class Foo to get the ClassVars and their values?

I am looking for something like {"bar": 1}, and need this to work for Python 3.8+.


Solution

  • You can do it by inspecting the class' __annotations__ dictionary.

    from typing import ClassVar
    
    class Foo:
        bar: ClassVar[int] = 1
    
        def __init__(self):
            self.spam: int = 2
    
    for attr, cls in Foo.__annotations__.items():
        print(f'{attr=}, {cls=}, value={getattr(Foo, attr)}')
    

    Output:

    attr='bar', cls=typing.ClassVar[int], value=1