Search code examples
pythonpython-typing

How to get type hints for an object's attributes?


I want to get the type hints for an object's attributes. I can only get the hints for the class and not an instance of it.

I have tried using foo_instance.__class__ from here but that only shows the class variables.

So in the example how do I get the type hint of bar?

class foo:
    var: int = 42
    def __init__(self):
        self.bar: int = 2

print(get_type_hints(foo)) # returns {'var': <class 'int'>}

Solution

  • This information isn't evaluated and only exists in the source code. if you must get this information, you can use the ast module and extract the information from the source code yourself, if you have access to the source code.

    You should also ask yourself if you need this information because in most cases reevaluating the source code will be to much effort.