Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Type annotation in Python

Principle

In Python, you can annotate your code with type annotation. For instance, we can say that variable a is an integer:

a: int = 5

In Python, type checking is decorrelated from the execution. So the following program works:

a: str = 5

You are free to leave variable unanotated.

a: str = "aze"
b = 1

Gradual typing

  • C, Java, have static typing.
  • Python, Javascript have dynamic typing.
  • Python has type anotations. You can annotate only a part of your program. This is called gradual typing. It leverages desirable aspects of both dynamic and static typing.

Javascript and Typescript

The situation is a bit close to Typescript which is Javascript with type annotations.

Declaring constants

A variable is… by definition variable. You can change its value (note that you can change it in Python even if its value is immutable).

To make a constant, we can use the type Final[...].

from typing import Final
a: Final[int] = 2
a = 1 # wrong
from typing import Final
lst: Final[list] = [2]
lst.append(3) # ok
lst = [3] # wrong

This is close to:

  • const in C, Javascript
  • final in Java
  • variable without the keyword mut in Rust

In PythonIn C
x: mutabletype = ....type * x = ...
x: immutabletype = ....const type * x = ...
x: Final[mutabletype] = ....type * const x = ...
x: Final[immutabletype] = ....const type * const x = ...

Any

Any is the type of anything in Python.

A: any = 2
  • In Typescript, it is also any
  • In Pascal, we had Variant but it is a bit different.

Parameterized types

A list of what? A tuple of what? A list of integers is list[int].

L: list[int] = [1, 2, 3]
D: dict[str, int] = {"aze": 2, "a": 1}

Veryfing types

Just run:

mypy mypythonprogram.py