First steps
Type system reference
Configuring and running mypy
Miscellaneous
Project Links
Mypy is very configurable. This is most useful when introducing typing toan existing codebase. SeeUsing mypy with an existing codebase for concrete advice forthat situation.
Mypy supports reading configuration settings from a file. By default, mypy willdiscover configuration files by walking up the file system (up until the root ofa repository or the root of the filesystem). In each directory, it will look forthe following configuration files (in this order):
mypy.ini
.mypy.ini
pyproject.toml
(containing a[tool.mypy]
section)
setup.cfg
(containing a[mypy]
section)
If no configuration file is found by this method, mypy will then look forconfiguration files in the following locations (in this order):
$XDG_CONFIG_HOME/mypy/config
~/.config/mypy/config
~/.mypy.ini
The--config-file
command-line flag has thehighest precedence and must point towards a valid configuration file;otherwise mypy will report an error and exit. Without the command line option,mypy will look for configuration files in the precedence order above.
It is important to understand that there is no merging of configurationfiles, as it would lead to ambiguity.
Most flags correspond closely tocommand-line flags but there are some differences in flag names and someflags may take a different value based on the module being processed.
Some flags support user home directory and environment variable expansion.To refer to the user home directory, use~
at the beginning of the path.To expand environment variables use$VARNAME
or${VARNAME}
.
The configuration file format is the usualini file format. It should containsection names in square brackets and flag settings of the formNAME = VALUE. Comments start with#
characters.
A section named[mypy]
must be present. This specifiesthe global flags.
Additional sections named[mypy-PATTERN1,PATTERN2,...]
may bepresent, wherePATTERN1
,PATTERN2
, etc., are comma-separatedpatterns of fully-qualified module names, with some components optionallyreplaced by the ‘*’ character (e.g.foo.bar
,foo.bar.*
,foo.*.baz
).These sections specify additional flags that only apply tomoduleswhose name matches at least one of the patterns.
A pattern of the formqualified_module_name
matches only the named module,whiledotted_module_name.*
matchesdotted_module_name
and anysubmodules (sofoo.bar.*
would match all offoo.bar
,foo.bar.baz
, andfoo.bar.baz.quux
).
Patterns may also be “unstructured” wildcards, in which stars mayappear in the middle of a name (e.gsite.*.migrations.*
). Stars match zero or more modulecomponents (sosite.*.migrations.*
can matchsite.migrations
).
When options conflict, the precedence order for configuration is:
Inline configuration in the source file
Sections with concrete module names (
foo.bar
)Sections with “unstructured” wildcard patterns (
foo.*.baz
),with sections later in the configuration file overridingsections earlier.Sections with “well-structured” wildcard patterns(
foo.bar.*
), with more specific overriding more general.Command line options.
Top-level configuration file options.
The difference in precedence order between “structured” patterns (byspecificity) and “unstructured” patterns (by order in the file) isunfortunate, and is subject to change in future versions.
Note
Thewarn_unused_configs
flag may be useful to debug misspelledsection names.
Note
Configuration flags are liable to change between releases.
Some of the config options may be set either globally (in the[mypy]
section)or on a per-module basis (in sections like[mypy-foo.bar]
).
If you set an option both globally and for a specific module, the module configurationoptions take precedence. This lets you set global defaults and override them on amodule-by-module basis. If multiple pattern sections match a module,the options from themost specific section are used where they disagree.
Some other options, as specified in their description,may only be set in the global section ([mypy]
).
Options that take a boolean value may be inverted by addingno_
totheir name or by (when applicable) swapping their prefix fromdisallow
toallow
(and vice versa).
mypy.ini
¶Here is an example of amypy.ini
file. To use this config file, place it at the rootof your repo and run mypy.
# Global options:[mypy]warn_return_any=Truewarn_unused_configs=True# Per-module options:[mypy-mycode.foo.*]disallow_untyped_defs=True[mypy-mycode.bar]warn_return_any=False[mypy-somelibrary]ignore_missing_imports=True
This config file specifies two global options in the[mypy]
section. These twooptions will:
Report an error whenever a function returns a value that is inferredto have typeAny
.
Report any config options that are unused by mypy. (This will help us catch typoswhen making changes to our config file).
Next, this module specifies three per-module options. The first two options change how mypytype checks code inmycode.foo.*
andmycode.bar
, which we assume here are two modulesthat you wrote. The final config option changes how mypy type checkssomelibrary
, which weassume here is some 3rd party library you’ve installed and are importing. These options will:
Selectively disallow untyped function definitions only within themycode.foo
package – that is, only for function definitions defined in themycode/foo
directory.
Selectivelydisable the “function is returning any” warnings withinmycode.bar
only. This overrides the global default we set earlier.
Suppress any error messages generated when your codebase tries importing themodulesomelibrary
. This is useful ifsomelibrary
is some 3rd party librarymissing type hints.
For more information, see theImport discoverysection of the command line docs.
string
Specifies the paths to use, after trying the paths fromMYPYPATH
environmentvariable. Useful if you’d like to keep stubs in your repo, along with the config file.Multiple paths are always separated with a:
or,
regardless of the platform.User home directory and environment variables will be expanded.
Relative paths are treated relative to the working directory of the mypy command,not the config file.Use theMYPY_CONFIG_FILE_DIR
environment variable to refer to paths relative tothe config file (e.g.mypy_path=$MYPY_CONFIG_FILE_DIR/src
).
This option may only be set in the global section ([mypy]
).
Note: On Windows, use UNC paths to avoid using:
(e.g.\\127.0.0.1\X$\MyDir
whereX
is the drive letter).
comma-separated list of strings
A comma-separated list of paths which should be checked by mypy if none are given on the commandline. Supports recursive file globbing usingglob
, where*
(e.g.*.py
) matchesfiles in the current directory and**/
(e.g.**/*.py
) matches files in any directories belowthe current one. User home directory and environment variables will be expanded.
This option may only be set in the global section ([mypy]
).
comma-separated list of strings
A comma-separated list of packages which should be checked by mypy if none are given on the commandline. Mypywill not recursively type check any submodules of the providedmodule.
This option may only be set in the global section ([mypy]
).
comma-separated list of strings
A comma-separated list of packages which should be checked by mypy if none are given on the commandline. Mypywill recursively type check any submodules of the providedpackage. This flag is identical tomodules
apart from thisbehavior.
This option may only be set in the global section ([mypy]
).
regular expression
A regular expression that matches file names, directory names and pathswhich mypy should ignore while recursively discovering files to check.Use forward slashes (/
) as directory separators on all platforms.
[mypy]exclude=(?x)(^one\.py$ # files named "one.py"| two\.pyi$ # or files ending with "two.pyi"| ^three\. # or files starting with "three.")
Crafting a single regular expression that excludes multiple files while remaininghuman-readable can be a challenge. The above example demonstrates one approach.(?x)
enables theVERBOSE
flag for the subsequent regular expression, whichignoresmostwhitespaceandsupportscomments
.The above is equivalent to:(^one\.py$|two\.pyi$|^three\.)
.
For more details, see--exclude
.
This option may only be set in the global section ([mypy]
).
Note
Note that the TOML equivalent differs slightly. It can be either a single string(including a multi-line string) – which is treated as a single regularexpression – or an array of such strings. The following TOML examples areequivalent to the above INI example.
Array of strings:
[tool.mypy]exclude=["^one\\.py$",# TOML's double-quoted strings require escaping backslashes'two\.pyi$',# but TOML's single-quoted strings do not'^three\.',]
A single, multi-line string:
[tool.mypy]exclude='''(?x)( ^one\.py$ # files named "one.py" | two\.pyi$ # or files ending with "two.pyi" | ^three\. # or files starting with "three.")'''# TOML's single-quoted strings do not require escaping backslashes
boolean
False
This flag will add everything that matches.gitignore
file(s) toexclude
.This option may only be set in the global section ([mypy]
).
boolean
True
EnablesPEP 420 style namespace packages. See thecorresponding flag--no-namespace-packages
for more information.
This option may only be set in the global section ([mypy]
).
boolean
False
This flag tells mypy that top-level packages will be based in either thecurrent directory, or a member of theMYPYPATH
environment variable ormypy_path
config option. This option is only useful inthe absence of__init__.py. SeeMapping filepaths to modules for details.
This option may only be set in the global section ([mypy]
).
boolean
False
Suppresses error messages about imports that cannot be resolved.
If this option is used in a per-module section, the module name shouldmatch the name of theimported module, not the module containing theimport statement.
boolean
False
Makes mypy analyze imports from installed packages even if missing apy.typed marker or stubs.
If this option is used in a per-module section, the module name shouldmatch the name of theimported module, not the module containing theimport statement.
Warning
Note that analyzing all unannotated modules might result in issueswhen analyzing code not designed to be type checked and may significantlyincrease how long mypy takes to run.
string
normal
Directs what to do with imports when the imported module is foundas a.py
file and not part of the files, modules and packagesprovided on the command line.
The four possible values arenormal
,silent
,skip
anderror
. For explanations see the discussion for the--follow-imports
command line flag.
Using this option in a per-module section (potentially with a wildcard,as described at the top of this page) is a good way to prevent mypy fromchecking portions of your code.
If this option is used in a per-module section, the module name shouldmatch the name of theimported module, not the module containing theimport statement.
boolean
False
Determines whether to respect thefollow_imports
setting even forstub (.pyi
) files.
Used in conjunction withfollow_imports=skip
, this can be usedto suppress the import of a module fromtypeshed
, replacing itwithAny
.
Used in conjunction withfollow_imports=error
, this can be usedto make any use of a particulartypeshed
module an error.
Note
This is not supported by the mypy daemon.
string
Specifies the path to the Python executable to inspect to collecta list of availablePEP 561 packages. Userhome directory and environment variables will be expanded. Defaults tothe executable used to run mypy.
This option may only be set in the global section ([mypy]
).
boolean
False
Disables using type information in installed packages (seePEP 561).This will also disable searching for a usable Python executable. This actsthe same as--no-site-packages
commandline flag.
boolean
False
Enables reporting error messages generated within installed packages (seePEP 561 for more details on distributing type information). Those errormessages are suppressed by default, since you are usually not able tocontrol errors in 3rd party code.
This option may only be set in the global section ([mypy]
).
string
Specifies the Python version used to parse and check the targetprogram. The string should be in the formatMAJOR.MINOR
–for example3.9
. The default is the version of the Pythoninterpreter used to run mypy.
This option may only be set in the global section ([mypy]
).
string
Specifies the OS platform for the target program, for exampledarwin
orwin32
(meaning OS X or Windows, respectively).The default is the current platform as revealed by Python’ssys.platform
variable.
This option may only be set in the global section ([mypy]
).
comma-separated list of strings
Specifies a list of variables that mypy will treat ascompile-time constants that are always true.
comma-separated list of strings
Specifies a list of variables that mypy will treat ascompile-time constants that are always false.
For more information, see theDisallow dynamic typingsection of the command line docs.
boolean
False
Disallows usage of types that come from unfollowed imports (anything imported froman unfollowed import is automatically given a type ofAny
).
boolean
False
Disallows all expressions in the module that have typeAny
.
boolean
False
Disallows functions that haveAny
in their signature after decorator transformation.
boolean
False
Disallows explicitAny
in type positions such as type annotations and generictype parameters.
boolean
False
Disallows usage of generic types that do not specify explicit type parameters.
boolean
False
Disallows subclassing a value of typeAny
.
For more information, see theUntyped definitions and callssection of the command line docs.
boolean
False
Disallows calling functions without type annotations from functions with typeannotations. Note that when used in per-module options, it enables/disablesthis checkinside the module(s) specified, not for functions that comefrom that module(s), for example config like this:
[mypy]disallow_untyped_calls=True[mypy-some.library.*]disallow_untyped_calls=False
will disable this check insidesome.library
, not for your code thatimportssome.library
. If you want to selectively disable this check forall your code that importssome.library
you should instead useuntyped_calls_exclude
, for example:
[mypy]disallow_untyped_calls=Trueuntyped_calls_exclude=some.library
comma-separated list of strings
Selectively excludes functions and methods defined in specific packages,modules, and classes from action ofdisallow_untyped_calls
.This also applies to all submodules of packages (i.e. everything insidea given prefix). Note, this option does not support per-file configuration,the exclusions list is defined globally for all your code.
boolean
False
Disallows defining functions without type annotations or with incomplete typeannotations (a superset ofdisallow_incomplete_defs
).
For example, it would report an error fordeff(a,b)
anddeff(a:int,b)
.
boolean
False
Disallows defining functions with incomplete type annotations, while stillallowing entirely unannotated definitions.
For example, it would report an error fordeff(a:int,b)
but notdeff(a,b)
.
boolean
False
Type-checks the interior of functions without type annotations.
boolean
False
Reports an error whenever a function with type annotations is decorated with adecorator without annotations.
For more information, see theNone and Optional handlingsection of the command line docs.
boolean
False
Causes mypy to treat parameters with aNone
default value as having an implicit optional type (T|None
).
Note: This was True by default in mypy versions 0.980 and earlier.
boolean
True
Effectively disables checking of optionaltypes andNone
values. With this option, mypy doesn’tgenerally check the use ofNone
values – it is treatedas compatible with every type.
Warning
strict_optional=false
is evil. Avoid using it and definitely donot use it without understanding what it does.
For more information, see theConfiguring warningssection of the command line docs.
boolean
False
Warns about casting an expression to its inferred type.
This option may only be set in the global section ([mypy]
).
boolean
False
Warns about unneeded#type:ignore
comments.
boolean
True
Shows errors for missing return statements on some execution paths.
boolean
False
Shows a warning when returning a value with typeAny
from a functiondeclared with a non-Any
return type.
boolean
False
Shows a warning when encountering any code inferred to be unreachable orredundant after performing type analysis.
comma-separated list of strings
Selectively excludes functions and methods defined in specific packages,modules, and classes from thedeprecated error code.This also applies to all submodules of packages (i.e. everything insidea given prefix). Note, this option does not support per-file configuration,the exclusions list is defined globally for all your code.
Note: these configuration options are available in the config file only. There isno analog available via the command line options.
boolean
False
Ignores all non-fatal errors.
For more information, see theMiscellaneous strictness flagssection of the command line docs.
boolean
False
Causes mypy to suppress errors caused by not being able to fullyinfer the types of global and class variables.
boolean
False
By default, mypy won’t allow a variable to be redefined with anunrelated type. Thisexperimental flag enables the redefinition ofunannotated variables with an arbitrary type. You will also need to enablelocal_partial_types
.Example:
defmaybe_convert(n:int,b:bool)->int|str:ifb:x=str(n)# Assign "str"else:x=n# Assign "int"# Type of "x" is "int | str" here.returnx
This also enables an unannotated variable to have different types in differentcode locations:
ifcheck():forxinrange(n):# Type of "x" is "int" here....else:forxin['a','b']:# Type of "x" is "str" here....
Note: We are planning to turn this flag on by default in a future mypyrelease, along withlocal_partial_types
.
boolean
False
Allows variables to be redefined with an arbitrary type, as long as the redefinitionis in the same block and nesting level as the original definition.Example where this can be useful:
defprocess(items:list[str])->None:# 'items' has type list[str]items=[item.split()foriteminitems]# 'items' now has type list[list[str]]
The variable must be used before it can be redefined:
defprocess(items:list[str])->None:items="mypy"# invalid redefinition to str because the variable hasn't been used yetprint(items)items="100"# valid, items now has type stritems=int(items)# valid, items now has type int
boolean
False
Disallows inferring variable type forNone
from two assignments in different scopes.This is always implicitly enabled when using themypy daemon.This will be enabled by default in a future mypy release.
comma-separated list of strings
Allows disabling one or multiple error codes globally.
comma-separated list of strings
Allows enabling one or multiple error codes globally.
Note: This option will override disabled error codes from the disable_error_code option.
boolean
False
This flag enables additional checks that are technically correct but may be impractical.Seemypy--extra-checks
for more info.
boolean
True
By default, imported values to a module are treated as exported and mypy allowsother modules to import them. When false, mypy will not re-export unlessthe item is imported using from-as or is included in__all__
. Note that mypytreats stub files as if this is always disabled. For example:
# This won't re-export the valuefromfooimportbar# This will re-export it as bar and allow other modules to import itfromfooimportbarasbar# This will also re-export barfromfooimportbar__all__=['bar']
boolean
False
Prohibit equality checks, identity checks, and container checks betweennon-overlapping types.
boolean
False
Disable treatingbytearray
andmemoryview
as subtypes ofbytes
.This will be enabled by default inmypy 2.0.
boolean
False
Enable all optional error checking flags. You can see the list offlags enabled by strict mode in the fullmypy--help
output.
Note: the exact list of flags enabled bystrict
maychange over time.
For more information, see theConfiguring error messagessection of the command line docs.
These options may only be set in the global section ([mypy]
).
boolean
False
Prefixes each error with the relevant context.
boolean
False
Shows column numbers in error messages.
boolean
False
Shows documentation link to corresponding error code.
boolean
False
Hides error codes in error messages. SeeError codes for more information.
boolean
False
Use visually nicer output in error messages: use soft word wrap,show source code snippets, and show error location markers.
boolean
True
Shows error messages with color enabled.
boolean
True
Shows a short summary line after error messages.
boolean
False
Show absolute paths to files.
boolean
False
Always useList
instead oflist
in error messages,even on Python 3.9+.
boolean
False
Always useUnion[]
andOptional[]
for union typesin error messages (instead of the|
operator),even on Python 3.10+.
These options may only be set in the global section ([mypy]
).
boolean
True
Enablesincremental mode.
string
.mypy_cache
Specifies the location where mypy stores incremental cache info.User home directory and environment variables will be expanded.This setting will be overridden by theMYPY_CACHE_DIR
environmentvariable.
Note that the cache is only read when incremental mode is enabledbut is always written to, unless the value is set to/dev/null
(UNIX) ornul
(Windows).
boolean
False
Include fine-grained dependency information in the cache for the mypy daemon.
boolean
False
Makes mypy use incremental cache data even if it was generated by adifferent version of mypy. (By default, mypy will perform a versioncheck and regenerate the cache if it was written by older versions of mypy.)
boolean
False
Skip cache internal consistency checks based on mtime.
These options may only be set in the global section ([mypy]
).
comma-separated list of strings
A comma-separated list of mypy plugins. SeeExtending mypy using plugins.
boolean
False
Shows traceback on fatal error.
boolean
False
Raise exception on fatal error.
string
Specifies a custom module to use as a substitute for thetyping
module.
string
This specifies the directory where mypy looks for standard library typeshedstubs, instead of the typeshed that ships with mypy. This isprimarily intended to make it easier to test typeshed changes beforesubmitting them upstream, but also allows you to use a forked version oftypeshed.
User home directory and environment variables will be expanded.
Note that this doesn’t affect third-party library stubs. To test third-party stubs,for example tryMYPYPATH=stubs/sixmypy...
.
boolean
False
Warns about missing type annotations in typeshed. This is only relevantin combination withdisallow_untyped_defs
ordisallow_incomplete_defs
.
If these options are set, mypy will generate a report in the specifiedformat into the specified directory.
Warning
Generating reports disables incremental mode and can significantly slow downyour workflow. It is recommended to enable reporting only for specific runs(e.g. in CI).
string
Causes mypy to generate a text file report documenting how manyexpressions of typeAny
are present within your codebase.
string
Causes mypy to generate a Cobertura XML type checking coverage report.
To generate this report, you must either manually install thelxmllibrary or specify mypy installation with the setuptools extramypy[reports]
.
string
Causes mypy to generate an HTML type checking coverage report.
To generate this report, you must either manually install thelxmllibrary or specify mypy installation with the setuptools extramypy[reports]
.
string
Causes mypy to generate a text file report documenting the functionsand lines that are typed and untyped within your codebase.
string
Causes mypy to generate a JSON file that maps each source file’sabsolute filename to a list of line numbers that belong to typedfunctions in that file.
string
Causes mypy to generate a flat text file report with per-modulestatistics of how many lines are typechecked etc.
These options may only be set in the global section ([mypy]
).
string
Causes mypy to generate a JUnit XML test result document withtype checking results. This can make it easier to integrate mypywith continuous integration (CI) tools.
boolean
False
Makes scriptx
become modulex
instead of__main__
. This isuseful when checking multiple scripts in a single run.
boolean
False
Warns about per-module sections in the config file that do notmatch any files processed when invoking mypy.(This requires turning off incremental mode usingincremental=False
.)
integer
0
Controls how much debug output will be generated. Higher numbers are more verbose.
Instead of using amypy.ini
file, apyproject.toml
file (as specified byPEP 518) may be used instead. A few notes on doing so:
The[mypy]
section should havetool.
prepended to its name:
I.e.,[mypy]
would become[tool.mypy]
The module specific sections should be moved into[[tool.mypy.overrides]]
sections:
For example,[mypy-packagename]
would become:
[[tool.mypy.overrides]]module='packagename'...
Multi-module specific sections can be moved into a single[[tool.mypy.overrides]]
section with amodule property set to an array of modules:
For example,[mypy-packagename,packagename2]
would become:
[[tool.mypy.overrides]]module=['packagename','packagename2']...
The following care should be given to values in thepyproject.toml
files as compared toini
files:
Strings must be wrapped in double quotes, or single quotes if the string contains special characters
Boolean values should be all lower case
Please see theTOML Documentation for more details and information onwhat is allowed in atoml
file. SeePEP 518 for more information on the layoutand structure of thepyproject.toml
file.
pyproject.toml
¶Here is an example of apyproject.toml
file. To use this config file, place it at the rootof your repo (or append it to the end of an existingpyproject.toml
file) and run mypy.
# mypy global options:[tool.mypy]python_version="3.9"warn_return_any=truewarn_unused_configs=trueexclude=['^file1\.py$',# TOML literal string (single-quotes, no escaping necessary)"^file2\\.py$",# TOML basic string (double-quotes, backslash and other characters need escaping)]# mypy per-module options:[[tool.mypy.overrides]]module="mycode.foo.*"disallow_untyped_defs=true[[tool.mypy.overrides]]module="mycode.bar"warn_return_any=false[[tool.mypy.overrides]]module=["somelibrary","some_other_library"]ignore_missing_imports=true
mypy.ini
pyproject.toml