Search code examples
pythonpython-3.xpython-3.7type-safetypython-typing

Python typying module for typesafety


python 3.7

I came from Scala with strict type system and this example got me confused:

from typing import Optional

tst: Optional[int] = None
tst2: int = None
tst3: Optional[int] = 'string'

print(tst)  # prints None
print(tst2) # prints None
print(tst3) # prints string

It executes fine without any error.

So the type annotations are only for description and external tools (like linters) and does not affect python runtime itself? Or I missed something


Solution

  • In short: yes, these annotations are mainly just for external tools. The type annotations do not materially change the way the program executes, and you correctly note that a Python program with type errors can execute just fine.

    Just to elaborate a little bit, these type hints come from PEP-483 and PEP-484. These proposals make a distinction between a "type" (the thing you annotate) and "class" (which is actually meaningful at runtime):

    Every class is a type as discussed above. But it is tricky and error prone to implement a class that exactly represents semantics of a given type, and it is not a goal of PEP 484. The static types described in PEP 484, should not be confused with the runtime classes.