Clone
20
Adding and maintaining type annotations in PyTorch
Tom Ritchford edited this page 2025-06-13 16:47:22 +02:00

Type annotations

Python is not a strictly typed language, but Python 3.5 in 2015 introduced type annotations or type hints, advisory descriptions of the types of Python variables and function parameters, and today, they're nearly essential for any new API development.

The official site is at typing.python.org, "Typing Python Libraries" is a good place to start. (PEP 483 - The Theory of Type Hints and PEP 0483 - Type Hints are badly out-of-date.)

The PyTorch project originated in 2016 and didn't start to introduce typing until around 2020, and its type annotations are still not complete. This is not helped by the fact that due to the necessarily baroque structure of such a large computational system, many types are very difficult to spell ("difficult to spell" being jargon for "hard to come up with a type hint that is actually useful for development").

mypy

The reference implementation for type checking is mypy, maintained by the Python foundation. Experimenting by running mypy over toy programs is very effective.

Here's the mypy reference documentation, and here's their "Cheat Sheet"

TODO: Original document is here, what should I just copy from that?

Notes and ideas

Use general types for function parameters and specific types for returns.

Avoid Any and object unless forced to.

What we can do in code

  • Add a declaration
  • Fix the incoming types
  • Assertions
  • typing.TypeIs/typing.TypeGuard
  • typing.Protocol
  • type: ignore annotations
  • typing.cast
  • typing_extensions.assert_type

Covariance, contravariance, invariance

Chameleon Unions

Callables

Decorators

Scalar tensors

TypeGuard vs TypeIs