Skip to content
Commits on Source (9)
......@@ -4,6 +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
include mypy_bootstrap.ini
include mypy_self_check.ini
include LICENSE
Metadata-Version: 2.1
Name: mypy
Version: 0.730
Version: 0.740
Summary: Optional static typing for Python
Home-page: http://www.mypy-lang.org/
Author: Jukka Lehtosalo
......
mypy (0.740-1) unstable; urgency=medium
* New upstream version
* Set upstream metadata fields: Repository.
* Remove obsolete fields Name from debian/upstream/metadata.
* Build mypy binaries using mypyc.
* Fix typos in upstream sources
-- Michael R. Crusoe <michael.crusoe@gmail.com> Wed, 23 Oct 2019 18:44:56 +0200
mypy (0.730-1) unstable; urgency=medium
* New upstream version
......
......@@ -20,7 +20,8 @@ Build-Depends: debhelper-compat (= 12),
python3-psutil (>= 5.4.0),
python3-mypy-extensions,
python3-typing-extensions,
python3-virtualenv <!nocheck>
python3-virtualenv <!nocheck>,
python3-all-dev
Standards-Version: 4.4.0
Vcs-Browser: https://salsa.debian.org/med-team/mypy
Vcs-Git: https://salsa.debian.org/med-team/mypy.git
......@@ -30,7 +31,7 @@ Package: mypy
Architecture: all
Depends: ${misc:Depends},
${python3:Depends},
python3-mypy (= ${binary:Version})
python3-mypy (>= ${binary:Version})
Suggests: mypy-doc
Description: optional static typing for Python
Add type annotations to your Python programs, and use mypy to type check them.
......@@ -58,10 +59,11 @@ Description: documentation for mypy
Build-Profiles: <!nodoc>
Package: python3-mypy
Architecture: all
Architecture: any
Section: python
Depends: ${misc:Depends},
${python3:Depends},
${shlibs:Depends},
python3-typed-ast,
python3-mypy-extensions,
python3-psutil,
......
......@@ -10,23 +10,6 @@ Files: debian/*
Copyright: © 2016 Michael R. Crusoe <michael.crusoe@gmail.com>
License: Expat
Files: test-data/stdlib-samples/3.2/incomplete/logging/__init__.py
Copyright: 2001-2010 Vinay Sajip
License: other
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Vinay Sajip
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Files: test-data/stdlib-samples/3.2/subprocess.py
Copyright: 2003-2005 Peter Astrand <astrand@lysator.liu.se>
License: Python-2.0
......
ignore_mypyc
proper_plugin
spelling
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.
"""
......@@ -11,11 +11,13 @@ ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES)))
WITH += ,sphinxdoc
endif
export DEB_BUILD_MAINT_OPTIONS=hardening=+all
%:
dh $@ --with python3$(WITH) --buildsystem=pybuild
override_dh_auto_build:
dh_auto_build
export MYPY_USE_MYPYC=1; dh_auto_build
ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES)))
PYTHONPATH=$(PPATH) help2man 'python3 -m mypy' --no-info \
--version-string="${DEB_VERSION_UPSTREAM}" \
......@@ -84,6 +86,7 @@ override_dh_auto_install:
override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_PROFILES)))
export TEST_MYPYC=1
PYBUILD_SYSTEM=custom \
PYBUILD_TEST_ARGS="{interpreter} -m mypy \
--config-file {dir}/mypy_self_check.ini -p mypy" dh_auto_test
......
......@@ -12,6 +12,8 @@ fi
cd "$AUTOPKGTEST_TMP"
export TEST_MYPYC=1
MYPY_TEST_PREFIX=${START} pytest-3 -n auto -o testpaths=mypy/test \
-o python_files=test*.py -o python_classes= -o python_functions= \
--pyarg mypy
......
Name: mypy
Repository: https://github.com/python/mypy
......@@ -9,9 +9,10 @@ of the previous sections.
Dataclasses
***********
In Python 3.7, a new ``dataclasses`` module has been added to the standard library.
In Python 3.7, a new :py:mod:`dataclasses` module has been added to the standard library.
This module allows defining and customizing simple boilerplate-free classes.
They can be defined using the ``@dataclasses.dataclass`` decorator:
They can be defined using the :py:func:`@dataclasses.dataclass
<python:dataclasses.dataclass>` decorator:
.. code-block:: python
......@@ -25,7 +26,7 @@ They can be defined using the ``@dataclasses.dataclass`` decorator:
test = Application("Testing...") # OK
bad = Application("Testing...", "with plugin") # Error: List[str] expected
Mypy will detect special methods (such as ``__lt__``) depending on the flags used to
Mypy will detect special methods (such as :py:meth:`__lt__ <object.__lt__>`) depending on the flags used to
define dataclasses. For example:
.. code-block:: python
......@@ -65,16 +66,16 @@ class can be used:
val = unbox(BoxedData(42, "<important>")) # OK, inferred type is int
For more information see `official docs <https://docs.python.org/3/library/dataclasses.html>`_
and `PEP 557 <https://www.python.org/dev/peps/pep-0557/>`_.
For more information see :doc:`official docs <python:library/dataclasses>`
and :pep:`557`.
Caveats/Known Issues
====================
Some functions in the ``dataclasses`` module, such as ``replace()`` and ``asdict()``,
Some functions in the :py:mod:`dataclasses` module, such as :py:func:`~dataclasses.replace` and :py:func:`~dataclasses.asdict`,
have imprecise (too permissive) types. This will be fixed in future releases.
Mypy does not yet recognize aliases of ``dataclasses.dataclass``, and will
Mypy does not yet recognize aliases of :py:func:`dataclasses.dataclass <dataclasses.dataclass>`, and will
probably never recognize dynamically computed decorators. The following examples
do **not** work:
......@@ -110,7 +111,7 @@ do **not** work:
The attrs package
*****************
`attrs <http://www.attrs.org/en/stable>`_ is a package that lets you define
:doc:`attrs <attrs:index>` is a package that lets you define
classes without writing boilerplate code. Mypy can detect uses of the
package and will generate the necessary method definitions for decorated
classes using the type annotations it finds.
......@@ -139,7 +140,7 @@ If you're using ``auto_attribs=True`` you must use variable annotations.
three: int = attr.ib(8)
Typeshed has a couple of "white lie" annotations to make type checking
easier. ``attr.ib`` and ``attr.Factory`` actually return objects, but the
easier. :py:func:`attr.ib` and :py:class:`attr.Factory` actually return objects, but the
annotation says these return the types that they expect to be assigned to.
That enables this to work:
......@@ -174,9 +175,9 @@ Caveats/Known Issues
* Currently, ``converter`` only supports named functions. If mypy finds something else it
will complain about not understanding the argument and the type annotation in
``__init__`` will be replaced by ``Any``.
:py:meth:`__init__ <object.__init__>` will be replaced by ``Any``.
* `Validator decorators <http://www.attrs.org/en/stable/examples.html#validators>`_
* :ref:`Validator decorators <attrs:examples_validators>`
and `default decorators <http://www.attrs.org/en/stable/examples.html#defaults>`_
are not type-checked against the attribute they are setting/validating.
......@@ -347,16 +348,16 @@ Extended Callable types
This feature is deprecated. You can use
:ref:`callback protocols <callback_protocols>` as a replacement.
As an experimental mypy extension, you can specify ``Callable`` types
As an experimental mypy extension, you can specify :py:data:`~typing.Callable` types
that support keyword arguments, optional arguments, and more. When
you specify the arguments of a Callable, you can choose to supply just
you specify the arguments of a :py:data:`~typing.Callable`, you can choose to supply just
the type of a nameless positional argument, or an "argument specifier"
representing a more complicated form of argument. This allows one to
more closely emulate the full range of possibilities given by the
``def`` statement in Python.
As an example, here's a complicated function definition and the
corresponding ``Callable``:
corresponding :py:data:`~typing.Callable`:
.. code-block:: python
......@@ -433,7 +434,7 @@ purpose:
In all cases, the ``type`` argument defaults to ``Any``, and if the
``name`` argument is omitted the argument has no name (the name is
required for ``NamedArg`` and ``DefaultNamedArg``). A basic
``Callable`` such as
:py:data:`~typing.Callable` such as
.. code-block:: python
......@@ -445,7 +446,7 @@ is equivalent to the following:
MyFunc = Callable[[Arg(int), Arg(str), Arg(int)], float]
A ``Callable`` with unspecified argument types, such as
A :py:data:`~typing.Callable` with unspecified argument types, such as
.. code-block:: python
......
......@@ -23,7 +23,7 @@ Type Description
====================== ===============================
The type ``Any`` and type constructors such as ``List``, ``Dict``,
``Iterable`` and ``Sequence`` are defined in the ``typing`` module.
``Iterable`` and ``Sequence`` are defined in the :py:mod:`typing` module.
The type ``Dict`` is a *generic* class, signified by type arguments within
``[...]``. For example, ``Dict[int, str]`` is a dictionary from integers to
......@@ -35,6 +35,6 @@ strings and ``Dict[Any, Any]`` is a dictionary of dynamically typed
correspond to Python protocols. For example, a ``str`` object or a
``List[str]`` object is valid
when ``Iterable[str]`` or ``Sequence[str]`` is expected. Note that even though
they are similar to abstract base classes defined in ``collections.abc``
they are similar to abstract base classes defined in :py:mod:`collections.abc`
(formerly ``collections``), they are not identical, since the built-in
collection type objects do not support indexing.
......@@ -6,7 +6,7 @@ Casts and type assertions
Mypy supports type casts that are usually used to coerce a statically
typed value to a subtype. Unlike languages such as Java or C#,
however, mypy casts are only used as hints for the type checker, and they
don't perform a runtime type check. Use the function ``cast`` to perform a
don't perform a runtime type check. Use the function :py:func:`~typing.cast` to perform a
cast:
.. code-block:: python
......
......@@ -3,8 +3,7 @@
Type hints cheat sheet (Python 2)
=================================
This document is a quick cheat sheet showing how the
`PEP 484 <https://www.python.org/dev/peps/pep-0484/>`_ type
This document is a quick cheat sheet showing how the :pep:`484` type
language represents various common types in Python 2.
.. note::
......
......@@ -3,8 +3,7 @@
Type hints cheat sheet (Python 3)
=================================
This document is a quick cheat sheet showing how the
`PEP 484 <https://www.python.org/dev/peps/pep-0484/>`_ type
This document is a quick cheat sheet showing how the :pep:`484` type
annotation notation represents various common types in Python 3.
.. note::
......@@ -18,9 +17,8 @@ annotation notation represents various common types in Python 3.
Variables
*********
Python 3.6 introduced a syntax for annotating variables in
`PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_ and
we use it in most examples.
Python 3.6 introduced a syntax for annotating variables in :pep:`526`
and we use it in most examples.
.. code-block:: python
......@@ -214,12 +212,13 @@ that are common in idiomatic Python are standardized.
# Mapping describes a dict-like object (with "__getitem__") that we won't
# mutate, and MutableMapping one (with "__setitem__") that we might
def f(my_dict: Mapping[int, str]) -> List[int]:
my_mapping[5] = 'maybe' # if we try this, mypy will throw an error...
return list(my_dict.keys())
f({3: 'yes', 4: 'no'})
def f(my_mapping: MutableMapping[int, str]) -> Set[str]:
my_mapping[5] = 'maybe'
my_mapping[5] = 'maybe' # ...but mypy is OK with this.
return set(my_mapping.values())
f({3: 'yes', 4: 'no'})
......
......@@ -24,7 +24,7 @@ initialized within the class. Mypy infers the types of attributes:
a.y = 3 # Error: 'A' has no attribute 'y'
This is a bit like each class having an implicitly defined
``__slots__`` attribute. This is only enforced during type
:py:data:`__slots__ <object.__slots__>` attribute. This is only enforced during type
checking and not when your program is running.
You can declare types of variables in the class body explicitly using
......@@ -40,7 +40,7 @@ a type annotation:
As in Python generally, a variable defined in the class body can be used
as a class or an instance variable. (As discussed in the next section, you
can override this with a ``ClassVar`` annotation.)
can override this with a :py:data:`~typing.ClassVar` annotation.)
Type comments work as well, if you need to support Python versions earlier
than 3.6:
......@@ -78,14 +78,14 @@ to it explicitly using ``self``:
a = self
a.x = 1 # Error: 'x' not defined
Annotating `__init__` methods
*****************************
Annotating ``__init__`` methods
*******************************
The ``__init__`` method is somewhat special -- it doesn't return a
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 is redundant, it is allowed to omit the return type declaration
on ``__init__`` methods **if at least one argument is annotated**. For
example, in the following classes ``__init__`` is considered fully
on :py:meth:`__init__ <object.__init__>` methods **if at least one argument is annotated**. For
example, in the following classes :py:meth:`__init__ <object.__init__>` is considered fully
annotated:
.. code-block:: python
......@@ -98,7 +98,7 @@ annotated:
def __init__(self, arg: int):
self.var = arg
However, if ``__init__`` has no annotated arguments and no return type
However, if :py:meth:`__init__ <object.__init__>` has no annotated arguments and no return type
annotation, it is considered an untyped method:
.. code-block:: python
......@@ -111,7 +111,7 @@ annotation, it is considered an untyped method:
Class attribute annotations
***************************
You can use a ``ClassVar[t]`` annotation to explicitly declare that a
You can use a :py:data:`ClassVar[t] <typing.ClassVar>` annotation to explicitly declare that a
particular attribute should not be set on instances:
.. code-block:: python
......@@ -134,7 +134,7 @@ particular attribute should not be set on instances:
PyPI). If you use Python 2.7, you can import it from ``typing``.
It's not necessary to annotate all class variables using
``ClassVar``. An attribute without the ``ClassVar`` annotation can
:py:data:`~typing.ClassVar`. An attribute without the :py:data:`~typing.ClassVar` annotation can
still be used as a class variable. However, mypy won't prevent it from
being used as an instance variable, as discussed previously:
......@@ -148,13 +148,13 @@ being used as an instance variable, as discussed previously:
a = A()
a.x = 1 # Also OK
Note that ``ClassVar`` is not a class, and you can't use it with
``isinstance()`` or ``issubclass()``. It does not change Python
Note that :py:data:`~typing.ClassVar` is not a class, and you can't use it with
:py:func:`isinstance` or :py:func:`issubclass`. It does not change Python
runtime behavior -- it's only for type checkers such as mypy (and
also helpful for human readers).
You can also omit the square brackets and the variable type in
a ``ClassVar`` annotation, but this might not do what you'd expect:
a :py:data:`~typing.ClassVar` annotation, but this might not do what you'd expect:
.. code-block:: python
......@@ -165,7 +165,7 @@ In this case the type of the attribute will be implicitly ``Any``.
This behavior will change in the future, since it's surprising.
.. note::
A ``ClassVar`` type parameter cannot include type variables:
A :py:data:`~typing.ClassVar` type parameter cannot include type variables:
``ClassVar[T]`` and ``ClassVar[List[T]]``
are both invalid if ``T`` is a type variable (see :ref:`generic-classes`
for more about type variables).
......@@ -232,10 +232,10 @@ effect at runtime:
Abstract base classes and multiple inheritance
**********************************************
Mypy supports Python abstract base classes (ABCs). Abstract classes
Mypy supports Python :doc:`abstract base classes <library/abc>` (ABCs). Abstract classes
have at least one abstract method or property that must be implemented
by any *concrete* (non-abstract) subclass. You can define abstract base
classes using the ``abc.ABCMeta`` metaclass and the ``abc.abstractmethod``
classes using the :py:class:`abc.ABCMeta` metaclass and the :py:func:`@abc.abstractmethod <abc.abstractmethod>`
function decorator. Example:
.. code-block:: python
......@@ -263,11 +263,11 @@ function decorator. Example:
.. note::
In Python 2.7 you have to use ``@abc.abstractproperty`` to define
In Python 2.7 you have to use :py:func:`@abc.abstractproperty <abc.abstractproperty>` to define
an abstract property.
Note that mypy performs checking for unimplemented abstract methods
even if you omit the ``ABCMeta`` metaclass. This can be useful if the
even if you omit the :py:class:`~abc.ABCMeta` metaclass. This can be useful if the
metaclass would cause runtime metaclass conflicts.
Since you can't create instances of ABCs, they are most commonly used in
......
......@@ -78,7 +78,7 @@ imports.
``--namespace-packages``
This flag enables import discovery to use namespace packages (see
`PEP 420`_). In particular, this allows discovery of imported
:pep:`420`). In particular, this allows discovery of imported
packages that don't have an ``__init__.py`` (or ``__init__.pyi``)
file.
......@@ -127,7 +127,7 @@ imports.
see :ref:`Following imports <follow-imports>`.
``--python-executable EXECUTABLE``
This flag will have mypy collect type information from `PEP 561`_
This flag will have mypy collect type information from :pep:`561`
compliant packages installed for the Python executable ``EXECUTABLE``.
If not provided, mypy will use PEP 561 compliant packages installed for
the Python executable running mypy.
......@@ -135,7 +135,7 @@ imports.
See :ref:`installed-packages` for more on making PEP 561 compliant packages.
``--no-site-packages``
This flag will disable searching for `PEP 561`_ compliant packages. This
This flag will disable searching for :pep:`561` compliant packages. This
will also disable searching for a usable Python executable.
Use this flag if mypy cannot find a Python executable for the version of
......@@ -143,7 +143,7 @@ imports.
Otherwise, use ``--python-executable``.
``--no-silence-site-packages``
By default, mypy will suppress any error messages generated within PEP 561
By default, mypy will suppress any error messages generated within :pep:`561`
compliant packages. Adding this flag will disable this behavior.
......@@ -165,7 +165,7 @@ For more information on how to use these flags, see :ref:`version_and_platform_c
``--py2`` flags are aliases for ``--python-version 2.7``.
This flag will attempt to find a Python executable of the corresponding
version to search for `PEP 561`_ compliant packages. If you'd like to
version to search for :pep:`561` compliant packages. If you'd like to
disable this, use the ``--no-site-packages`` flag (see
:ref:`import-discovery` for more details).
......@@ -178,7 +178,7 @@ For more information on how to use these flags, see :ref:`version_and_platform_c
default to using whatever operating system you are currently using.
The ``PLATFORM`` parameter may be any string supported by
`sys.platform <https://docs.python.org/3/library/sys.html#sys.platform>`_.
:py:data:`sys.platform`.
.. _always-true:
......@@ -213,7 +213,7 @@ The following options are available:
This flag disallows all expressions in the module that have type ``Any``.
If an expression of type ``Any`` appears anywhere in the module
mypy will output an error unless the expression is immediately
used as an argument to ``cast`` or assigned to a variable with an
used as an argument to :py:func:`~typing.cast` or assigned to a variable with an
explicit type annotation.
In addition, declaring a variable of type ``Any``
......@@ -230,9 +230,9 @@ The following options are available:
``--disallow-any-generics``
This flag disallows usage of generic types that do not specify explicit
type parameters. Moreover, built-in collections (such as ``list`` and
``dict``) become disallowed as you should use their aliases from the typing
module (such as ``List[int]`` and ``Dict[str, str]``).
type parameters. Moreover, built-in collections (such as :py:class:`list` and
:py:class:`dict`) become disallowed as you should use their aliases from the :py:mod:`typing`
module (such as :py:class:`List[int] <typing.List>` and :py:class:`Dict[str, str] <typing.Dict>`).
``--disallow-subclassing-any``
This flag reports an error whenever a class subclasses a value of
......@@ -285,14 +285,14 @@ definitions or calls.
None and Optional handling
**************************
The following flags adjust how mypy handles values of type `None`.
The following flags adjust how mypy handles values of type ``None``.
For more details, see :ref:`no_strict_optional`.
.. _no-implicit-optional:
``--no-implicit-optional``
This flag causes mypy to stop treating arguments with a ``None``
default value as having an implicit ``Optional[...]`` type.
default value as having an implicit :py:data:`~typing.Optional` type.
For example, by default mypy will assume that the ``x`` parameter
is of type ``Optional[int]`` in the code snippet below since
......@@ -312,7 +312,7 @@ For more details, see :ref:`no_strict_optional`.
print(x)
``--no-strict-optional``
This flag disables strict checking of ``Optional[...]``
This flag disables strict checking of :py:data:`~typing.Optional`
types and ``None`` values. With this option, mypy doesn't
generally check the use of ``None`` values -- they are valid
everywhere. See :ref:`no_strict_optional` for more about this feature.
......@@ -387,7 +387,7 @@ potentially problematic or redundant in some way.
unreachable" warning will be silenced in exactly two cases:
1. When the unreachable statement is a ``raise`` statement, is an
``assert False`` statement, or calls a function that has the ``NoReturn``
``assert False`` statement, or calls a function that has the :py:data:`~typing.NoReturn`
return type hint. In other words, when the unreachable statement
throws an error or terminates the program in some way.
2. When the unreachable statement was *intentionally* marked as unreachable
......@@ -578,7 +578,7 @@ in developing or debugging mypy internals.
``--custom-typing MODULE``
This flag lets you use a custom module as a substitute for the
``typing`` module.
:py:mod:`typing` module.
``--custom-typeshed-dir DIR``
This flag specifies the directory where mypy looks for typeshed
......@@ -673,15 +673,11 @@ Miscellaneous
This flag will give command line arguments that appear to be
scripts (i.e. files whose name does not end in ``.py``)
a module name derived from the script name rather than the fixed
name ``__main__``.
name :py:mod:`__main__`.
This lets you check more than one script in a single mypy invocation.
(The default ``__main__`` is technically more correct, but if you
(The default :py:mod:`__main__` is technically more correct, but if you
have many scripts that import a large package, the behavior enabled
by this flag is often more convenient.)
.. _PEP 420: https://www.python.org/dev/peps/pep-0420/
.. _PEP 561: https://www.python.org/dev/peps/pep-0561/
.. _lxml: https://pypi.org/project/lxml/
......@@ -69,7 +69,7 @@ flagged as an error.
:ref:`reveal_type() <reveal-type>` might come in handy.
Note that sometimes library stubs have imprecise type information,
e.g. the ``pow()`` builtin returns ``Any`` (see `typeshed issue 285
e.g. the :py:func:`pow` builtin returns ``Any`` (see `typeshed issue 285
<https://github.com/python/typeshed/issues/285>`_ for the reason).
- **Some imports may be silently ignored**. Another source of
......@@ -143,7 +143,7 @@ Another option is to explicitly annotate values with type ``Any`` --
mypy will let you perform arbitrary operations on ``Any``
values. Sometimes there is no more precise type you can use for a
particular value, especially if you use dynamic Python features
such as ``__getattr__``:
such as :py:meth:`__getattr__ <object.__getattr__>`:
.. code-block:: python
......@@ -326,7 +326,7 @@ above example:
Complex type tests
------------------
Mypy can usually infer the types correctly when using ``isinstance()``
Mypy can usually infer the types correctly when using :py:func:`isinstance <isinstance>`
type tests, but for other kinds of checks you may need to add an
explicit type cast:
......@@ -342,17 +342,17 @@ explicit type cast:
.. note::
Note that the ``object`` type used in the above example is similar
Note that the :py:class:`object` type used in the above example is similar
to ``Object`` in Java: it only supports operations defined for *all*
objects, such as equality and ``isinstance()``. The type ``Any``,
objects, such as equality and :py:func:`isinstance`. The type ``Any``,
in contrast, supports all operations, even if they may fail at
runtime. The cast above would have been unnecessary if the type of
``o`` was ``Any``.
Mypy can't infer the type of ``o`` after the ``type()`` check
because it only knows about ``isinstance()`` (and the latter is better
Mypy can't infer the type of ``o`` after the :py:class:`type() <type>` check
because it only knows about :py:func:`isinstance` (and the latter is better
style anyway). We can write the above code without a cast by using
``isinstance()``:
:py:func:`isinstance`:
.. code-block:: python
......@@ -379,8 +379,8 @@ the targeted Python version or platform. This allows you to more effectively
typecheck code that supports multiple versions of Python or multiple operating
systems.
More specifically, mypy will understand the use of ``sys.version_info`` and
``sys.platform`` checks within ``if/elif/else`` statements. For example:
More specifically, mypy will understand the use of :py:data:`sys.version_info` and
:py:data:`sys.platform` checks within ``if/elif/else`` statements. For example:
.. code-block:: python
......@@ -417,14 +417,14 @@ Example:
# The rest of this file doesn't apply to Windows.
Some other expressions exhibit similar behavior; in particular,
``typing.TYPE_CHECKING``, variables named ``MYPY``, and any variable
:py:data:`~typing.TYPE_CHECKING`, variables named ``MYPY``, and any variable
whose 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 assign
any special meaning when assigning a ``sys.version_info`` or ``sys.platform``
any special meaning when assigning a :py:data:`sys.version_info` or :py:data:`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 current
......@@ -438,8 +438,7 @@ to 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, pass
in ``--platform win32``. See the documentation for
`sys.platform <https://docs.python.org/3/library/sys.html#sys.platform>`_
in ``--platform win32``. See the documentation for :py:data:`sys.platform`
for examples of valid platform parameters.
.. _reveal-type:
......@@ -515,10 +514,10 @@ File ``bar.py``:
.. note::
The ``TYPE_CHECKING`` constant defined by the ``typing`` module
The :py:data:`~typing.TYPE_CHECKING` constant defined by the :py:mod:`typing` module
is ``False`` at runtime but ``True`` while type checking.
Python 3.5.1 doesn't have ``typing.TYPE_CHECKING``. An alternative is
Python 3.5.1 doesn't have :py:data:`~typing.TYPE_CHECKING`. An alternative is
to define a constant named ``MYPY`` that has the value ``False``
at runtime. Mypy considers it to be ``True`` when type checking.
Here's the above example modified to use ``MYPY``:
......@@ -539,7 +538,7 @@ Using classes that are generic in stubs but not at runtime
----------------------------------------------------------
Some classes are declared as generic in stubs, but not at runtime. Examples
in the standard library include ``os.PathLike`` and ``queue.Queue``.
in the standard library include :py:class:`os.PathLike` and :py:class:`queue.Queue`.
Subscripting such a class will result in a runtime error:
.. code-block:: python
......@@ -552,7 +551,7 @@ Subscripting such a class will result in a runtime error:
results: Queue[int] = Queue() # TypeError: 'type' object is not subscriptable
To avoid these errors while still having precise types you can either use
string literal types or ``typing.TYPE_CHECKING``:
string literal types or :py:data:`~typing.TYPE_CHECKING`:
.. code-block:: python
......@@ -616,7 +615,7 @@ Consider this example:
c.x << 5 # Since this will fail!
To work around this problem consider whether "mutating" is actually part
of a protocol. If not, then one can use a ``@property`` in
of a protocol. If not, then one can use a :py:class:`@property <property>` in
the protocol definition:
.. code-block:: python
......
......@@ -30,7 +30,7 @@ from mypy.version import __version__ as mypy_version
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
extensions = ['sphinx.ext.intersphinx']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
......@@ -266,3 +266,11 @@ texinfo_documents = [
#texinfo_no_detailmenu = False
rst_prolog = '.. |...| unicode:: U+2026 .. ellipsis\n'
intersphinx_mapping = {
'python': ('https://docs.python.org/3', None),
'six': ('https://six.readthedocs.io', None),
'attrs': ('http://www.attrs.org/en/stable', None),
'cython': ('http://docs.cython.org/en/latest', None),
'monkeytype': ('https://monkeytype.readthedocs.io/en/latest', None),
}
......@@ -29,10 +29,9 @@ Config file format
******************
The configuration file format is the usual
`ini file <https://docs.python.org/3.6/library/configparser.html>`_
format. It should contain section names in square brackets and flag
settings of the form `NAME = VALUE`. Comments start with ``#``
characters.
:doc:`ini file <python:library/configparser>` format. It should contain
section names in square brackets and flag settings of the form
`NAME = VALUE`. Comments start with ``#`` characters.
- A section named ``[mypy]`` must be present. This specifies
the global flags. The ``setup.cfg`` file is an exception to this.
......@@ -190,7 +189,7 @@ See below for a list of import discovery options that may be used
Used in conjunction with ``follow_imports=skip``, this can be used
to suppress the import of a module from ``typeshed``, replacing it
with `Any`.
with ``Any``.
Used in conjunction with ``follow_imports=error``, this can be used
to make any use of a particular ``typeshed`` module an error.
......@@ -255,8 +254,8 @@ For more information, see the :ref:`None and optional handling <none-and-optiona
section of the command line docs.
``no_implicit_optional`` (bool, default False)
Changes the treatment of arguments with a default value of None by not implicitly
making their type Optional.
Changes the treatment of arguments with a default value of ``None`` by not implicitly
making their type :py:data:`~typing.Optional`.
``strict_optional`` (bool, default True)
Enables or disables strict Optional checks. If False, mypy treats ``None``
......@@ -357,7 +356,7 @@ 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
Enables :pep:`420` style namespace packages. See :ref:`the
corresponding flag <import-discovery>` for more information.
``python_executable`` (string)
......@@ -367,7 +366,7 @@ a list of import discovery options that may be used
the executable used to run mypy.
``no_silence_site_packages`` (bool, default False)
Enables reporting error messages generated within PEP 561 compliant packages.
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.
......@@ -378,10 +377,10 @@ a list of import discovery options that may be used
User home directory and environment variables will be expanded.
``files`` (string)
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
[the glob library](https://docs.python.org/3/library/glob.html), where `*` (e.g. `*.py`) matches
files in the current directory and `**/` (e.g. `**/*.py`) matches files in any directories below
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.
......@@ -401,7 +400,7 @@ section of the command line docs.
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
``sys.platform`` variable.
:py:data:`sys.platform` variable.
Incremental mode
......@@ -420,7 +419,7 @@ section of the command line docs.
variable.
Note that the cache is only read when incremental mode is enabled
but is always written to, unless the value is set to ``/dev/nul``
but is always written to, unless the value is set to ``/dev/null``
(UNIX) or ``nul`` (Windows).
``skip_version_check`` (bool, default False)
......@@ -464,7 +463,7 @@ section of the command line docs.
Shows traceback on fatal error.
``custom_typing_module`` (string)
Specifies a custom module to use as a substitute for the ``typing`` module.
Specifies a custom module to use as a substitute for the :py:mod:`typing` module.
``custom_typeshed_dir`` (string)
Specifies an alternative directory to look for stubs instead of the
......