Python version and system platform checks

Mypy supports the ability to perform Python version checks and platformchecks (e.g. Windows vs Posix), ignoring code paths that won’t be run onthe targeted Python version or platform. This allows you to more effectivelytypecheck code that supports multiple versions of Python or multiple operatingsystems.

More specifically, mypy will understand the use of sys.version_info andsys.platform checks within if/elif/else statements. For example:

  1. import sys
  2.  
  3. # Distinguishing between different versions of Python:
  4. if sys.version_info >= (3, 5):
  5. # Python 3.5+ specific definitions and imports
  6. elif sys.version_info[0] >= 3:
  7. # Python 3 specific definitions and imports
  8. else:
  9. # Python 2 specific definitions and imports
  10.  
  11. # Distinguishing between different operating systems:
  12. if sys.platform.startswith("linux"):
  13. # Linux-specific code
  14. elif sys.platform == "darwin":
  15. # Mac-specific code
  16. elif sys.platform == "win32":
  17. # Windows-specific code
  18. else:
  19. # Other systems

As a special case, you can also use one of these checks in a top-level(unindented) assert; this makes mypy skip the rest of the file.Example:

  1. import sys
  2.  
  3. assert sys.platform != 'win32'
  4.  
  5. # The rest of this file doesn't apply to Windows.

Some other expressions exhibit similar behavior; in particular,TYPE_CHECKING, variables named MYPY, and any variablewhose name is passed to —always-true or —always-false.(However, True and False are not treated specially!)

Note

Mypy currently does not support more complex checks, and does not assignany special meaning when assigning a sys.version_info or sys.platformcheck to a variable. This may change in future versions of mypy.

By default, mypy will use your current version of Python and your currentoperating system as default values for sys.version_info andsys.platform.

To target a different Python version, use the —python-version X.Y flag.For example, to verify your code typechecks if were run using Python 2, passin —python-version 2.7 from the command line. Note that you do not needto have Python 2.7 installed to perform this check.

To target a different operating system, use the —platform PLATFORM flag.For example, to verify your code typechecks if it were run in Windows, passin —platform win32. See the documentation for sys.platformfor examples of valid platform parameters.