Skip to content

Commit 4825e34

Browse files
author
Guido van Rossum
committed
Update basic mypy docs.
- Remove some phrasings that still sound like mypy is a separate language. - Remove mention of `import typing` to trigger type checking. - Note spurious messages from semantic analysis. - Update instructions for writing stubs. - Warn against setting MYPYPATH to sys.path or site-packages.
1 parent 110842c commit 4825e34

File tree

1 file changed

+81
-83
lines changed

1 file changed

+81
-83
lines changed

docs/source/basics.rst

+81-83
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,29 @@ as the rest of documentation may not make much sense otherwise.
88
Function signatures
99
*******************
1010

11-
A function without a type signature is dynamically typed. You can
12-
declare the signature of a function using the Python 3 annotation
13-
syntax (Python 2 is discussed later in :ref:`python2`.) This makes the
14-
function statically typed (the type checker reports type errors within
15-
the function). A function without a type annotation is dynamically
16-
typed, and identical to ordinary Python:
11+
A function without a type annotation is considered dynamically typed:
1712

1813
.. code-block:: python
1914
2015
def greeting(name):
2116
return 'Hello, {}'.format(name)
2217
23-
This version of the above function is statically typed (but it's still
24-
valid Python):
18+
You can declare the signature of a function using the Python 3
19+
annotation syntax (Python 2 is discussed later in :ref:`python2`).
20+
This makes the the function statically typed, and that causes type
21+
checker report type errors within the function.
22+
23+
Here's a version of the above function is statically typed and will be
24+
type checked:
2525

2626
.. code-block:: python
2727
2828
def greeting(name: str) -> str:
2929
return 'Hello, {}'.format(name)
3030
31-
A ``None`` return type indicates a function that does not explicitly
32-
return a value. Using a ``None`` result in a statically typed context
33-
results in a type check error:
31+
If a function does not explicitly return a value we give the return
32+
type as ``None``. Using a ``None`` result in a statically typed
33+
context results in a type check error:
3434

3535
.. code-block:: python
3636
@@ -39,22 +39,36 @@ results in a type check error:
3939
4040
a = p() # Type check error: p has None return value
4141
42-
The typing module
43-
*****************
42+
Mixing dynamic and static typing
43+
********************************
4444

45-
We cheated a bit in the above examples: a module is type checked only
46-
if it imports the module ``typing``. Here is a complete statically typed
47-
example from the previous section:
45+
Mixing dynamic and static typing within a single file is often
46+
useful. For example, if you are migrating existing Python code to
47+
static typing, it may be easiest to do this incrementally, such as by
48+
migrating a few functions at a time. Also, when prototyping a new
49+
feature, you may decide to first implement the relevant code using
50+
dynamic typing and only add type signatures later, when the code is
51+
more stable.
4852

4953
.. code-block:: python
5054
51-
import typing
55+
def f():
56+
1 + 'x' # No static type error (dynamically typed)
5257
53-
def greeting(name: str) -> str:
54-
return 'Hello, {}'.format(name)
58+
def g() -> None:
59+
1 + 'x' # Type check error (statically typed)
60+
61+
.. note::
62+
63+
The earlier stages of mypy, known as the semantic analysis, may
64+
report errors even for dynamically typed functions. However, you
65+
should not rely on this, as this may change in the future.
66+
67+
The typing module
68+
*****************
5569

