Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'>}
like image 308
ellie ff1493 Avatar asked Mar 03 '23 06:03

ellie ff1493


1 Answers

I just had the same problem. The python doc isn't that clear since the example is made with what is now officially called dataclass.

Student(NamedTuple):
    name: Annotated[str, 'some marker']

get_type_hints(Student) == {'name': str}
get_type_hints(Student, include_extras=False) == {'name': str}
get_type_hints(Student, include_extras=True) == {
    'name': Annotated[str, 'some marker']
}

It give the impression that get_type_hints() works on class directly. Turns out get_type_hints() returns hints based on functions, not on class. That way it can be use with both if we know that. A normal class obviously not being instantiated at it's declaration, it does not have any of the variables set within the __init__() method who hasn't yet been called. It couldn't be that way either if we want the possibility to get the type hints from class-wide variables.

So you could either call it on __init__(), that is if variables are passed in arguments though (yes i seen it's not in your example but might help others since i didn't seen this anywhere in hours of search);

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

print(get_type_hints(foo.__init__))

At last for your exact example i believe you have two choices. You could instantiate a temporary object and use del to clean it right after if your logic allows it. Or declare your variables as class ones with or without default values so you can get them with get_type_hints() and assign them later in instantiations.

like image 124
Carl L.D. Avatar answered Mar 13 '23 00:03

Carl L.D.