SE4Sci

Static Typing

Prelude

To keep the slides simple, I will assume the following imports:

import enum
import typing
from collections.abc import Sequence
from typing import Literal, assert_never, overload

Static typing

  • What is the best thing about Python? No explicit typing

  • What is the worst thing about Python? No explicit typing

Static typing

  • What is the best thing about Python? No explicit typing

    • Easy to read a little code
    • Easier to learn
  • What is the worst thing about Python? No explicit typing

    • Hard to read a larger codebase
    • Breakage always happens at runtime
    • Lots of pitfalls even with good tests (like forgetting None)

Optional static typing

Python has been gaining optional static typing!

def times_three(x: float) -> float:
    return x * 3

What happens when we do this:

times_three(["hi"])

Optional static typing (2)

Python doesn't check type annotations! Libraries can read them at runtime, but this is uncommon. Use a type checker to check them.

  • mypy: The original type checker, started by Jukka Lehtosalo with help from CPython core developers.
  • Pyright: Microsoft's type checker. Powers Pylance in VS Code.
  • Pyre / Pyrefly: Meta's type checkers. Pyre is in OCaml; Pyrefly (its replacement) is in Rust.
  • pytype: Google's type checker with inference. Deprecated.
  • PyCharm also has a built-in one.
  • ty (beta): from Astral, written in Rust (by the Ruff/uv devs).