5670
The ``typing`` module contains many definitions that are useful in
57-
statically typed code. You can also use ``from ... import`` to import
71+
statically typed code. You typically use ``from ... import`` to import
5872
them (we'll explain ``Iterable`` later in this document):
5973

6074
.. code-block:: python
@@ -69,32 +83,9 @@ For brevity, we often omit the ``typing`` import in code examples, but
6983
you should always include it in modules that contain statically typed
7084
code.
7185

72-
You can still have dynamically typed functions in modules that import ``typing``:
73-
74-
.. code-block:: python
75-
76-
import typing
77-
78-
def f():
79-
1 + 'x' # No static type error (dynamically typed)
80-
81-
def g() -> None:
82-
1 + 'x' # Type check error (statically typed)
83-
84-
Mixing dynamic and static typing within a single file is often
85-
useful. For example, if you are migrating existing Python code to
86-
static typing, it may be easiest to do this incrementally, such as by
87-
migrating a few functions at a time. Also, when prototyping a new
88-
feature, you may decide to first implement the relevant code using
89-
dynamic typing and only add type signatures later, when the code is
90-
more stable.
91-
92-
.. note::
93-
94-
Currently the type checker checks the top levels and annotated
95-
functions of all modules, even those that don't import
96-
``typing``. However, you should not rely on this, as this will change
97-
in the future.
86+
The presence or absence of the ``typing`` module does not affect
87+
whether your code is type checked; it is only required when you use
88+
one or more special features it defines.
9889

9990
Type checking and running programs
10091
**********************************
@@ -105,22 +96,19 @@ running it::
10596

10697
$ mypy program.py
10798

108-
You can always run a mypy program as a Python program, without type
109-
checking, even if it has type errors::
110-
111-
$ python3 program.py
112-
11399
All errors reported by mypy are essentially warnings that you are free
114100
to ignore, if you so wish.
115101

116-
The `README <https://github.com/JukkaL/mypy/blob/master/README.md>`_
102+
The `README <https://github.com/python/mypy/blob/master/README.md>`_
117103
explains how to download and install mypy.
118104

119105
.. note::
120106

121107
Depending on how mypy is configured, you may have to explicitly use
122-
the Python interpreter to run mypy. The mypy tool is an ordinary
123-
mypy (and so also Python) program.
108+
the Python 3 interpreter to run mypy. The mypy tool is an ordinary
109+
mypy (and so also Python) program. For example::
110+
111+
$ python3 -m mypy program.py
124112

125113
.. _library-stubs:
126114

@@ -131,57 +119,67 @@ In order to type check code that uses library modules such as those
131119
included in the Python standard library, you need to have library
132120
*stubs*. A library stub defines a skeleton of the public interface
133121
of the library, including classes, variables and functions and
134-
their types, but empty function bodies (containing only ``pass``).
122+
their types, but dummy function bodies.
135123

136124
For example, consider this code:
137125

138126
.. code-block:: python
139127
140128
x = chr(4)
141129
142-
Without a library stub, the type checker has no way of inferring the
143-
type of ``x`` and checking that the argument to ``chr`` has a valid
144-
type. Mypy contains the `typeshed <http://github.com/python/typeshed>`_ project,
145-
which contains library stubs for Python builtins that contains a definition
146-
like this for ``chr``:
130+
Without a library stub, the type checker would have no way of
131+
inferring the type of ``x`` and checking that the argument to ``chr``
132+
has a valid type. Mypy incorporates the `typeshed
133+
<http://github.com/python/typeshed>`_ project, which contains library
134+
stubs for the Python builtins and the standard library. The stub for
135+
the builtins contains a definition like this for ``chr``:
147136

148137
.. code-block:: python
149138
150-
def chr(code: int) -> str: pass
139+
def chr(code: int) -> str: ...
140+
141+
In stubs we don't care about the function bodies, so we use an
142+
ellipsis instead. That ``...`` is three literal dots!
151143

152-
Mypy complains if it can't find a stub for a library module that you
153-
import. You can create a stub easily; here is an overview:
144+
Mypy complains if it can't find a stub (or a real module) for a
145+
library module that you import. You can create a stub easily; here is
146+
an overview:
154147

155-
* Write a stub file for the library and store it as a ``.pyi`` file within
156-
the mypy module search path. The Python interpreter will ignore the ``.pyi`` file,
157-
so you can have stubs and normal Python files in the same directory.
158-
* Alternatively, create a ``.py`` file in
159-
a directory reserved for stubs (e.g., ``myproject/stubs``). Also, you have
160-
to set the environment variable ``MYPYPATH`` to refer to the above directory.
161-
For example::
148+
* Write a stub file for the library and store it as a ``.pyi`` file in
149+
the same directory as the library module.
150+
* Alternatively, put your stubs (``.pyi`` files) in a directory
151+
reserved for stubs (e.g., ``myproject/stubs``). In this case you
152+
have to set the environment variable ``MYPYPATH`` to refer to the
153+
directory. For example::
162154

163155
$ export MYPYPATH=~/work/myproject/stubs
164156

165157
Use the normal Python file name conventions for modules, e.g. ``csv.pyi``
166-
for module ``csv``, and use a subdirectory with ``__init__.pyi`` for packages.
167-
168-
If there is both a ``.py`` and a ``.pyi`` file for a module, the ``.pyi`` file
169-
takes precedence. This way you can easily add annotations for a module even if
170-
you don't want to modify the source code. This can be useful, for example, if you
171-
use 3rd party open source libraries in your program.
158+
for module ``csv``. Use a subdirectory with ``__init__.pyi`` for packages.
172159

173-
You can also override the stubs mypy uses for standard library modules, in case
174-
you need to make local modifications. (Note that if you want to submit your
175-
changes, please submit a pull request to `typeshed <http://github.com/python/typeshed>`_
176-
first, and then update the submodule in mypy using a commit that only touches
177-
the typeshed submodule and nothing else)
160+
If a directory contains both a ``.py`` and a ``.pyi`` file for the
161+
same module, the ``.pyi`` file takes precedence. This way you can
162+
easily add annotations for a module even if you don't want to modify
163+
the source code. This can be useful, for example, if you use 3rd party
164+
open source libraries in your program (and there are no stubs in
165+
typeshed yet).
178166

179167
That's it! Now you can access the module in mypy programs and type check
180168
code that uses the library. If you write a stub for a library module,
181-
consider making it available for other programmers that use mypy or
182-
contributing it to mypy.
169+
consider making it available for other programmers that use mypy
170+
by contributing it back to the typeshed repo.
183171

184172
There is more information about creating stubs in the
185173
`mypy wiki <https://github.com/python/mypy/wiki/Creating-Stubs-For-Python-Modules>`_.
186174
The following sections explain the kinds of type annotations you can use
187175
in your programs and stub files.
176+
177+
.. note::
178+
179+
You may be tempted to point ``MYPYPATH`` to the standard library or
180+
to the ``site-packages`` directory where your 3rd party packages
181+
are installed. This is almost always a bad idea -- you will likely
182+
get tons of error messages about code you didn't write and that
183+
mypy can't analyze all that well yet, and in the worst case
184+
scenario mypy may crash due to some construct in a 3rd party
185+
package that it didn't expect.

0 commit comments

Comments
 (0)