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:

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

  1. from typing import List
  2.  
  3. def hello(): # type: () -> None
  4. print 'hello'
  5.  
  6. class Example:
  7. def method(self, lst, opt=0, *args, **kwargs):
  8. # type: (List[str], int, *str, **bool) -> int
  9. """Docstring comes after type comment."""
  10. ...

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 with or **, respectively (except when using the multi-lineannotation syntax described below). Again, the above exampleillustrates this.
  • Things like Any must be imported from typing, even if theyare only used in comments.
  • In Python 2 mode str is implicitly promoted to unicode, similarto how int is compatible with float. This is unlike bytes andstr in Python 3, which are incompatible. bytes in Python 2 isequivalent to str. (This might change in the future.)