Ben Chuanlong Du's Blog

It is never too late to learn.

Type Annotation in Python

Tips and Traps

  1. 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.

  2. Notice that the annotation on List and Tuple are different. List[T] stands for a variable length list of elements with type T. However, Tuple[T] stands for a tuple with 1 element of type T. To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.

  3. Use typing.TextIO and typing.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

  1. Run the following command to annotate your Python script.

     :::bash
     monkeytype run yourscript.py
  1. MonkeyType supports pytest.

     :::bash
     monkeytype run `which pytest`

pytype & mypy & pyright

  1. 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.

  2. Both pytype and mypy can be used to check code based using type information. pytype is superior than mype for a few reasons.

    1. 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.

    2. 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

https://github.com/ramonhagenaars/nptyping

https://github.com/microsoft/python-type-stubs

In [ ]:

Comments