Search code examples
pythonpython-3.xtype-hinting

What happens when I provide type hint but don't initialize?


I have been after a way to provide none initialized instance variables to my class. I found that we can actually do that using type hinting without assigning anything to them. Which does not seem to create it in anyway. For example:

class T:
    def __init__(self):
        self.a: str
    
    def just_print(self):
        print(self.a)
    
    def assign(self):
        self.a = "test"

Now lets say I run this code:

t = T()
t.just_print()

It will raise an AttributeError saying 'T' object has not attribute 'a'. Obviously, when I run this code, it prints test.

t = T()
t.assign()
t.just_print()

My question is, what happens behind the scene when I just do a: str? It doesn't get added to the class's attributes. But it doesn't cause any problem either. So... is it just ignored? This is python 3.8 by the way.


Solution

  • You're referring to type annotations, as defined by PEP 526:

    my_var: int
    

    Please note that type annotations differ from type hints, as defined by PEP 428:

    def my_func(foo: str):
        ...
    

    Type annotations have actual runtime effects. For example, the documentation states:

    In addition, at the module or class level, if the item being annotated is a simple name, then it and the annotation will be stored in the __annotations__ attribute of that module or class [...]

    So, by slightly modifying your example, we get this:

    >>> class T:
    ...    a: str
    ...    
    >>> T.__annotations__
    {'a': <class 'str'>}