Skip to content

Commit 6f97ae7

Browse files
JukkaLIvan Levkivskyi
authored and
Ivan Levkivskyi
committed
Various doc updates, mostly about list[t] etc. (#9936)
Use the new generic built-in type syntax (list[t] etc.) in the cheat sheet, getting started and built-in types sections. Most examples still use the old syntax, but this at least introduces the new syntax early on. Also other minor documentation tweaks.
1 parent 40e92a2 commit 6f97ae7

7 files changed

+155
-71
lines changed

docs/source/builtin_types.rst

Lines changed: 72 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,94 @@
11
Built-in types
22
==============
33

4-
These are examples of some of the most common built-in types:
4+
This chapter introduces some commonly used built-in types. We will
5+
cover many other kinds of types later.
6+
7+
Simple types
8+
............
9+
10+
Here are examples of some common built-in types:
511

612
====================== ===============================
713
Type Description
814
====================== ===============================
915
``int`` integer
1016
``float`` floating point number
1117
``bool`` boolean value (subclass of ``int``)
12-
``str`` string (unicode)
18+
``str`` string (unicode in Python 3)
1319
``bytes`` 8-bit string
1420
``object`` an arbitrary object (``object`` is the common base class)
21+
====================== ===============================
22+
23+
All built-in classes can be used as types.
24+
25+
Any type
26+
........
27+
28+
If you can't find a good type for some value, you can always fall back
29+
to ``Any``:
30+
31+
====================== ===============================
32+
Type Description
33+
====================== ===============================
34+
``Any`` dynamically typed value with an arbitrary type
35+
====================== ===============================
36+
37+
The type ``Any`` is defined in the :py:mod:`typing` module.
38+
See :ref:`dynamic-typing` for more details.
39+
40+
Generic types
41+
.............
42+
43+
In Python 3.9 and later, built-in collection type objects support
44+
indexing:
45+
46+
====================== ===============================
47+
Type Description
48+
====================== ===============================
49+
``list[str]`` list of ``str`` objects
50+
``tuple[int, int]`` tuple of two ``int`` objects (``tuple[()]`` is the empty tuple)
51+
``tuple[int, ...]`` tuple of an arbitrary number of ``int`` objects
52+
``dict[str, int]`` dictionary from ``str`` keys to ``int`` values
53+
``Iterable[int]`` iterable object containing ints
54+
``Sequence[bool]`` sequence of booleans (read-only)
55+
``Mapping[str, int]`` mapping from ``str`` keys to ``int`` values (read-only)
56+
====================== ===============================
57+
58+
The type ``dict`` is a *generic* class, signified by type arguments within
59+
``[...]``. For example, ``dict[int, str]`` is a dictionary from integers to
60+
strings and ``dict[Any, Any]`` is a dictionary of dynamically typed
61+
(arbitrary) values and keys. ``list`` is another generic class.
62+
63+
``Iterable``, ``Sequence``, and ``Mapping`` are generic types that correspond to
64+
Python protocols. For example, a ``str`` object or a ``list[str]`` object is
65+
valid when ``Iterable[str]`` or ``Sequence[str]`` is expected.
66+
You can import them from :py:mod:`collections.abc` instead of importing from
67+
:py:mod:`typing` in Python 3.9.
68+
69+
See :ref:`generic-builtins` for more details, including how you can
70+
use these in annotations also in Python 3.7 and 3.8.
71+
72+
These legacy types defined in :py:mod:`typing` are needed if you need to support
73+
Python 3.8 and earlier:
74+
75+
====================== ===============================
76+
Type Description
77+
====================== ===============================
1578
``List[str]`` list of ``str`` objects
1679
``Tuple[int, int]`` tuple of two ``int`` objects (``Tuple[()]`` is the empty tuple)
1780
``Tuple[int, ...]`` tuple of an arbitrary number of ``int`` objects
1881
``Dict[str, int]`` dictionary from ``str`` keys to ``int`` values
1982
``Iterable[int]`` iterable object containing ints
2083
``Sequence[bool]`` sequence of booleans (read-only)
2184
``Mapping[str, int]`` mapping from ``str`` keys to ``int`` values (read-only)
22-
``Any`` dynamically typed value with an arbitrary type
2385
====================== ===============================
2486

25-
The type ``Any`` and type constructors such as ``List``, ``Dict``,
26-
``Iterable`` and ``Sequence`` are defined in the :py:mod:`typing` module.
87+
``List`` is an alias for the built-in type ``list`` that supports
88+
indexing (and similarly for ``dict``/``Dict`` and
89+
``tuple``/``Tuple``).
2790

28-
The type ``Dict`` is a *generic* class, signified by type arguments within
29-
``[...]``. For example, ``Dict[int, str]`` is a dictionary from integers to
30-
strings and ``Dict[Any, Any]`` is a dictionary of dynamically typed
31-
(arbitrary) values and keys. ``List`` is another generic class. ``Dict`` and
32-
``List`` are aliases for the built-ins ``dict`` and ``list``, respectively.
33-
34-
``Iterable``, ``Sequence``, and ``Mapping`` are generic types that correspond to
35-
Python protocols. For example, a ``str`` object or a ``List[str]`` object is
36-
valid when ``Iterable[str]`` or ``Sequence[str]`` is expected. Note that even
37-
though they are similar to abstract base classes defined in
38-
:py:mod:`collections.abc` (formerly ``collections``), they are not identical. In
39-
particular, prior to Python 3.9, the built-in collection type objects do not
40-
support indexing.
41-
42-
In Python 3.9 and later, built-in collection type objects support indexing. This
43-
means that you can use built-in classes or those from :py:mod:`collections.abc`
44-
instead of importing from :py:mod:`typing`. See :ref:`generic-builtins` for more
45-
details.
91+
Note that even though ``Iterable``, ``Sequence`` and ``Mapping`` look
92+
similar to abstract base classes defined in :py:mod:`collections.abc`
93+
(formerly ``collections``), they are not identical, since the latter
94+
don't support indexing prior to Python 3.9.

docs/source/cheat_sheet_py3.rst

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,21 +54,29 @@ Built-in types
5454
x: str = "test"
5555
x: bytes = b"test"
5656
57-
# For collections, the name of the type is capitalized, and the
58-
# name of the type inside the collection is in brackets
57+
# For collections, the type of the collection item is in brackets
58+
# (Python 3.9+)
59+
x: list[int] = [1]
60+
x: set[int] = {6, 7}
61+
62+
# In Python 3.8 and earlier, the name of the collection type is
63+
# capitalized, and the type is imported from 'typing'
5964
x: List[int] = [1]
6065
x: Set[int] = {6, 7}
6166
62-
# Same as above, but with type comment syntax
67+
# Same as above, but with type comment syntax (Python 3.5 and earlier)
6368
x = [1] # type: List[int]
6469
6570
# For mappings, we need the types of both keys and values
71+
x: dict[str, float] = {'field': 2.0} # Python 3.9+
6672
x: Dict[str, float] = {'field': 2.0}
6773
6874
# For tuples of fixed size, we specify the types of all the elements
75+
x: tuple[int, str, float] = (3, "yes", 7.5) # Python 3.9+
6976
x: Tuple[int, str, float] = (3, "yes", 7.5)
7077
7178
# For tuples of variable size, we use one type and ellipsis
79+
x: tuple[int, ...] = (1, 2, 3) # Python 3.9+
7280
x: Tuple[int, ...] = (1, 2, 3)
7381
7482
# Use Optional[] for values that could be None

docs/source/config_file.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,7 @@ section of the command line docs.
538538
:default: False
539539

540540
Disallows inferring variable type for ``None`` from two assignments in different scopes.
541+
This is always implicitly enabled when using the :ref:`mypy daemon <mypy_daemon>`.
541542

542543
.. confval:: disable_error_code
543544

docs/source/getting_started.rst

Lines changed: 48 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -160,22 +160,19 @@ Arguments with default values can be annotated like so:
160160
for key, value in kwargs:
161161
print(key, value)
162162
163-
The typing module
164-
*****************
163+
Additional types, and the typing module
164+
***************************************
165165

166166
So far, we've added type hints that use only basic concrete types like
167167
``str`` and ``float``. What if we want to express more complex types,
168168
such as "a list of strings" or "an iterable of ints"?
169169

170-
You can find many of these more complex static types inside of the :py:mod:`typing`
171-
module. For example, to indicate that some function can accept a list of
172-
strings, use the :py:class:`~typing.List` type:
170+
For example, to indicate that some function can accept a list of
171+
strings, use the ``list[str]`` type (Python 3.9 and later):
173172

174173
.. code-block:: python
175174
176-
from typing import List
177-
178-
def greet_all(names: List[str]) -> None:
175+
def greet_all(names: list[str]) -> None:
179176
for name in names:
180177
print('Hello ' + name)
181178
@@ -185,20 +182,38 @@ strings, use the :py:class:`~typing.List` type:
185182
greet_all(names) # Ok!
186183
greet_all(ages) # Error due to incompatible types
187184
188-
The :py:class:`~typing.List` type is an example of something called a *generic type*: it can
189-
accept one or more *type parameters*. In this case, we *parameterized* :py:class:`~typing.List`
190-
by writing ``List[str]``. This lets mypy know that ``greet_all`` accepts specifically
185+
The ``list`` type is an example of something called a *generic type*: it can
186+
accept one or more *type parameters*. In this case, we *parameterized* ``list``
187+
by writing ``list[str]``. This lets mypy know that ``greet_all`` accepts specifically
191188
lists containing strings, and not lists containing ints or any other type.
192189

193-
In this particular case, the type signature is perhaps a little too rigid.
190+
In Python 3.8 and earlier, you can instead import the
191+
:py:class:`~typing.List` type from the :py:mod:`typing` module:
192+
193+
.. code-block:: python
194+
195+
from typing import List # Python 3.8 and earlier
196+
197+
def greet_all(names: List[str]) -> None:
198+
for name in names:
199+
print('Hello ' + name)
200+
201+
...
202+
203+
You can find many of these more complex static types in the :py:mod:`typing` module.
204+
205+
In the above examples, the type signature is perhaps a little too rigid.
194206
After all, there's no reason why this function must accept *specifically* a list --
195207
it would run just fine if you were to pass in a tuple, a set, or any other custom iterable.
196208

197-
You can express this idea using the :py:class:`~typing.Iterable` type instead of :py:class:`~typing.List`:
209+
You can express this idea using the
210+
:py:class:`collections.abc.Iterable` type instead of
211+
:py:class:`~typing.List` (or :py:class:`typing.Iterable` in Python
212+
3.8 and earlier):
198213

199214
.. code-block:: python
200215
201-
from typing import Iterable
216+
from collections.abc import Iterable # or "from typing import Iterable"
202217
203218
def greet_all(names: Iterable[str]) -> None:
204219
for name in names:
@@ -239,13 +254,21 @@ and a more detailed overview (including information on how to make your own
239254
generic types or your own type aliases) by looking through the
240255
:ref:`type system reference <overview-type-system-reference>`.
241256

242-
One final note: when adding types, the convention is to import types
243-
using the form ``from typing import Iterable`` (as opposed to doing
244-
just ``import typing`` or ``import typing as t`` or ``from typing import *``).
257+
.. note::
258+
259+
When adding types, the convention is to import types
260+
using the form ``from typing import Union`` (as opposed to doing
261+
just ``import typing`` or ``import typing as t`` or ``from typing import *``).
245262

246-
For brevity, we often omit these :py:mod:`typing` imports in code examples, but
247-
mypy will give an error if you use types such as :py:class:`~typing.Iterable`
248-
without first importing them.
263+
For brevity, we often omit imports from :py:mod:`typing` or :py:mod:`collections.abc`
264+
in code examples, but mypy will give an error if you use types such as
265+
:py:class:`~typing.Iterable` without first importing them.
266+
267+
.. note::
268+
269+
In some examples we use capitalized variants of types, such as
270+
``List``, and sometimes we use plain ``list``. They are equivalent,
271+
but the prior variant is needed if you are not using a recent Python.
249272

250273
Local type inference
251274
********************
@@ -267,7 +290,7 @@ of type ``List[float]`` and that ``num`` must be of type ``float``:
267290

268291
.. code-block:: python
269292
270-
def nums_below(numbers: Iterable[float], limit: float) -> List[float]:
293+
def nums_below(numbers: Iterable[float], limit: float) -> list[float]:
271294
output = []
272295
for num in numbers:
273296
if num < limit:
@@ -289,10 +312,13 @@ syntax like so:
289312

290313
.. code-block:: python
291314
315+
# If you're using Python 3.9+
316+
my_global_dict: dict[int, float] = {}
317+
292318
# If you're using Python 3.6+
293319
my_global_dict: Dict[int, float] = {}
294320
295-
# If you want compatibility with older versions of Python
321+
# If you want compatibility with even older versions of Python
296322
my_global_dict = {} # type: Dict[int, float]
297323
298324
.. _stubs-intro:

docs/source/index.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ Mypy is a static type checker for Python 3 and Python 2.7.
3737
class_basics
3838
runtime_troubles
3939
protocols
40-
python2
4140
dynamic_typing
41+
python2
4242
casts
4343
duck_type_compatibility
4444
stubs

docs/source/kinds_of_types.rst

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -241,27 +241,6 @@ more specific type:
241241
since the caller may have to use :py:func:`isinstance` before doing anything
242242
interesting with the value.
243243

244-
.. _alternative_union_syntax:
245-
246-
X | Y syntax for Unions
247-
-----------------------
248-
249-
:pep:`604` introduced an alternative way for spelling union types. In Python
250-
3.10 and later, you can write ``Union[int, str]`` as ``int | str``. It is
251-
possible to use this syntax in versions of Python where it isn't supported by
252-
the runtime with some limitations, see :ref:`runtime_troubles`.
253-
254-
.. code-block:: python
255-
256-
from typing import List
257-
258-
t1: int | str # equivalent to Union[int, str]
259-
260-
t2: int | None # equivalent to Optional[int]
261-
262-
# Usable in type comments
263-
t3 = 42 # type: int | str
264-
265244
.. _strict_optional:
266245

267246
Optional types and the None type
@@ -428,6 +407,27 @@ case you should add an explicit ``Optional[...]`` annotation (or type comment).
428407
``Optional[...]`` type. It's possible that this will become the default
429408
behavior in the future.
430409

410+
.. _alternative_union_syntax:
411+
412+
X | Y syntax for Unions
413+
-----------------------
414+
415+
:pep:`604` introduced an alternative way for spelling union types. In Python
416+
3.10 and later, you can write ``Union[int, str]`` as ``int | str``. It is
417+
possible to use this syntax in versions of Python where it isn't supported by
418+
the runtime with some limitations (see :ref:`runtime_troubles`).
419+
420+
.. code-block:: python
421+
422+
from typing import List
423+
424+
t1: int | str # equivalent to Union[int, str]
425+
426+
t2: int | None # equivalent to Optional[int]
427+
428+
# Usable in type comments
429+
t3 = 42 # type: int | str
430+
431431
.. _no_strict_optional:
432432

433433
Disabling strict optional checking

docs/source/running_mypy.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ How mypy determines fully qualified module names depends on if the options
397397
With :option:`--explicit-package-bases <mypy --explicit-package-bases>`, mypy
398398
will locate the nearest parent directory that is a member of the ``MYPYPATH``
399399
environment variable, the :confval:`mypy_path` config or is the current
400-
working directory. mypy will then use the relative path to determine the
400+
working directory. Mypy will then use the relative path to determine the
401401
fully qualified module name.
402402

403403
For example, say your directory tree consists solely of

0 commit comments

Comments
 (0)