paulgorman.org/technical

Python Type Hints

(2023)

Python 3-something added support for type hints.

The Python runtime does not enforce types, but pre-runtime checkers (IDEs, linters, etc.) exist to check type hints. To turn on type checking with the VS Code Pylance plugin, set python.analysis.typeCheckingMode to basic or strict.

x: int = 1
x: float = 1.0
x: bool = True
x: str = "test"
x: bytes = b"test"

Remember that these are type hints and not enforced by the Python runtime:

>>> x: int = 3
>>> type(x)
<class 'int'>
>>> x = 2.999
>>> type(x)
<class 'float'>

We can declare variable without assigning a value. Again, the type isn’t enforced (or even known) by the Python runtime, but pre-runtime checkers could do something about the type hint:

>>> import typing
>>> x: int
>>> type(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  NameError: name 'x' is not defined

References