[Python] Type hints without value assignment in Python

Discussão em 'Python' iniciado por Stack, Abril 22, 2025.

  1. Stack

    Stack Membro Participativo

    I was under the impression that typing module in Python is mostly for increasing code readability and for code documentation purposes.

    After playing around with it and reading about the module, I've managed to confuse myself with it.

    Code below works even though those two variables are not initialized (as you would normally initialize them e.g. a = "test").

    I've only put a type hint on it and everything seems ok. That is, I did not get a NameError as I would get if I just had a in my code NameError: name 'a' is not defined

    Is declaring variables in this manner (with type hints) an OK practice? Why does this work?

    from typing import Any

    test_var: int
    a: Any

    print('hi')


    I expected test_var: int to return an error saying that test_var is not initiated and that I would have to do something like test_var: int = 0 (or any value at all). Does this get set to a default value because I added type hint to it?

    Continue reading...

Compartilhe esta Página