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:
- import sys
- # Distinguishing between different versions of Python:
- if sys.version_info >= (3, 5):
- # Python 3.5+ specific definitions and imports
- elif sys.version_info[0] >= 3:
- # Python 3 specific definitions and imports
- else:
- # Python 2 specific definitions and imports
- # Distinguishing between different operating systems:
- if sys.platform.startswith("linux"):
- # Linux-specific code
- elif sys.platform == "darwin":
- # Mac-specific code
- elif sys.platform == "win32":
- # Windows-specific code
- else:
- # 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:
- import sys
- assert sys.platform != 'win32'
- # 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.platform
check 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.platform
for examples of valid platform parameters.