Why study this?

  • Final step toward compiled languages
  • Type checker is basically a compiler (that doesn't compile)
  • mypyc actually can compile, by the way
  • Valuable skill in Python, too!

We can study types, generics, Protocols, etc. All without leaving Python!

Runtime usage

  • Type annotations are evaluated & stored on class/module/function (lazily evaluated on access in 3.14+)
  • Type annotations are thrown away inside functions
  • A string is identical to its evaluated contents
  • If you from __future__ import annotations (Python 3.7), then unevaluated strings are stored instead

Some libraries that use runtime annotations are Pydantic and beartype. They should still be types, though.

The stdlib uses them in a couple of places (dataclasses look for typing.ClassVar, and functools.singledispatch can use them).

Demo simple.py

Run mypy with:

mypy simple.py

You can also use pre-commit, nox, etc.

This is "gradual" typing. You can enable strict mode:

mypy --strict simple.py

Demo: Optional example

mypy is great at checking for None handling. See if you can spot the error in optional.py. mypy can!

Revealing the type

You can use reveal_type(x) or typing.reveal_type(x) (newer versions of Python) like a type-checker "print" statement.

Ignoring errors

You can ignore errors with # type: ignore comments!

x: str = f()
x.nonexistent()  # type: ignore[attr-defined]

Lying about types

You can lie about typing in Python, since it's not actually using them.

Doesn't work in a compiled language!

But a useful escape hatch sometimes.

Typing basics

# Variable annotation (3.6+)
x: int = 2

# No assignment is allowed ("declaration")
y: int

# Function annotation
def f(x: int) -> int:
    return x

# Class annotations
class X:
    a: int  # Declares instance variable, use typing.ClassVar otherwise

Basic types

Note you don't need types if they can be inferred.

a: int = 1
b: str = "hi"
c: bytes = b"hi"
d: float = 1.0
e: complex = 1 + 1j
f: bool = True
g: None = None  # is its own type

Catchall types

from typing import Any

x: Any = could_return_anything()  # Everything valid
y: object = could_return_anything()  # Nothing assumed

Operations on object are restricted to only things that work on all objects (like str(y)).

Any is an escape hatch allowing a mix of static and dynamic code.

Generics

Generics are parametrized types. Python has several built-in:

a: list[int] = [1, 2, 3]
b: tuple[int, int, int] = (1, 2, 3)
c: tuple[int, ...] = (1, 2, 3)
d: dict[str, int] = {"one": 1, "two": 2}

Lists have a single parameter, the type the list holds. Tuples take one parameter per element, or a single type followed by ... for any length. And dicts take one for the key and one for the value.

Unions

w: int | str = "hi"  # Either string or int
x: list[int | str] = [1, "hi"]  # Mix of strings and ints
y: list[int] | list[str] = [1, 2]  # All strings or all ints

Uses the A|B (Python 3.10+, 3.7+ annotations only with future import) or typing.Union[A,B].

Very commonly used for "Nonable" (typing.Optional)

x: int | None = None

Other types

These are things common in compiled languages.

  • Literal[X]: Only this value (or values) exactly. Enum-like
  • Final[X]: Not allowed to be replaced later
  • @final: A decorator for methods that can't be overridden or classes that can't be subclassed
  • enum.Enum: An enum type (subclass to make one)
  • TypedDict: A string keyed dict with types per key
  • NamedTuple: A tuple with names for items (and types, of course)
  • Self: The current class (3.11+)

Typing backports

If something was added in a newer version of Python, it is also in typing_extensions for older versions of Python.

import sys

if sys.version_info < (3, 11):
    from typing_extensions import Self
else:
    from typing import Self

And then only require typing-extensions; python_version<"3.11".

Type narrowing

How do type checkers work? One key feature is type narrowing.

def f(x: str | None) -> str:  # x is str | None
    if x is None:
        return ""  # x must be None here
    return x  # x must be str here

The if statement "guards" against the None case, so after the if, the type has been narrowed to just str.

Type narrowing: question

What would this print?

def f(x: str | None) -> None:
    if x:
        reveal_type(x)
    else:
        reveal_type(x)

Type narrowing: a little help

You can help narrow with assert:

def could_be_none(y: bool) -> int | None:
    return 42 if y else None

y = could_be_none(True)
assert y is not None
print(f"Bitcount: {y.bit_count()}")

FYI, for the above, it would be better to use overloads with literals, we'll see that later.

Literals

Literals are often useful with type narrowing. Taking the following example:

from typing import Literal

def run(action: Literal["start", "stop"]) -> bool:
    if action == "start":
        return True
    return False

We'd like to be able to a) run this on str too, and b) get a literal True/False out if we put a literal in.

Overloads

@overload
def run(action: Literal["start"]) -> Literal[True]: ...

@overload
def run(action: Literal["stop"]) -> Literal[False]: ...

@overload
def run(action: str) -> bool: ...

def run(action: str) -> bool:
    if action == "start":
        return True
    return False

Now if we use a literal, the type system will know the actual value!

Exhaustiveness checking

class Direction(enum.Enum):
    up = enum.auto()
    down = enum.auto()

def handle_direction(direction: Direction) -> str:
    if direction == Direction.up:  # direction contains [up, down]
        return "up"
    if direction == Direction.down:  # direction contains [down]
        return "down"
    assert_never(direction)  # direction is the empty Union

If you add a new enum item later, this will fail until you handle it!

Structural subtyping

This is basically formalized duck typing.

  • Python: Protocol
  • C++: Concepts
  • Go: Interfaces

Similar, but nominal (you must opt in explicitly): Java interfaces, Rust traits.

Protocols

What is the type of x in this function?

def f(x) -> None:
    x.quack()

We could look up the actual type(s) this is called on.

Or we could formalize what we know with a Protocol!

Protocols (2)

class Duck(typing.Protocol):
    def quack(self) -> None: ...  # `...` is the conventional stub body

def f(x: Duck) -> None:
    x.quack()

Now, f can be called on any object that has a .quack() method, and the type checker will be happy!

Runtime protocols

Opt-in. Only checks that the methods exist, not their signatures.

@typing.runtime_checkable
class Duck(typing.Protocol):
    def quack(self) -> None: ...

class MyDuck:
    def quack(self) -> None:
        print("Quack!")

# Works at runtime
assert isinstance(MyDuck(), Duck)

Verify you pass a Protocol

Here's a (slightly weird) trick to see if you pass a Protocol:

if typing.TYPE_CHECKING:
    _: Duck = typing.cast(MyDuck, None)

When running the type checker, you pretend (cast) that None is an instance of a MyDuck, and then see if you can assign it to a variable of type Duck. If you can, it's a valid Duck.

Note that typing.assert_type (3.11) only checks exact types, not structural subtypes, so it's not useful for this.

Standard ABCs

  • Iterable[T]: Something that can be iterated (has __iter__)
  • Iterator[T]: Something that is being iterated (has __next__ and __iter__)
  • Sized: Something that has a __len__
  • Collection[T]: This can be iterated over and is Sized
  • Sequence[T]: Collection with random access (list, tuple)
  • Generator[T, None, None]: This is what a yield function returns (Generator[T] in 3.13+)
  • Mapping[K, V]: Something that acts like a dict
  • Callable[[Args, ...], RetValue]: Something that is callable
  • Set[T] (from collections.abc, not typing): A set or frozenset, or similar

When to use abstract vs. concrete types

  • Input parameters should be as general as possible
  • Output should be as specific as possible
from collections.abc import Sequence, Sized

def match_ints(a: Sequence[int], b: Sized) -> list[int]:
    return list(a[: len(b)])

In this case, we might want to "pass-through" the type of a...

Generics: TypeVar

Let's type this trivial function:

def f(x):
    return x

We need to "pass-through" the type of x.

Generics: TypeVar (Python 3.12+)

def f[T](x: T) -> T:
    return x

In Python 3.12+, we could do it as shown. But that is not valid at runtime in older versions, since it's new syntax, and not only an annotation.

For generic classes, this syntax also infers covariance/contravariance for you!

Generics: TypeVar

T = typing.TypeVar("T")

def f(x: T) -> T:
    return x
  • TypeVars must be used in the input of a function.
  • TypeVar can be inside another type
  • You can constrain TypeVar to certain types & subclasses (bound=)
  • Or just to specific types (positional arguments)
  • TypeVars can be covariant, contravariant, or invariant (more later)

Type theory: Contravariant or Covariant

TL;DR: Do whatever the type checker tells you

Variance is a property of a generic type. If C is a subclass of B:

  • Covariant: Container[C] is a subtype of Container[B]
  • Contravariant: Container[B] is a subtype of Container[C]
  • Invariant: neither

Immutable collections are covariant: Sequence[C] works where Sequence[B] is expected. Lists (or anything mutable) are invariant. Callable arguments are contravariant.

Going further

Try mypyc; it can compile your Python, often giving a 1.5-5x speedup on a fully typed codebase.

Examples

Following are some examples.

What's the best annotation for this function?

def all_upper(values):
    return [v.upper() for v in values]

items = ["one", "two"]
result = all_upper(items)

Attempt 1: explicit values

def all_upper(values: list[str]) -> list[str]:
    return [v.upper() for v in values]

items = ["one", "two"]
result = all_upper(items)

What about a different container?

def all_upper(values: list[str]) -> list[str]:
    return [v.upper() for v in values]

items = ("one", "two")
result = all_upper(items)  # ❌

Attempt 2: abstract type (ABC)

def all_upper(values: Sequence[str]) -> list[str]:
    return [v.upper() for v in values]

items = ("one", "two")
result = all_upper(items)

Details

This is fairly common: Use an abstract type (ABC or Protocol) for input arguments, and be as exact as possible on return types!

In fact, try never to return an abstract type. You want the type system to track actual types.

Bad use of abstract types

from collections.abc import Sequence
from typing import Any, reveal_type
import copy

def copy_sequence(seq: Sequence[Any]) -> Sequence[Any]:
    return copy.copy(seq)

a = ["1", "2"]
b = copy_sequence(a)
reveal_type(b)  # Sequence[Any]

As a reader, the type of b is obvious: it's a list[str]. But typing can't see that.

Better

from collections.abc import Sequence
from typing import Any, reveal_type
import copy

def copy_sequence[T: Sequence[Any]](seq: T) -> T:
    return copy.copy(seq)

a = ["1", "2"]
b = copy_sequence(a)
reveal_type(b)  # list[str]

Smarter return types

You want the return type to be as accurate as possible. Use overloads if the type depends on the arguments in a non-trivial way (not passed through).

def call(*args: str, quiet: bool = False) -> str | None:
    # Logic would go here
    if quiet:
        return f"result of {args}"
    return None

call("echo", "hi", quiet=True).strip()  # ❌ Can't call on None

Smarter return types (2)

@overload
def call(*args: str, quiet: Literal[False] = ...) -> None: ...

@overload
def call(*args: str, quiet: Literal[True]) -> str: ...

@overload
def call(*args: str, quiet: bool = ...) -> str | None: ...

def call(*args: str, quiet: bool = False) -> str | None:
    "See above"