Skip to content
Commits on Source (6)
......@@ -4,7 +4,7 @@ recursive-include extensions *
recursive-include docs *
recursive-include mypy/typeshed *.py *.pyi
recursive-include mypy/xml *.xsd *.xslt *.css
recursive-include mypyc/lib-rt *.c *.h
recursive-include mypyc/lib-rt *.c *.h *.tmpl
include mypy_bootstrap.ini
include mypy_self_check.ini
include LICENSE
Metadata-Version: 2.1
Name: mypy
Version: 0.740
Version: 0.750
Summary: Optional static typing for Python
Home-page: http://www.mypy-lang.org/
Author: Jukka Lehtosalo
......@@ -25,6 +25,7 @@ Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Topic :: Software Development
Requires-Python: >=3.5
Provides-Extra: dmypy
......@@ -110,11 +110,16 @@ IDE, Linter Integrations, and Pre-commit
Mypy can be integrated into popular IDEs:
* Vim: [syntastic](https://github.com/vim-syntastic/syntastic) in `.vimrc` add `let g:syntastic_python_checkers=['mypy']`
* Vim:
* Using [Syntastic](https://github.com/vim-syntastic/syntastic): in `~/.vimrc` add
`let g:syntastic_python_checkers=['mypy']`
* Using [ALE](https://github.com/dense-analysis/ale): should be enabled by default when `mypy` is installed,
or can be explicitly enabled by adding `let b:ale_linters = ['mypy']` in `~/vim/ftplugin/python.vim`
* Emacs: using [Flycheck](https://github.com/flycheck/) and [Flycheck-mypy](https://github.com/lbolla/emacs-flycheck-mypy)
* Sublime Text: [SublimeLinter-contrib-mypy](https://github.com/fredcallaway/SublimeLinter-contrib-mypy)
* Atom: [linter-mypy](https://atom.io/packages/linter-mypy)
* PyCharm: [mypy plugin](https://github.com/dropbox/mypy-PyCharm-plugin) (PyCharm integrates [its own implementation of PEP 484](https://www.jetbrains.com/help/pycharm/type-hinting-in-product.html))
* PyCharm: [mypy plugin](https://github.com/dropbox/mypy-PyCharm-plugin) (PyCharm integrates
[its own implementation of PEP 484](https://www.jetbrains.com/help/pycharm/type-hinting-in-product.html))
* VS Code: provides [basic integration](https://code.visualstudio.com/docs/python/linting#_mypy) with mypy.
Mypy can also be integrated into [Flake8] using [flake8-mypy], or
......@@ -264,7 +269,7 @@ in the typing gitter instead: https://gitter.im/python/typing
Compiled version of mypy
------------------------
We have built an compiled version of mypy using the [mypyc
We have built a compiled version of mypy using the [mypyc
compiler](https://github.com/python/mypy/tree/master/mypyc) for
mypy-annotated Python code. It is approximately 4 times faster than
interpreted mypy and is available (and the default) for 64-bit
......
mypy (0.740-7) UNRELEASED; urgency=low
mypy (0.750-1) unstable; urgency=low
* Give up trying to build on the alpha architecture, switch to pure Python
there.
* Demote riscv64 to -O1 and m68k to -O0
* Prepare for coming Python3.8 transition and run the tests using all
installed Python versions.
* New upstream version
* debian/patches/stubgen-fix.patch: Pull a fix from upstream
-- Michael R. Crusoe <michael.crusoe@gmail.com> Wed, 30 Oct 2019 09:59:41 +0100
-- Michael R. Crusoe <michael.crusoe@gmail.com> Sun, 01 Dec 2019 13:00:56 +0100
mypy (0.740-6) unstable; urgency=medium
......
......@@ -9,7 +9,7 @@ https://github.com/python/mypy/blob/master/mypyc/doc/dev-intro.md
So it doesn't sound ready for general release yet
--- mypy.orig/setup.py
+++ mypy/setup.py
@@ -181,7 +181,6 @@
@@ -182,7 +182,6 @@
'mypyc', 'mypyc.test',
],
package_data={'mypy': package_data},
......
......@@ -2,7 +2,7 @@ Author: Michael R. Crusoe <michael.crusoe@gmail.com>
Description: Add file from upstream missing from their sdist
--- /dev/null
+++ mypy/misc/proper_plugin.py
@@ -0,0 +1,131 @@
@@ -0,0 +1,137 @@
+from mypy.plugin import Plugin, FunctionContext
+from mypy.types import (
+ Type, Instance, CallableType, UnionType, get_proper_type, ProperType,
......@@ -47,29 +47,35 @@ Description: Add file from upstream missing from their sdist
+ return ctx.default_return_type
+ ctx.api.fail('Never apply isinstance() to unexpanded types;'
+ ' use mypy.types.get_proper_type() first', ctx.context)
+ ctx.api.note('If you pass on the original type' # type: ignore[attr-defined]
+ ' after the check, always use its unexpanded version', ctx.context)
+ return ctx.default_return_type
+
+
+def is_special_target(right: ProperType) -> bool:
+ """Whitelist some special cases for use in isinstance() with improper types."""
+ if isinstance(right, CallableType) and right.is_type_obj():
+ if right.type_object().fullname() == 'builtins.tuple':
+ if right.type_object().fullname == 'builtins.tuple':
+ # Used with Union[Type, Tuple[Type, ...]].
+ return True
+ if right.type_object().fullname() in ('mypy.types.Type',
+ 'mypy.types.ProperType',
+ 'mypy.types.TypeAliasType'):
+ if right.type_object().fullname in (
+ 'mypy.types.Type',
+ 'mypy.types.ProperType',
+ 'mypy.types.TypeAliasType'
+ ):
+ # Special case: things like assert isinstance(typ, ProperType) are always OK.
+ return True
+ if right.type_object().fullname() in ('mypy.types.UnboundType',
+ 'mypy.types.TypeVarType',
+ 'mypy.types.RawExpressionType',
+ 'mypy.types.EllipsisType',
+ 'mypy.types.StarType',
+ 'mypy.types.TypeList',
+ 'mypy.types.CallableArgument',
+ 'mypy.types.PartialType',
+ 'mypy.types.ErasedType'):
+ if right.type_object().fullname in (
+ 'mypy.types.UnboundType',
+ 'mypy.types.TypeVarType',
+ 'mypy.types.RawExpressionType',
+ 'mypy.types.EllipsisType',
+ 'mypy.types.StarType',
+ 'mypy.types.TypeList',
+ 'mypy.types.CallableArgument',
+ 'mypy.types.PartialType',
+ 'mypy.types.ErasedType'
+ ):
+ # Special case: these are not valid targets for a type alias and thus safe.
+ # TODO: introduce a SyntheticType base to simplify this?
+ return True
......
ignore_mypyc
proper_plugin
spelling
verbose
stubgen-fix.patch
From: Michael R. Crusoe <michael.crusoe@gmail.com>
Subject: Fix typos found by Debian's Lintian program
--- mypy.orig/mypy/metastore.py
+++ mypy/mypy/metastore.py
@@ -47,7 +47,7 @@
If mtime is specified, set it as the mtime of the entry. Otherwise,
the current time is used.
- Returns True if the entry is succesfully written, False otherwise.
+ Returns True if the entry is successfully written, False otherwise.
"""
@abstractmethod
--- mypy.orig/mypy/plugin.py
+++ mypy/mypy/plugin.py
@@ -154,7 +154,7 @@
@abstractmethod
def fail(self, msg: str, ctx: Context, *, code: Optional[ErrorCode] = None) -> None:
- """Emmit an error message at given location."""
+ """Emit an error message at given location."""
raise NotImplementedError
@abstractmethod
@@ -257,7 +257,7 @@
@abstractmethod
def fail(self, msg: str, ctx: Context, serious: bool = False, *,
blocker: bool = False, code: Optional[ErrorCode] = None) -> None:
- """Emmit an error message at given location."""
+ """Emit an error message at given location."""
raise NotImplementedError
@abstractmethod
@@ -634,7 +634,7 @@
) -> Optional[Callable[[DynamicClassDefContext], None]]:
"""Semantically analyze a dynamic class definition.
- This plugin hook allows to semantically analyze dynamic class definitions like:
+ This plugin hook allows one to semantically analyze dynamic class definitions like:
from lib import dynamic_class
--- mypy.orig/mypyc/emitmodule.py
+++ mypy/mypyc/emitmodule.py
@@ -377,7 +377,7 @@
# Store the module reference in a static and return it when necessary.
# This is separate from the *global* reference to the module that will
# be populated when it is imported by a compiled module. We want that
- # reference to only be populated when the module has been succesfully
+ # reference to only be populated when the module has been successfully
# imported, whereas this we want to have to stop a circular import.
module_static = self.module_internal_static_name(module_name, emitter)
--- mypy.orig/mypy/options.py
+++ mypy/mypy/options.py
@@ -262,7 +262,7 @@
# Don't properly free objects on exit, just kill the current process.
self.fast_exit = False
- # To avoid breaking plugin compatability, keep providing new_semantic_analyzer
+ # To avoid breaking plugin compatibility, keep providing new_semantic_analyzer
@property
def new_semantic_analyzer(self) -> bool:
return True
--- mypy.orig/mypyc/build.py
+++ mypy/mypyc/build.py
@@ -385,7 +385,7 @@
return extensions
-# For backwards compatability we define this as an alias. Previous
+# For backwards compatibility we define this as an alias. Previous
# versions used to require using it, and it is conceivable that future
# versions will need it also.
MypycifyBuildExt = build_ext
--- mypy.orig/mypyc/emit.py
+++ mypy/mypyc/emit.py
@@ -287,7 +287,7 @@
Somewhat strangely, this supports unboxed types but only
operates on boxed versions. This is necessary to properly
- handle types such as Optional[int] in compatability glue.
+ handle types such as Optional[int] in compatibility glue.
Assign NULL (error value) to dest if the value has an incompatible type.
--- mypy.orig/mypy/fscache.py
+++ mypy/mypy/fscache.py
@@ -201,7 +201,7 @@
else:
try:
names = self.listdir(head)
- # This allows to check file name case sensitively in
+ # This allows one to check file name case sensitively in
# case-insensitive filesystems.
res = tail in names and self.isfile(path)
except OSError:
--- mypy.orig/mypy/typeshed/stdlib/2and3/decimal.pyi
+++ mypy/mypy/typeshed/stdlib/2and3/decimal.pyi
@@ -234,7 +234,7 @@
capitals: Optional[int] = ..., _clamp: Optional[int] = ...,
_ignored_flags: Optional[List[_TrapType]] = ...) -> None: ...
if sys.version_info >= (3,):
- # __setattr__() only allows to set a specific set of attributes,
+ # __setattr__() only allows one to set a specific set of attributes,
# already defined above.
def __delattr__(self, name: str) -> None: ...
def __reduce__(self) -> Tuple[Type[Context], Tuple[Any, ...]]: ...
--- mypy.orig/mypyc/genops.py
+++ mypy/mypyc/genops.py
@@ -1603,7 +1603,7 @@
class A:
def f(self, x: int) -> object: ...
- then it is totally permissable to have a subclass
+ then it is totally permissible to have a subclass
class B(A):
def f(self, x: object) -> int: ...
--- mypy.orig/mypyc/namegen.py
+++ mypy/mypyc/namegen.py
@@ -42,7 +42,7 @@
"""Initialize with names of all modules in the compilation unit.
The names of modules are used to shorten names referring to
- modules in the compilation unit, for convenience. Arbitary module
+ modules in the compilation unit, for convenience. Arbitrary module
names are supported for generated names, but modules not in the
compilation unit will use long names.
"""
Origin: https://github.com/python/mypy/pull/8003
Applied-Upstream: commit:https://github.com/python/mypy/pull/8003/commits/7f0b1ac239512e90d9f4f7700b1ffccac78f203d
From: "Michael J. Sullivan" <sully@msully.net>
Date: Fri, 22 Nov 2019 15:12:24 -0800
Subject: [PATCH] Remove a semi-broken stubgen assert
C modules in the standard library don't seem to have a __file__ in
the Python distributions that ship with Ubuntu. I think maybe they
are built into the binary? I don't know.
---
mypy/test/teststubgen.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/mypy/test/teststubgen.py b/mypy/test/teststubgen.py
index 6a1a287943..e77c83070b 100644
--- a/mypy/test/teststubgen.py
+++ b/mypy/test/teststubgen.py
@@ -861,7 +861,6 @@ def test_c_module(self) -> None:
p = m.get_package_properties('_socket')
assert p is not None
assert p.name == '_socket'
- assert p.file
assert p.path is None
assert p.is_c_module is True
assert p.subpackages == []
......@@ -2,11 +2,11 @@ Author: Michael R. Crusoe <michael.crusoe@gmail.com>
Description: make the build more verbose
--- mypy.orig/setup.py
+++ mypy/setup.py
@@ -148,6 +148,7 @@
@@ -149,6 +149,7 @@
# Use multi-file compliation mode on windows because without it
# our Appveyor builds run out of memory sometimes.
multi_file=sys.platform == 'win32' or force_multifile,
+ verbose=True,
)
cmdclass['build_ext'] = MypycifyBuildExt
else:
ext_modules = []
......@@ -286,7 +286,7 @@ run after starting or restarting the daemon.
The mypy daemon requires extra fine-grained dependency data in
the cache files which aren't included by default. To use caching with
the mypy daemon, use the ``--cache-fine-grained`` option in your CI
the mypy daemon, use the :option:`--cache-fine-grained <mypy --cache-fine-grained>` option in your CI
build::
$ mypy --cache-fine-grained <args...>
......@@ -326,7 +326,7 @@ at least if your codebase is hundreds of thousands of lines or more:
network), the script can still fall back to a normal incremental build.
* You can have multiple local cache directories for different local branches
using the ``--cache-dir`` option. If the user switches to an existing
using the :option:`--cache-dir <mypy --cache-dir>` option. If the user switches to an existing
branch where downloaded cache data is already available, you can continue
to use the existing cache data instead of redownloading the data.
......
......@@ -78,8 +78,8 @@ to it explicitly using ``self``:
a = self
a.x = 1 # Error: 'x' not defined
Annotating ``__init__`` methods
*******************************
Annotating __init__ methods
***************************
The :py:meth:`__init__ <object.__init__>` method is somewhat special -- it doesn't return a
value. This is best expressed as ``-> None``. However, since many feel
......
This diff is collapsed.
......@@ -31,7 +31,7 @@ flagged as an error.
return type) are not type-checked, and even the most blatant type
errors (e.g. ``2 + 'a'``) pass silently. The solution is to add
annotations. Where that isn't possible, functions without annotations
can be checked using ``--check-untyped-defs``.
can be checked using :option:`--check-untyped-defs <mypy --check-untyped-defs>`.
Example:
......@@ -73,17 +73,17 @@ flagged as an error.
<https://github.com/python/typeshed/issues/285>`_ for the reason).
- **Some imports may be silently ignored**. Another source of
unexpected ``Any`` values are the :ref:`"--ignore-missing-imports"
<ignore-missing-imports>` and :ref:`"--follow-imports=skip"
<follow-imports>` flags. When you use ``--ignore-missing-imports``,
unexpected ``Any`` values are the :option:`--ignore-missing-imports
<mypy --ignore-missing-imports>` and :option:`--follow-imports=skip
<mypy --follow-imports>` flags. When you use :option:`--ignore-missing-imports <mypy --ignore-missing-imports>`,
any imported module that cannot be found is silently replaced with
``Any``. When using ``--follow-imports=skip`` the same is true for
``Any``. When using :option:`--follow-imports=skip <mypy --follow-imports>` the same is true for
modules for which a ``.py`` file is found but that are not specified
on the command line. (If a ``.pyi`` stub is found it is always
processed normally, regardless of the value of
``--follow-imports``.) To help debug the former situation (no
module found at all) leave out ``--ignore-missing-imports``; to get
clarity about the latter use ``--follow-imports=error``. You can
:option:`--follow-imports <mypy --follow-imports>`.) To help debug the former situation (no
module found at all) leave out :option:`--ignore-missing-imports <mypy --ignore-missing-imports>`; to get
clarity about the latter use :option:`--follow-imports=error <mypy --follow-imports>`. You can
read up about these and other useful flags in :ref:`command-line`.
- **A function annotated as returning a non-optional type returns 'None'
......@@ -418,7 +418,7 @@ Example:
Some other expressions exhibit similar behavior; in particular,
:py:data:`~typing.TYPE_CHECKING`, variables named ``MYPY``, and any variable
whose name is passed to ``--always-true`` or ``--always-false``.
whose name is passed to :option:`--always-true <mypy --always-true>` or :option:`--always-false <mypy --always-false>`.
(However, ``True`` and ``False`` are not treated specially!)
.. note::
......@@ -431,14 +431,14 @@ By default, mypy will use your current version of Python and your current
operating system as default values for ``sys.version_info`` and
``sys.platform``.
To target a different Python version, use the ``--python-version X.Y`` flag.
To target a different Python version, use the :option:`--python-version X.Y <mypy --python-version>` flag.
For example, to verify your code typechecks if were run using Python 2, pass
in ``--python-version 2.7`` from the command line. Note that you do not need
in :option:`--python-version 2.7 <mypy --python-version>` from the command line. Note that you do not need
to have Python 2.7 installed to perform this check.
To target a different operating system, use the ``--platform PLATFORM`` flag.
To target a different operating system, use the :option:`--platform PLATFORM <mypy --platform>` flag.
For example, to verify your code typechecks if it were run in Windows, pass
in ``--platform win32``. See the documentation for :py:data:`sys.platform`
in :option:`--platform win32 <mypy --platform>`. See the documentation for :py:data:`sys.platform`
for examples of valid platform parameters.
.. _reveal-type:
......@@ -533,6 +533,7 @@ Here's the above example modified to use ``MYPY``:
def listify(arg: 'bar.BarClass') -> 'List[bar.BarClass]':
return [arg]
.. _not-generic-runtime:
Using classes that are generic in stubs but not at runtime
----------------------------------------------------------
......@@ -568,6 +569,15 @@ string literal types or :py:data:`~typing.TYPE_CHECKING`:
results: 'Queue[int]' = Queue() # OK
If you are running Python 3.7+ you can use ``from __future__ import annotations``
as a (nicer) alternative to string quotes, read more in :pep:`563`. For example:
.. code-block:: python
from __future__ import annotations
from queue import Queue
results: Queue[int] = Queue() # This works at runtime
.. _silencing-linters:
......
......@@ -273,4 +273,5 @@ intersphinx_mapping = {
'attrs': ('http://www.attrs.org/en/stable', None),
'cython': ('http://docs.cython.org/en/latest', None),
'monkeytype': ('https://monkeytype.readthedocs.io/en/latest', None),
'setuptools': ('https://setuptools.readthedocs.io/en/latest', None),
}
......@@ -7,11 +7,11 @@ Mypy supports reading configuration settings from a file. By default
it uses the file ``mypy.ini`` with fallback to ``setup.cfg`` in the current
directory, then ``$XDG_CONFIG_HOME/mypy/config``, then
``~/.config/mypy/config``, and finally ``.mypy.ini`` in the user home directory
if none of them are found; the ``--config-file`` command-line flag can be used
to read a different file instead (see :ref:`--config-file <config-file-flag>`).
if none of them are found; the :option:`--config-file <mypy --config-file>` command-line flag can be used
to read a different file instead (see :ref:`config-file-flag`).
It is important to understand that there is no merging of configuration
files, as it would lead to ambiguity. The ``--config-file`` flag
files, as it would lead to ambiguity. The :option:`--config-file <mypy --config-file>` flag
has the highest precedence and must be correct; otherwise mypy will report
an error and exit. Without command line option, mypy will look for defaults,
but will use only one of them. The first one to read is ``mypy.ini``,
......@@ -25,6 +25,7 @@ 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}``.
Config file format
******************
......@@ -80,6 +81,29 @@ unfortunate, and is subject to change in future versions.
Configuration flags are liable to change between releases.
Per-module and global options
*****************************
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 configuration
options take precedence. This lets you set global defaults and override them on a
module-by-module basis. If multiple pattern sections match a module, :ref:`the options from the
most specific section are used where they disagree <config-precedence>`.
Some other options, as specified in their description,
may only be set in the global section (``[mypy]``).
Inverting option values
***********************
Options that take a boolean value may be inverted by adding ``no_`` to
their name or by (when applicable) swapping their prefix from
``disallow`` to ``allow`` (and vice versa).
Examples
********
......@@ -110,7 +134,7 @@ This config file specifies three global options in the ``[mypy]`` section. These
options will:
1. Type-check your entire project assuming it will be run using Python 2.7.
(This is equivalent to using the ``--python-version 2.7`` or ``--2`` flag).
(This is equivalent to using the :option:`--python-version 2.7 <mypy --python-version>` or :option:`-2 <mypy -2>` flag).
2. Report an error whenever a function returns a value that is inferred
to have type ``Any``.
......@@ -134,34 +158,38 @@ assume here is some 3rd party library you've installed and are importing. These
module ``somelibrary``. This is useful if ``somelibrary`` is some 3rd party library
missing type hints.
.. _per-module-flags:
Per-module and global options
*****************************
.. _config-file-import-discovery:
The following config options may be set either globally (in the ``[mypy]`` section)
or on a per-module basis (in sections like ``[mypy-foo.bar]``).
Import discovery
****************
If you set an option both globally and for a specific module, the module configuration
options take precedence. This lets you set global defaults and override them on a
module-by-module basis. If multiple pattern sections match a module, :ref:`the options from the
most specific section are used where they disagree <config-precedence>`.
For more information, see the :ref:`Import discovery <import-discovery>`
section of the command line docs.
Options that take a boolean value may be inverted by adding ``no_`` to
their name or by (when applicable) swapping their prefix from
``disallow`` to ``allow`` (and vice versa).
``mypy_path`` (string)
Specifies the paths to use, after trying the paths from ``MYPYPATH`` environment
variable. 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.
.. _config-file-import-discovery-per-module:
This option may only be set in the global section (``[mypy]``).
Import discovery
----------------
**Note:** On Windows, use UNC paths to avoid using ``:`` (e.g. ``\\127.0.0.1\X$\MyDir`` where ``X`` is the drive letter).
``files`` (comma-separated list of strings)
A comma-separated list of paths which should be checked by mypy if none are given on the command
line. Supports recursive file globbing using :py:mod:`glob`, where ``*`` (e.g. ``*.py``) matches
files in the current directory and ``**/`` (e.g. ``**/*.py``) matches files in any directories below
the current one. User home directory and environment variables will be expanded.
For more information, see the :ref:`import discovery <import-discovery>`
section of the command line docs.
This option may only be set in the global section (``[mypy]``).
``namespace_packages`` (bool, default False)
Enables :pep:`420` style namespace packages. See :ref:`the
corresponding flag <import-discovery>` for more information.
Note: this section describes options that can be used both globally and per-module.
See below for a list of import discovery options that may be used
:ref:`only globally <config-file-import-discovery-global>`.
This option may only be set in the global section (``[mypy]``).
``ignore_missing_imports`` (bool, default False)
Suppresses error messages about imports that cannot be resolved.
......@@ -194,10 +222,54 @@ See below for a list of import discovery options that may be used
Used in conjunction with ``follow_imports=error``, this can be used
to make any use of a particular ``typeshed`` module an error.
``python_executable`` (string)
Specifies the path to the Python executable to inspect to collect
a list of available :ref:`PEP 561 packages <installed-packages>`. User
home directory and environment variables will be expanded. Defaults to
the executable used to run mypy.
This option may only be set in the global section (``[mypy]``).
``no_silence_site_packages`` (bool, default False)
Enables reporting error messages generated within :pep:`561` compliant packages.
Those error messages are suppressed by default, since you are usually
not able to control errors in 3rd party code.
This option may only be set in the global section (``[mypy]``).
Platform configuration
**********************
``python_version`` (string)
Specifies the Python version used to parse and check the target
program. The string should be in the format ``DIGIT.DIGIT`` --
for example ``2.7``. The default is the version of the Python
interpreter used to run mypy.
This option may only be set in the global section (``[mypy]``).
``platform`` (string)
Specifies the OS platform for the target program, for example
``darwin`` or ``win32`` (meaning OS X or Windows, respectively).
The default is the current platform as revealed by Python's
:py:data:`sys.platform` variable.
This option may only be set in the global section (``[mypy]``).
``always_true`` (comma-separated list of strings)
Specifies a list of variables that mypy will treat as
compile-time constants that are always true.
``always_false`` (comma-separated list of strings)
Specifies a list of variables that mypy will treat as
compile-time constants that are always false.
Disallow dynamic typing
-----------------------
***********************
For more information, see the :ref:`disallowing dynamic typing <disallow-dynamic-typing>`
For more information, see the :ref:`Disallow dynamic typing <disallow-dynamic-typing>`
section of the command line docs.
``disallow_any_unimported`` (bool, default False)
......@@ -222,9 +294,9 @@ section of the command line docs.
Untyped definitions and calls
-----------------------------
*****************************
For more information, see the :ref:`untyped definitions and calls <untyped-definitions-and-calls>`
For more information, see the :ref:`Untyped definitions and calls <untyped-definitions-and-calls>`
section of the command line docs.
``disallow_untyped_calls`` (bool, default False)
......@@ -245,12 +317,13 @@ section of the command line docs.
Reports an error whenever a function with type annotations is decorated with a
decorator without annotations.
.. _config-file-none-and-optional-handling:
None and optional handling
--------------------------
None and Optional handling
**************************
For more information, see the :ref:`None and optional handling <none-and-optional-handling>`
For more information, see the :ref:`None and Optional handling <none-and-optional-handling>`
section of the command line docs.
``no_implicit_optional`` (bool, default False)
......@@ -265,11 +338,16 @@ section of the command line docs.
Configuring warnings
--------------------
********************
For more information, see the :ref:`configuring warnings <configuring-warnings>`
For more information, see the :ref:`Configuring warnings <configuring-warnings>`
section of the command line docs.
``warn_redundant_casts`` (bool, default False)
Warns about casting an expression to its inferred type.
This option may only be set in the global section (``[mypy]``).
``warn_unused_ignores`` (bool, default False)
Warns about unneeded ``# type: ignore`` comments.
......@@ -284,10 +362,9 @@ section of the command line docs.
Shows a warning when encountering any code inferred to be unreachable or
redundant after performing type analysis.
.. _config-file-suppressing-errors:
Suppressing errors
------------------
******************
Note: these configuration options are available in the config file only. There is
no analog available via the command line options.
......@@ -299,8 +376,13 @@ no analog available via the command line options.
``ignore_errors`` (bool, default False)
Ignores all non-fatal errors.
Miscellaneous strictness flags
------------------------------
******************************
``allow_untyped_globals`` (bool, default False)
Causes mypy to suppress errors caused by not being able to fully
infer the types of global and class variables.
``allow_redefinition`` (bool, default False)
Allows variables to be redefined with an arbitrary type, as long as the redefinition
......@@ -326,88 +408,42 @@ Miscellaneous strictness flags
Prohibit equality checks, identity checks, and container checks between
non-overlapping types.
Platform configuration
----------------------
``always_true`` (comma-separated list of strings)
Specifies a list of variables that mypy will treat as
compile-time constants that are always true.
``always_false`` (comma-separated list of strings)
Specifies a list of variables that mypy will treat as
compile-time constants that are always false.
Global-only options
*******************
The following options may only be set in the global section (``[mypy]``).
.. _config-file-import-discovery-global:
Import discovery
----------------
Configuring error messages
**************************
For more information, see the :ref:`import discovery <import-discovery>`
For more information, see the :ref:`Configuring error messages <configuring-error-messages>`
section of the command line docs.
Note: this section describes only global-only import discovery options. See above for
a list of import discovery options that may be used
:ref:`both per-module and globally <config-file-import-discovery-per-module>`.
``namespace_packages`` (bool, default False)
Enables :pep:`420` style namespace packages. See :ref:`the
corresponding flag <import-discovery>` for more information.
``python_executable`` (string)
Specifies the path to the Python executable to inspect to collect
a list of available :ref:`PEP 561 packages <installed-packages>`. User
home directory and environment variables will be expanded. Defaults to
the executable used to run mypy.
``no_silence_site_packages`` (bool, default False)
Enables reporting error messages generated within :pep:`561` compliant packages.
Those error messages are suppressed by default, since you are usually
not able to control errors in 3rd party code.
``mypy_path`` (string)
Specifies the paths to use, after trying the paths from ``MYPYPATH`` environment
variable. 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.
These options may only be set in the global section (``[mypy]``).
``files`` (string)
``show_error_context`` (bool, default False)
Prefixes each error with the relevant context.
A comma-separated list of paths which should be checked by mypy if none are given on the command
line. Supports recursive file globbing using :py:mod:`glob`, where ``*`` (e.g. ``*.py``) matches
files in the current directory and ``**/`` (e.g. ``**/*.py``) matches files in any directories below
the current one. User home directory and environment variables will be expanded.
``show_column_numbers`` (bool, default False)
Shows column numbers in error messages.
``show_error_codes`` (bool, default False)
Shows error codes in error messages. See :ref:`error-codes` for more information.
Platform configuration
----------------------
``pretty`` (bool, default False)
Use visually nicer output in error messages: use soft word wrap,
show source code snippets, and show error location markers.
For more information, see the :ref:`platform configuration <platform-configuration>`
section of the command line docs.
``color_output`` (bool, default True)
Shows error messages with color enabled.
``python_version`` (string)
Specifies the Python version used to parse and check the target
program. The string should be in the format ``DIGIT.DIGIT`` --
for example ``2.7``. The default is the version of the Python
interpreter used to run mypy.
``error_summary`` (bool, default True)
Shows a short summary line after error messages.
``platform`` (string)
Specifies the OS platform for the target program, for example
``darwin`` or ``win32`` (meaning OS X or Windows, respectively).
The default is the current platform as revealed by Python's
:py:data:`sys.platform` variable.
``show_absolute_path`` (bool, default False)
Show absolute paths to files.
Incremental mode
----------------
****************
For more information, see the :ref:`incremental mode <incremental>`
section of the command line docs.
These options may only be set in the global section (``[mypy]``).
``incremental`` (bool, default True)
Enables :ref:`incremental mode <incremental>`.
......@@ -422,39 +458,25 @@ section of the command line docs.
but is always written to, unless the value is set to ``/dev/null``
(UNIX) or ``nul`` (Windows).
``sqlite_cache`` (bool, default False)
Use an `SQLite`_ database to store the cache.
``cache_fine_grained`` (bool, default False)
Include fine-grained dependency information in the cache for the mypy daemon.
``skip_version_check`` (bool, default False)
Makes mypy use incremental cache data even if it was generated by a
different version of mypy. (By default, mypy will perform a version
check and regenerate the cache if it was written by older versions of mypy.)
Configuring error messages
--------------------------
For more information, see the :ref:`configuring error messages <configuring-error-messages>`
section of the command line docs.
``show_error_context`` (bool, default False)
Prefixes each error with the relevant context.
``show_column_numbers`` (bool, default False)
Shows column numbers in error messages.
``show_error_codes`` (bool, default False)
Shows error codes in error messages. See :ref:`error-codes` for more information.
``color_output`` (bool, default True)
Shows error messages with color enabled.
``error_summary`` (bool, default True)
Shows a short summary line after error messages.
``skip_cache_mtime_checks`` (bool, default False)
Skip cache internal consistency checks based on mtime.
Advanced options
----------------
****************
For more information, see the :ref:`advanced flags <advanced-flags>`
section of the command line docs.
These options may only be set in the global section (``[mypy]``).
``pdb`` (bool, default False)
Invokes pdb on fatal error.
......@@ -462,6 +484,9 @@ section of the command line docs.
``show_traceback`` (bool, default False)
Shows traceback on fatal error.
``raise_exceptions`` (bool, default False)
Raise exception on fatal error.
``custom_typing_module`` (string)
Specifies a custom module to use as a substitute for the :py:mod:`typing` module.
......@@ -475,11 +500,59 @@ section of the command line docs.
in combination with ``disallow_untyped_defs`` or ``disallow_incomplete_defs``.
Report generation
*****************
If these options are set, mypy will generate a report in the specified
format into the specified directory.
``any_exprs_report`` (string)
Causes mypy to generate a text file report documenting how many
expressions of type ``Any`` are present within your codebase.
``cobertura_xml_report`` (string)
Causes mypy to generate a Cobertura XML type checking coverage report.
You must install the `lxml`_ library to generate this report.
``html_report`` / ``xslt_html_report`` (string)
Causes mypy to generate an HTML type checking coverage report.
You must install the `lxml`_ library to generate this report.
``linecount_report`` (string)
Causes mypy to generate a text file report documenting the functions
and lines that are typed and untyped within your codebase.
``linecoverage_report`` (string)
Causes mypy to generate a JSON file that maps each source file's
absolute filename to a list of line numbers that belong to typed
functions in that file.
``lineprecision_report`` (string)
Causes mypy to generate a flat text file report with per-module
statistics of how many lines are typechecked etc.
``txt_report`` / ``xslt_txt_report`` (string)
Causes mypy to generate a text file type checking coverage report.
You must install the `lxml`_ library to generate this report.
``xml_report`` (string)
Causes mypy to generate an XML type checking coverage report.
You must install the `lxml`_ library to generate this report.
Miscellaneous
-------------
*************
``warn_redundant_casts`` (bool, default False)
Warns about casting an expression to its inferred type.
These options may only be set in the global section (``[mypy]``).
``junit_xml`` (string)
Causes mypy to generate a JUnit XML test result document with
type checking results. This can make it easier to integrate mypy
with continuous integration (CI) tools.
``scripts_are_modules`` (bool, default False)
Makes script ``x`` become module ``x`` instead of ``__main__``. This is
......@@ -493,6 +566,5 @@ Miscellaneous
``verbosity`` (integer, default 0)
Controls how much debug output will be generated. Higher numbers are more verbose.
``new_semantic_analyzer`` (bool, default True)
Enables the new, improved, semantic analyzer.
(See :ref:`The mypy command line <command-line>` for more information.)
.. _lxml: https://pypi.org/project/lxml/
.. _SQLite: https://www.sqlite.org/
......@@ -83,7 +83,7 @@ definition in an active scope, such as an assignment, function
definition or an import. This can catch missing definitions, missing
imports, and typos.
This example accidentally calls ``sort()`` instead of ``sorted()``:
This example accidentally calls ``sort()`` instead of :py:func:`sorted`:
.. code-block:: python
......@@ -181,7 +181,7 @@ This example incorrectly uses the function ``log`` as a type:
for x in objs:
f(x)
You can use ``Callable`` as the type for callable objects:
You can use :py:data:`~typing.Callable` as the type for callable objects:
.. code-block:: python
......@@ -418,8 +418,8 @@ Example:
Check TypedDict items [typeddict-item]
--------------------------------------
When constructing a TypedDict object, mypy checks that each key and value is compatible
with the TypedDict type that is inferred from the surrounding context.
When constructing a ``TypedDict`` object, mypy checks that each key and value is compatible
with the ``TypedDict`` type that is inferred from the surrounding context.
Example:
......@@ -484,7 +484,7 @@ Example:
.. code-block:: python
# Error: Cannot find module named 'acme' [import]
# Error: Cannot find implementation or library stub for module named 'acme' [import]
import acme
See :ref:`ignore-missing-imports` for how to work around these errors.
......@@ -542,8 +542,7 @@ Check instantiation of abstract classes [abstract]
Mypy generates an error if you try to instantiate an abstract base
class (ABC). An abtract base class is a class with at least one
abstract method or attribute. (See also :doc:`Python
abc module documentation <python:library/abc>`)
abstract method or attribute. (See also :py:mod:`abc` module documentation)
Sometimes a class is made accidentally abstract, often due to an
unimplemented abstract method. In a case like this you need to provide
......@@ -572,7 +571,7 @@ Example:
Check the target of NewType [valid-newtype]
-------------------------------------------
The target of a ``NewType`` definition must be a class type. It can't
The target of a :py:func:`NewType <typing.NewType>` definition must be a class type. It can't
be a union type, ``Any``, or various other special types.
You can also get this error if the target has been imported from a
......@@ -596,10 +595,10 @@ for more information.
Check the return type of __exit__ [exit-return]
-----------------------------------------------
If mypy can determine that ``__exit__`` always returns ``False``, mypy
If mypy can determine that :py:meth:`__exit__ <object.__exit__>` always returns ``False``, mypy
checks that the return type is *not* ``bool``. The boolean value of
the return type affects which lines mypy thinks are reachable after a
``with`` statement, since any ``__exit__`` method that can return
``with`` statement, since any :py:meth:`__exit__ <object.__exit__>` method that can return
``True`` may swallow exceptions. An imprecise return type can result
in mysterious errors reported near ``with`` statements.
......
......@@ -18,7 +18,7 @@ error codes that are enabled by default.
Check that type arguments exist [type-arg]
------------------------------------------
If you use ``--disallow-any-generics``, mypy requires that each generic
If you use :option:`--disallow-any-generics <mypy --disallow-any-generics>`, mypy requires that each generic
type has values for each type argument. For example, the types ``List`` or
``dict`` would be rejected. You should instead use types like ``List[int]`` or
``Dict[str, int]``. Any omitted generic type arguments get implicit ``Any``
......@@ -39,7 +39,7 @@ Example:
Check that every function has an annotation [no-untyped-def]
------------------------------------------------------------
If you use ``--disallow-untyped-defs``, mypy requires that all functions
If you use :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`, mypy requires that all functions
have annotations (either a Python 3 annotation or a type comment).
Example:
......@@ -67,7 +67,7 @@ Example:
Check that cast is not redundant [redundant-cast]
-------------------------------------------------
If you use ``--warn-redundant-casts``, mypy will generate an error if the source
If you use :option:`--warn-redundant-casts <mypy --warn-redundant-casts>`, mypy will generate an error if the source
type of a cast is the same as the target type.
Example:
......@@ -87,7 +87,7 @@ Example:
Check that comparisons are overlapping [comparison-overlap]
-----------------------------------------------------------
If you use ``--strict-equality``, mypy will generate an error if it
If you use :option:`--strict-equality <mypy --strict-equality>`, mypy will generate an error if it
thinks that a comparison operation is always true or false. These are
often bugs. Sometimes mypy is too picky and the comparison can
actually be useful. Instead of disabling strict equality checking
......@@ -118,7 +118,7 @@ literal:
Check that no untyped functions are called [no-untyped-call]
------------------------------------------------------------
If you use ``--disallow-untyped-calls``, mypy generates an error when you
If you use :option:`--disallow-untyped-calls <mypy --disallow-untyped-calls>`, mypy generates an error when you
call an unannotated function in an annotated function.
Example:
......@@ -138,7 +138,7 @@ Example:
Check that function does not return Any value [no-any-return]
-------------------------------------------------------------
If you use ``--warn-return-any``, mypy generates an error if you return a
If you use :option:`--warn-return-any <mypy --warn-return-any>`, mypy generates an error if you return a
value with an ``Any`` type in a function that is annotated to return a
non-``Any`` value.
......@@ -158,7 +158,7 @@ Example:
Check that types have no Any components due to missing imports [no-any-unimported]
----------------------------------------------------------------------------------
If you use ``--disallow-any-unimported``, mypy generates an error if a component of
If you use :option:`--disallow-any-unimported <mypy --disallow-any-unimported>`, mypy generates an error if a component of
a type becomes ``Any`` because mypy couldn't resolve an import. These "stealth"
``Any`` types can be surprising and accidentally cause imprecise type checking.
......
......@@ -23,7 +23,7 @@ Error codes may change in future mypy releases.
Displaying error codes
----------------------
Error codes are not displayed by default. Use ``--show-error-codes``
Error codes are not displayed by default. Use :option:`--show-error-codes <mypy --show-error-codes>`
to display error codes. Error codes are shown inside square brackets:
.. code-block:: text
......@@ -43,7 +43,7 @@ codes on individual lines using this comment.
.. note::
There are command-line flags and config file settings for enabling
certain optional error codes, such as ``--disallow-untype-defs``,
certain optional error codes, such as :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`,
which enables the ``no-untyped-def`` error code.
This example shows how to ignore an error about an imported name mypy
......
......@@ -42,8 +42,8 @@ find or that don't have stub files:
.. code-block:: text
core/config.py:7: error: Cannot find module named 'frobnicate'
core/model.py:9: error: Cannot find module named 'acme'
core/config.py:7: error: Cannot find implementation or library stub for module named 'frobnicate'
core/model.py:9: error: Cannot find implementation or library stub for module named 'acme'
...
This is normal, and you can easily ignore these errors. For example,
......