Type checking Python 2 code
For code that needs to be Python 2.7 compatible, function typeannotations are given in comments, since the function annotationsyntax was introduced in Python 3. The comment-based syntax isspecified in PEP 484.
Run mypy in Python 2 mode by using the —py2
option:
- $ mypy --py2 program.py
To run your program, you must have the typing
module in yourPython 2 module search path. Use pip install typing
to install themodule. This also works for Python 3 versions prior to 3.5 that don’tinclude typing
in the standard library.
The example below illustrates the Python 2 function type annotationsyntax. This syntax is also valid in Python 3 mode:
- from typing import List
- def hello(): # type: () -> None
- print 'hello'
- class Example:
- def method(self, lst, opt=0, *args, **kwargs):
- # type: (List[str], int, *str, **bool) -> int
- """Docstring comes after type comment."""
- ...
It’s worth going through these details carefully to avoid surprises:
- You don’t provide an annotation for the
self
/cls
variable ofmethods. - Docstring always comes after the type comment.
- For
args
and**kwargs
the type should be prefixed withor
**
, respectively (except when using the multi-lineannotation syntax described below). Again, the above exampleillustrates this. - Things like
Any
must be imported fromtyping
, even if theyare only used in comments. - In Python 2 mode
str
is implicitly promoted tounicode
, similarto howint
is compatible withfloat
. This is unlikebytes
andstr
in Python 3, which are incompatible.bytes
in Python 2 isequivalent tostr
. (This might change in the future.)