Tips and Traps¶
Type hints cheat sheet (Python 3) is a quick cheat sheet showing how the PEP 484 type annotation notation represents various common types in Python 3.
Notice that the annotation on List and Tuple are different.
List[T]
stands for a variable length list of elements with typeT
. However,Tuple[T]
stands for a tuple with 1 element of typeT
. To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g.Tuple[int, ...]
. A plain Tuple is equivalent toTuple[Any, ...]
, and in turn to tuple.Use
typing.TextIO
andtyping.BinaryIO
for file handler object.
Forward References¶
You can use forward reference in Python 3.8+.
It is also backported into Python 3.7,
which is accessible after the import statement from __future__ import annotations
.
MonkeyType¶
Run the following command to annotate your Python script.
:::bash monkeytype run yourscript.py
MonkeyType supports pytest.
:::bash monkeytype run `which pytest`
pytype & mypy & pyright¶
When you are using Visual Studio Code, install the Python extension for Visual Studio Code and you are good to go. Pyright’s type-checking functionality and language features are now incorporated into a VS Code extension called Pylance, the officially supported Python Language Server from Microsoft. Pylance is designed to work with the Python extension for VS Code.
Both pytype and mypy can be used to check code based using type information. pytype is superior than mype for a few reasons.
Pytype uses inference instead of gradual typing. This means it will infer types on code even when the code has no type hints on it. So it can detect issues with code like this, which other type checkers would miss.
Pytype is lenient instead of strict. That means it allows all operations that succeed at runtime and don’t contradict annotations. For instance, this code will pass as safe in pytype, but fail in other type checkers, which assign types to variables as soon as they are initialized.
Stubs¶
typeshed contains external type annotations for the Python standard library and Python builtins, as well as third party packages as contributed by people external to those projects. typeshed is already contained in static type checking tools such as Pyright.
https://github.com/zero323/pyspark-stubs
https://github.com/predictive-analytics-lab/data-science-types
References¶
http://www.legendu.net/misc/blog/static-type-checking-of-Python-Scripts-using-pytype/
http://www.legendu.net/misc/blog/static-type-checking-python-mypy/
https://stackoverflow.com/questions/15853469/putting-current-class-as-return-type-annotation