Updated Adding and maintaining type annotations in PyTorch (markdown)

Tom Ritchford
2025-06-07 16:05:27 +02:00
parent 71b46ed668
commit d465213694

@ -1,17 +1,17 @@
## Type annotations
Python is not a strictly typed language, but in 2015, Python 3.5 introduced the idea of **type annotations**, often called **type hints**, advisory descriptions of the types of Python variables or function parameters, and within a decade, type annotations became almost essential for disciplined development.
Python is not a strictly typed language, but in 2015, Python 3.5 introduced the idea of **type annotations**, often called **type hints**, advisory descriptions of the types of Python variables or function parameters. Within a decade, type annotations became almost essential for disciplined development in Python.
A complete, current reference for the type system is at [typing.python.org](https://typing.python.org/en/latest/index.html). Their one-page ["Best Practices"](https://typing.python.org/en/latest/reference/best_practices.html) is a quick read but incomplete. (The two documents that started it all, [PEP 483 - The Theory of Type Hints](https://peps.python.org/pep-0483/) and [PEP 0483 - Type Hints](https://peps.python.org/pep-0483/) 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 computation program, 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. An effective way to experiment with Python type checking is to write small toy programs and run `mypy` over them.
Here's the [`mypy` reference documentation](https://mypy.readthedocs.io), and here's their ["Cheat Sheet"](https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html)
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 computation program, 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").
## Use general types for function parameters and specific types for returns.