Skip to content
Commits on Source (3)
Metadata-Version: 2.1
Name: mypy
Version: 0.670
Version: 0.720
Summary: Optional static typing for Python
Home-page: http://www.mypy-lang.org/
Author: Jukka Lehtosalo
......@@ -17,12 +17,11 @@ Description: Mypy -- Optional Static Typing for Python
types.
Platform: UNKNOWN
Classifier: Development Status :: 3 - Alpha
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
......
......@@ -64,14 +64,14 @@ See 'Development status' below.
Requirements
------------
You need Python 3.4 or later to run mypy. You can have multiple Python
You need Python 3.5 or later to run mypy. You can have multiple Python
versions (2.x and 3.x) installed on the same system without problems.
In Ubuntu, Mint and Debian you can install Python 3 like this:
$ sudo apt-get install python3 python3-pip
For other Linux flavors, OS X and Windows, packages are available at
For other Linux flavors, macOS and Windows, packages are available at
http://www.python.org/getit/
......@@ -99,26 +99,30 @@ programs, even if they have type errors:
$ python3 PROGRAM
[statically typed parts]: http://mypy.readthedocs.io/en/latest/basics.html#function-signatures
You can also try mypy in an [online playground](https://mypy-play.net/) (developed by
Yusuke Miyazaki).
[statically typed parts]: https://mypy.readthedocs.io/en/latest/getting_started.html#function-signatures-and-dynamic-vs-static-typing
IDE & Linter Integrations
-------------------------
IDE, Linter Integrations, and Pre-commit
----------------------------------------
Mypy can be integrated into popular IDEs:
* Vim: [vim-mypy](https://github.com/Integralist/vim-mypy)
* Vim: [syntastic](https://github.com/vim-syntastic/syntastic) in `.vimrc` add `let g:syntastic_python_checkers=['mypy']`
* 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))
* 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].
Mypy can also be integrated into [Flake8] using [flake8-mypy], or
can be set up as a pre-commit hook using [pre-commit mirrors-mypy].
[Flake8]: http://flake8.pycqa.org/
[flake8-mypy]: https://github.com/ambv/flake8-mypy
[pre-commit mirrors-mypy]: https://github.com/pre-commit/mirrors-mypy
Web site and documentation
--------------------------
......@@ -152,7 +156,7 @@ dependencies, including the `typing` module, will be installed to
system-dependent locations. Sometimes the script directory will not
be in `PATH`, and you have to add the target directory to `PATH`
manually or create a symbolic link to the script. In particular, on
Mac OS X, the script may be installed under `/Library/Frameworks`:
macOS, the script may be installed under `/Library/Frameworks`:
/Library/Frameworks/Python.framework/Versions/<version>/bin
......@@ -186,7 +190,8 @@ you need to pull in the typeshed repo as follows:
$ git submodule init
$ git submodule update
Either way you should now have a subdirectory `typeshed` containing a
Either way you should now have a subdirectory `typeshed` inside your mypy repo,
your folders tree should be like `mypy/mypy/typeshed`, containing a
clone of the typeshed repo (`https://github.com/python/typeshed`).
From the mypy directory, use pip to install mypy:
......@@ -224,6 +229,7 @@ Tests
The basic way to run tests:
$ pip3 install -r test-requirements.txt
$ python2 -m pip install -U typing
$ ./runtests.py
For more on the tests, see [Test README.md](test-data/unit/README.md)
......@@ -232,36 +238,44 @@ For more on the tests, see [Test README.md](test-data/unit/README.md)
Development status
------------------
Mypy is alpha software, but it has already been used in production
for well over a year at Dropbox, and it has an extensive test suite.
Mypy is beta software, but it has already been used in production
for several years at Dropbox, and it has an extensive test suite.
See [the roadmap](ROADMAP.md) if you are interested in plans for the
future.
Changelog
---------
Follow mypy's updates on the blog: http://mypy-lang.blogspot.com/
Issue tracker
-------------
Please report any bugs and enhancement ideas using the mypy issue
tracker:
tracker: https://github.com/python/mypy/issues
https://github.com/python/mypy/issues
If you have any questions about using mypy or types, please ask
in the typing gitter instead: https://gitter.im/python/typing
Feel free to also ask questions on the tracker.
Compiled version of mypy
------------------------
mypy_mypyc
----------
We have built an compiled version of mypy using the [mypyc
compiler](https://github.com/mypyc/mypyc) for mypy-annotated Python
code. It is approximately 4 times faster than interpreted mypy and is
available (and the default) for 64-bit Windows, macOS, and Linux.
We have built an experimental compiled version of mypy using the
[mypyc compiler](https://github.com/mypyc/mypyc) for mypy-annotated
Python code. It is approximately 4 times faster than interpreted mypy.
To install an interpreted mypy instead, use:
If you wish to test out the compiled version of mypy, and are running
OS X or Linux, you can directly install a binary from
https://github.com/mypyc/mypy_mypyc-wheels/releases/latest.
$ python3 -m pip install --no-binary mypy -U mypy
Compiled mypy packages on PyPI are Coming Soon.
If you wish to test out the compiled version of a development
version of mypy, you can directly install a binary from
https://github.com/mypyc/mypy_mypyc-wheels/releases/latest.
Help wanted
......
mypy (0.720-1) unstable; urgency=medium
* New upstream release
-- Michael R. Crusoe <michael.crusoe@gmail.com> Sat, 13 Jul 2019 12:09:09 +0200
mypy (0.670-2) unstable; urgency=medium
* Include upstream's README.md in the the mypy binary package.
......
......@@ -18,6 +18,7 @@ Build-Depends: debhelper (>= 12~),
python3-typed-ast (>= 1.3.1), python3-typed-ast (<< 1.4.0),
python3-psutil (>= 5.4.0),
python3-mypy-extensions,
python3-typing-extensions,
python3-virtualenv <!nocheck>
Standards-Version: 4.3.0
Vcs-Browser: https://salsa.debian.org/med-team/mypy
......
From: Michael R. Crusoe <michael.crusoe@gmail.com>
Subject: specify python3 for typeshed test
--- mypy.orig/mypy/typeshed/tests/pytype_test.py
+++ mypy/mypy/typeshed/tests/pytype_test.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
r"""Test runner for typeshed.
Depends on pytype being installed.
......@@ -342,6 +342,11 @@ at least if your codebase is hundreds of thousands of lines or more:
Extended Callable types
***********************
.. note::
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
that support keyword arguments, optional arguments, and more. When
you specify the arguments of a Callable, you can choose to supply just
......@@ -454,11 +459,9 @@ is (roughly) equivalent to
.. note::
This feature is experimental. Details of the implementation may
change and there may be unknown limitations. **IMPORTANT:**
Each of the functions above currently just returns its ``type``
argument, so the information contained in the argument specifiers
is not available at runtime. This limitation is necessary for
backwards compatibility with the existing ``typing.py`` module as
present in the Python 3.5+ standard library and distributed via
PyPI.
argument at runtime, so the information contained in the argument
specifiers is not available at runtime. This limitation is
necessary for backwards compatibility with the existing
``typing.py`` module as present in the Python 3.5+ standard library
and distributed via PyPI.
......@@ -58,7 +58,7 @@ Functions
.. code-block:: python
from typing import Callable, Iterable, Union, Optional, List
from typing import Callable, Iterator, Union, Optional, List
# This is how you annotate a function definition
def stringify(num):
......@@ -95,9 +95,9 @@ Functions
x = f # type: Callable[[int, float], float]
# A generator function that yields ints is secretly just a function that
# returns an iterable (see below) of ints, so that's how we annotate it
def f(n):
# type: (int) -> Iterable[int]
# returns an iterator of ints, so that's how we annotate it
def g(n):
# type: (int) -> Iterator[int]
i = 0
while i < n:
yield i
......
......@@ -86,7 +86,7 @@ Python 3 supports an annotation syntax for function declarations.
.. code-block:: python
from typing import Callable, Iterable, Union, Optional, List
from typing import Callable, Iterator, Union, Optional, List
# This is how you annotate a function definition
def stringify(num: int) -> str:
......@@ -104,8 +104,8 @@ Python 3 supports an annotation syntax for function declarations.
x: Callable[[int, float], float] = f
# A generator function that yields ints is secretly just a function that
# returns an iterable (see below) of ints, so that's how we annotate it
def f(n: int) -> Iterable[int]:
# returns an iterator of ints, so that's how we annotate it
def g(n: int) -> Iterator[int]:
i = 0
while i < n:
yield i
......
......@@ -57,11 +57,15 @@ Config file
Settings override mypy's built-in defaults and command line flags
can override settings.
Specifying ``--config-file=`` (with no filename) will ignore *all*
config files.
See :ref:`config-file` for the syntax of configuration files.
``--warn-unused-configs``
This flag makes mypy warn about unused ``[mypy-<pattern>]`` config
file sections.
(This requires turning off incremental mode using ``--no-incremental``.)
.. _import-discovery:
......@@ -129,7 +133,6 @@ imports.
the Python executable running mypy.
See :ref:`installed-packages` for more on making PEP 561 compliant packages.
This flag will attempt to set ``--python-version`` if not already set.
``--no-site-packages``
This flag will disable searching for `PEP 561`_ compliant packages. This
......@@ -336,7 +339,7 @@ potentially problematic or redundant in some way.
a ``# type: ignore`` comment on a line that is not actually
generating an error message.
This flag, along with the ``--warn-unused-casts`` flag, are both
This flag, along with the ``--warn-redundant-casts`` flag, are both
particularly useful when you are upgrading mypy. Previously,
you may have needed to add casts or ``# type: ignore`` annotations
to work around bugs in mypy or missing stubs for 3rd party libraries.
......@@ -361,6 +364,43 @@ potentially problematic or redundant in some way.
This flag causes mypy to generate a warning when returning a value
with type ``Any`` from a function declared with a non- ``Any`` return type.
``--warn-unreachable``
This flag will make mypy report an error whenever it encounters
code determined to be unreachable or redundant after performing type analysis.
This can be a helpful way of detecting certain kinds of bugs in your code.
For example, enabling this flag will make mypy report that the ``x > 7``
check is redundant and that the ``else`` block below is unreachable.
.. code-block:: python
def process(x: int) -> None:
# Error: Right operand of 'or' is never evaluated
if isinstance(x, int) or x > 7:
# Error: Unsupported operand types for + ("int" and "str")
print(x + "bad")
else:
# Error: 'Statement is unreachable' error
print(x + "bad")
To help prevent mypy from generating spurious warnings, the "Statement is
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``
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
using :ref:`version_and_platform_checks`.
.. note::
Mypy currently cannot detect and report unreachable or redundant code
inside any functions using :ref:`type-variable-value-restriction`.
This limitation will be removed in future releases of mypy.
Miscellaneous strictness flags
******************************
......@@ -386,6 +426,39 @@ of the above sections.
# 'items' now has type List[List[str]]
...
``--no-implicit-reexport``
By default, imported values to a module are treated as exported and mypy allows
other modules to import them. This flag changes the behavior to not re-export unless
the item is imported using from-as. Note this is always treated as enabled for
stub files. For example:
.. code-block:: python
# This won't re-export the value
from foo import bar
# This will re-export it as bar and allow other modules to import it
from foo import bar as bar
``--strict-equality``
By default, mypy allows always-false comparisons like ``42 == 'no'``.
Use this flag to prohibit such comparisons of non-overlapping types, and
similar identity and container checks:
.. code-block:: python
from typing import List, Text
items: List[int]
if 'some string' in items: # Error: non-overlapping container check!
...
text: Text
if text != b'other bytes': # Error: non-overlapping equality check!
...
assert text is not None # OK, check against None is allowed as a special case.
``--strict``
This flag mode enables all optional error checking flags. You can see the
list of flags enabled by strict mode in the full ``mypy --help`` output.
......@@ -586,6 +659,18 @@ Miscellaneous
have many scripts that import a large package, the behavior enabled
by this flag is often more convenient.)
``--no-new-semantic-analyzer``
This flag disables the improved implementation of
the *semantic analyzer* (the part of mypy that binds Python
names to definitions). The old and the new semantic analyzers
mostly behave identically. The new semantic analyzer is better at
handling import cycles and forward references to definitions. It
also fixes inconsistencies between the daemon and non-daemon modes,
and it detects additional error conditions.
Likely, the old semantic analyzer will be removed in the next
release.
.. _PEP 420: https://www.python.org/dev/peps/pep-0420/
.. _PEP 561: https://www.python.org/dev/peps/pep-0561/
......
......@@ -14,7 +14,7 @@ Can't install mypy using pip
If installation fails, you've probably hit one of these issues:
* Mypy needs Python 3.4 or later to run.
* Mypy needs Python 3.5 or later to run.
* You may have to run pip like this:
``python3 -m pip install mypy``.
......@@ -149,6 +149,20 @@ generates spurious errors. Mypy will only look at the stub file
and ignore the implementation, since stub files take precedence
over ``.py`` files.
Ignoring a whole file
---------------------
A ``# type: ignore`` comment at the top of a module (before any statements,
including imports or docstrings) has the effect of ignoring the *entire* module.
.. code-block:: python
# type: ignore
import foo
foo.bar()
Unexpected errors about 'None' and/or 'Optional' types
------------------------------------------------------
......@@ -641,8 +655,8 @@ renaming the method, a work-around is to use an alias:
def register(self, path: bytes_):
...
I need a mypy bug fix that hasn't been released yet
---------------------------------------------------
Using a development mypy build
------------------------------
You can install the latest development version of mypy from source. Clone the
`mypy repository on GitHub <https://github.com/python/mypy>`_, and then run
......
......@@ -41,7 +41,7 @@ characters.
whose name matches at least one of the patterns.
A pattern of the form ``qualified_module_name`` matches only the named module,
while ``qualified_module_name.*`` matches ``dotted_module_name`` and any
while ``dotted_module_name.*`` matches ``dotted_module_name`` and any
submodules (so ``foo.bar.*`` would match all of ``foo.bar``,
``foo.bar.baz``, and ``foo.bar.baz.quux``).
......@@ -52,15 +52,16 @@ characters.
.. _config-precedence:
When options conflict, the precedence order for the configuration sections is:
1. Sections with concrete module names (``foo.bar``)
2. Sections with "unstructured" wildcard patterns (``foo.*.baz``),
When options conflict, the precedence order for configuration is:
1. :ref:`Inline configuration <inline-config>` in the source file
2. Sections with concrete module names (``foo.bar``)
3. Sections with "unstructured" wildcard patterns (``foo.*.baz``),
with sections later in the configuration file overriding
sections earlier.
3. Sections with "well-structured" wildcard patterns
4. Sections with "well-structured" wildcard patterns
(``foo.bar.*``), with more specific overriding more general.
4. Command line options.
5. Top-level configuration file options.
5. Command line options.
6. Top-level configuration file options.
The difference in precedence order between "structured" patterns (by
specificity) and "unstructured" patterns (by order in the file) is
......@@ -143,6 +144,10 @@ options take precedence. This lets you set global defaults and override them on
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>`.
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).
.. _config-file-import-discovery-per-module:
Import discovery
......@@ -272,6 +277,10 @@ section of the command line docs.
Shows a warning when returning a value with type ``Any`` from a function
declared with a non- ``Any`` return type.
``warn_unreachable`` (bool, default False)
Shows a warning when encountering any code inferred to be unreachable or
redundant after performing type analysis.
.. _config-file-suppressing-errors:
Suppressing errors
......@@ -290,10 +299,39 @@ no analog available via the command line options.
Miscellaneous strictness flags
------------------------------
``allow_redefinition`` (bool, default false)
``allow_redefinition`` (bool, default False)
Allows variables to be redefined with an arbitrary type, as long as the redefinition
is in the same block and nesting level as the original definition.
``implicit_reexport`` (bool, default True)
By default, imported values to a module are treated as exported and mypy allows
other modules to import them. When false, mypy will not re-export unless
the item is imported using from-as. Note that mypy treats stub files as if this
is always disabled. For example:
.. code-block:: python
# This won't re-export the value
from foo import bar
# This will re-export it as bar and allow other modules to import it
from foo import bar as bar
``strict_equality`` (bool, default False)
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
*******************
......@@ -329,6 +367,13 @@ a list of import discovery options that may be used
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.
``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
the current one.
Platform configuration
----------------------
......@@ -348,14 +393,6 @@ section of the command line docs.
The default is the current platform as revealed by Python's
``sys.platform`` variable.
``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.
Incremental mode
----------------
......@@ -428,6 +465,11 @@ Miscellaneous
``warn_unused_configs`` (bool, default False)
Warns about per-module sections in the config file that do not
match any files processed when invoking mypy.
(This requires turning off incremental mode using ``incremental = False``.)
``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.)
......@@ -4,12 +4,12 @@
Dynamically typed code
======================
As mentioned earlier, bodies of functions that don't have have any
explicit types in their function annotation are dynamically typed
(operations are checked at runtime). Code outside functions is
statically typed by default, and types of variables are inferred. This
does usually the right thing, but you can also make any variable
dynamically typed by defining it explicitly with the type ``Any``:
As mentioned earlier, bodies of functions that don't have any explicit
types in their function annotation are dynamically typed (operations
are checked at runtime). Code outside functions is statically typed by
default, and types of variables are inferred. This does usually the
right thing, but you can also make any variable dynamically typed by
defining it explicitly with the type ``Any``:
.. code-block:: python
......
......@@ -59,8 +59,11 @@ new first class kinds of types.
The plugin system is experimental and prone to change. If you want to write
a mypy plugin, we recommend you start by contacting the mypy core developers
on `gitter <https://gitter.im/python/typing>`_. In particular, there are
no guarantees about backwards compatibility. Backwards incompatible changes
may be made without a deprecation period.
no guarantees about backwards compatibility.
Backwards incompatible changes may be made without a deprecation period,
but we will announce them in
`the plugin API changes announcement issue <https://github.com/python/mypy/issues/6617>`_.
Configuring mypy to use plugins
*******************************
......@@ -184,11 +187,11 @@ For example in this code:
mypy will call ``get_method_signature_hook("ctypes.Array.__setitem__")``
so that the plugin can mimic the ``ctypes`` auto-convert behavior.
**get_attribute_hook** can be used to give more precise type of an instance
attribute. Note however, that this method is only called for variables that
already exist in the class symbol table. If you want to add some generated
variables/methods to the symbol table you can use one of the three hooks
below.
**get_attribute_hook** overrides instance member field lookups and property
access (not assignments, and not method calls). This hook is only called for
fields which already exist on the class. *Exception:* if ``__getattr__`` or
``__getattribute__`` is a method on the class, the hook is called for all
fields which do not refer to methods.
**get_class_decorator_hook()** can be used to update class definition for
given class decorators. For example, you can add some attributes to the class
......@@ -227,3 +230,35 @@ method resolution order, etc.)
**get_customize_class_mro_hook()** can be used to modify class MRO (for example
insert some entries there) before the class body is analyzed.
**get_additional_deps()** can be used to add new dependencies for a
module. It is called before semantic analysis. For example, this can
be used if a library has dependencies that are dynamically loaded
based on configuration information.
Supporting the new semantic analyzer
************************************
Support for the new semantic analyzer (enabled through
``--new-semantic-analyzer``) requires some changes to plugins. Here is
a short summary of the most important changes:
* The order of processing AST nodes is different. Code outside
functions is processed first, and functions and methods are
processed afterwards.
* Each AST node can be processed multiple times to resolve forward
references. The same plugin hook may be called multiple times, so
they need to be idempotent.
* The ``anal_type()`` API method returns ``None`` if some part of
the type is not available yet due to forward references, for example.
* When looking up symbols, you may encounter *placeholder nodes* that
are used for names that haven't been fully processed yet. You'll
generally want to request another semantic analysis iteration by
*deferring* in that case.
See the docstring at the top of
`mypy/plugin.py <https://github.com/python/mypy/blob/master/mypy/plugin.py>`_
for more details.
......@@ -12,7 +12,7 @@ may not make much sense otherwise.
Installing and running mypy
***************************
Mypy requires Python 3.4 or later to run. Once you've
Mypy requires Python 3.5 or later to run. Once you've
`installed Python 3 <https://www.python.org/downloads/>`_,
install mypy using pip:
......@@ -104,7 +104,7 @@ when you are prototyping a new feature, it may be convenient to initially implem
the code using dynamic typing and only add type hints later once the code is more stable.
Once you are finished migrating or prototyping your code, you can make mypy warn you
if you add a dynamic function by mistake by using the ``--disallow-unchecked-defs``
if you add a dynamic function by mistake by using the ``--disallow-untyped-defs``
flag. See :ref:`command-line` for more information on configuring mypy.
.. note::
......@@ -286,7 +286,7 @@ for example, when assigning an empty dictionary to some global value:
You can teach mypy what type ``my_global_dict`` is meant to have by giving it
a type hint. For example, if you knew this variable is supposed to be a dict
of ints to floats, you could annotate it using either variable annotations
(introduced in Python 3.6 by :ref:`PEP 526 <pep526_>`_) or using a comment-based
(introduced in Python 3.6 by `PEP 526 <pep526_>`_) or using a comment-based
syntax like so:
.. code-block:: python
......
......@@ -54,6 +54,7 @@ Mypy is a static type checker for Python 3 and Python 2.7.
running_mypy
command_line
config_file
inline_config
mypy_daemon
installed_packages
extending_mypy
......
.. _inline-config:
Inline configuration
====================
Mypy supports setting per-file configuration options inside files themselves
using ``# mypy:`` comments. For example:
.. code-block:: python
# mypy: disallow-any-generics
Inline configuration comments take precedence over all other
configuration mechanisms.
Configuration comment format
****************************
Flags correspond to :ref:`config file flags <config-file>` but allow
hyphens to be substituted for underscores.
Values are specified using ``=``, but ``= True`` may be omitted:
.. code-block:: python
# mypy: disallow-any-generics
# mypy: always-true=FOO
Multiple flags can be separated by commas or placed on separate
lines. To include a comma as part of an option's value, place the
value inside quotes:
.. code-block:: python
# mypy: disallow-untyped-defs, always-false="FOO,BAR"
Like in the configuration file, 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):
.. code-block:: python
# mypy: allow-untyped-defs, no-strict-optional
......@@ -496,7 +496,7 @@ overlapping when both of the following are true:
subtype of) the second.
So in this example, the ``int`` argument in the first variant is a subtype of
the ``object`` argument in the second, yet the ``int`` return type not is a subtype of
the ``object`` argument in the second, yet the ``int`` return type is not a subtype of
``str``. Both conditions are true, so mypy will correctly flag ``unsafe_func`` as
being unsafe.
......@@ -740,11 +740,6 @@ and one
TypedDict
*********
.. note::
TypedDict is an officially supported feature, but it is still experimental.
Python programs often use dictionaries with string keys to represent objects.
Here is a typical example:
......@@ -923,7 +918,7 @@ In Python 2 code, these methods are also supported:
* ``has_key(key)``
* ``viewitems()``
* ``viewkeys()``
* ``viervalues()``
* ``viewvalues()``
.. note::
......
......@@ -376,7 +376,8 @@ This is computed from the following items:
For sources given on the command line, the path is adjusted by crawling
up from the given file or package to the nearest directory that does not
contain an ``__init__.py`` or ``__init__.pyi`` file.
contain an ``__init__.py`` or ``__init__.pyi`` file. If the given path
is relative, it will only crawl as far as the current working directory.
Second, mypy searches for stub files in addition to regular Python files
and packages.
......
......@@ -62,20 +62,81 @@ Stub file syntax
Stub files are written in normal Python 3 syntax, but generally
leaving out runtime logic like variable initializers, function bodies,
and default arguments, or replacing them with ellipses.
and default arguments.
In this example, each ellipsis ``...`` is literally written in the
If it is not possible to completely leave out some piece of runtime
logic, the recommended convention is to replace or elide them with ellipsis
expressions (``...``). Each ellipsis below is literally written in the
stub file as three dots:
.. code-block:: python
# Variables with annotations do not need to be assigned a value.
# So by convention, we omit them in the stub file.
x: int
def afunc(code: str) -> int: ...
def afunc(a: int, b: int = ...) -> int: ...
# Function bodies cannot be completely removed. By convention,
# we replace them with `...` instead of the `pass` statement.
def func_1(code: str) -> int: ...
# We can do the same with default arguments.
def func_2(a: int, b: int = ...) -> int: ...
.. note::
The ellipsis ``...`` is also used with a different meaning in
:ref:`callable types <callable-types>` and :ref:`tuple types
<tuple-types>`.
.. note::
It is always legal to use Python 3 syntax in stub files, even when
writing Python 2 code. The example above is a valid stub file
for both Python 2 and 3.
Using stub file syntax at runtime
*********************************
You may also occasionally need to elide actual logic in regular
Python code -- for example, when writing methods in
:ref:`overload variants <function-overloading>` or
:ref:`custom protocols <protocol-types>`.
The recommended style is to use ellipses to do so, just like in
stub files. It is also considered stylistically acceptable to
throw a ``NotImplementedError`` in cases where the user of the
code may accidentally call functions with no actual logic.
You can also elide default arguments as long as the function body
also contains no runtime logic: the function body only contains
a single ellipsis, the pass statement, or a ``raise NotImplementedError()``.
It is also acceptable for the function body to contain a docstring.
For example:
.. code-block:: python
from typing import List
from typing_extensions import Protocol
class Resource(Protocol):
def ok_1(self, foo: List[str] = ...) -> None: ...
def ok_2(self, foo: List[str] = ...) -> None:
raise NotImplementedError()
def ok_3(self, foo: List[str] = ...) -> None:
"""Some docstring"""
pass
# Error: Incompatible default for argument "foo" (default has
# type "ellipsis", argument has type "List[str]")
def not_ok(self, foo: List[str] = ...) -> None:
print(foo)
.. note::
Ellipsis expressions are legal syntax in Python 3 only. This means
it is not possible to elide default arguments in Python 2 code.
You can still elide function bodies in Python 2 by using either
the ``pass`` statement or by throwing a ``NotImplementedError``.