Skip to content

Commit 28a5853

Browse files
hoeflinggvanrossum
authored andcommitted
Crossreferences to standard library in mypy docs, part 7 (#7699)
Signed-off-by: Oleg Höfling <[email protected]>
1 parent 0e41cce commit 28a5853

File tree

1 file changed

+94
-60
lines changed

1 file changed

+94
-60
lines changed

docs/source/protocols.rst

Lines changed: 94 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ inherits class ``C``, it's also a subtype of ``C``, and instances of
1010
``D`` can be used when ``C`` instances are expected. This form of
1111
subtyping is used by default in mypy, since it's easy to understand
1212
and produces clear and concise error messages, and since it matches
13-
how the native ``isinstance()`` check works -- based on class
13+
how the native :py:func:`isinstance <isinstance>` check works -- based on class
1414
hierarchy. *Structural* subtyping can also be useful. Class ``D`` is
1515
a structural subtype of class ``C`` if the former has all attributes
1616
and methods of the latter, and with compatible types.
@@ -26,10 +26,10 @@ and structural subtyping in Python.
2626
Predefined protocols
2727
********************
2828

29-
The ``typing`` module defines various protocol classes that correspond
30-
to common Python protocols, such as ``Iterable[T]``. If a class
31-
defines a suitable ``__iter__`` method, mypy understands that it
32-
implements the iterable protocol and is compatible with ``Iterable[T]``.
29+
The :py:mod:`typing` module defines various protocol classes that correspond
30+
to common Python protocols, such as :py:class:`Iterable[T] <typing.Iterable>`. If a class
31+
defines a suitable :py:meth:`__iter__ <object.__iter__>` method, mypy understands that it
32+
implements the iterable protocol and is compatible with :py:class:`Iterable[T] <typing.Iterable>`.
3333
For example, ``IntList`` below is iterable, over ``int`` values:
3434

3535
.. code-block:: python
@@ -56,7 +56,7 @@ For example, ``IntList`` below is iterable, over ``int`` values:
5656
print_numbered([4, 5]) # Also OK
5757
5858
The subsections below introduce all built-in protocols defined in
59-
``typing`` and the signatures of the corresponding methods you need to define
59+
:py:mod:`typing` and the signatures of the corresponding methods you need to define
6060
to implement each protocol (the signatures can be left out, as always, but mypy
6161
won't type check unannotated methods).
6262

@@ -66,170 +66,200 @@ Iteration protocols
6666
The iteration protocols are useful in many contexts. For example, they allow
6767
iteration of objects in for loops.
6868

69-
``Iterable[T]``
70-
---------------
69+
Iterable[T]
70+
-----------
7171

7272
The :ref:`example above <predefined_protocols>` has a simple implementation of an
73-
``__iter__`` method.
73+
:py:meth:`__iter__ <object.__iter__>` method.
7474

7575
.. code-block:: python
7676
7777
def __iter__(self) -> Iterator[T]
7878
79-
``Iterator[T]``
80-
---------------
79+
See also :py:class:`~typing.Iterable`.
80+
81+
Iterator[T]
82+
-----------
8183

8284
.. code-block:: python
8385
8486
def __next__(self) -> T
8587
def __iter__(self) -> Iterator[T]
8688
89+
See also :py:class:`~typing.Iterator`.
90+
8791
Collection protocols
8892
....................
8993

9094
Many of these are implemented by built-in container types such as
91-
``list`` and ``dict``, and these are also useful for user-defined
95+
:py:class:`list` and :py:class:`dict`, and these are also useful for user-defined
9296
collection objects.
9397

94-
``Sized``
95-
---------
98+
Sized
99+
-----
96100

97-
This is a type for objects that support ``len(x)``.
101+
This is a type for objects that support :py:func:`len(x) <len>`.
98102

99103
.. code-block:: python
100104
101105
def __len__(self) -> int
102106
103-
``Container[T]``
104-
----------------
107+
See also :py:class:`~typing.Sized`.
108+
109+
Container[T]
110+
------------
105111

106112
This is a type for objects that support the ``in`` operator.
107113

108114
.. code-block:: python
109115
110116
def __contains__(self, x: object) -> bool
111117
112-
``Collection[T]``
113-
-----------------
118+
See also :py:class:`~typing.Container`.
119+
120+
Collection[T]
121+
-------------
114122

115123
.. code-block:: python
116124
117125
def __len__(self) -> int
118126
def __iter__(self) -> Iterator[T]
119127
def __contains__(self, x: object) -> bool
120128
129+
See also :py:class:`~typing.Collection`.
130+
121131
One-off protocols
122132
.................
123133

124134
These protocols are typically only useful with a single standard
125135
library function or class.
126136

127-
``Reversible[T]``
128-
-----------------
137+
Reversible[T]
138+
-------------
129139

130-
This is a type for objects that support ``reversed(x)``.
140+
This is a type for objects that support :py:func:`reversed(x) <reversed>`.
131141

132142
.. code-block:: python
133143
134144
def __reversed__(self) -> Iterator[T]
135145
136-
``SupportsAbs[T]``
137-
------------------
146+
See also :py:class:`~typing.Reversible`.
138147
139-
This is a type for objects that support ``abs(x)``. ``T`` is the type of
140-
value returned by ``abs(x)``.
148+
SupportsAbs[T]
149+
--------------
150+
151+
This is a type for objects that support :py:func:`abs(x) <abs>`. ``T`` is the type of
152+
value returned by :py:func:`abs(x) <abs>`.
141153

142154
.. code-block:: python
143155
144156
def __abs__(self) -> T
145157
146-
``SupportsBytes``
147-
-----------------
158+
See also :py:class:`~typing.SupportsAbs`.
148159
149-
This is a type for objects that support ``bytes(x)``.
160+
SupportsBytes
161+
-------------
162+
163+
This is a type for objects that support :py:class:`bytes(x) <bytes>`.
150164

151165
.. code-block:: python
152166
153167
def __bytes__(self) -> bytes
154168
169+
See also :py:class:`~typing.SupportsBytes`.
170+
155171
.. _supports-int-etc:
156172

157-
``SupportsComplex``
158-
-------------------
173+
SupportsComplex
174+
---------------
159175

160-
This is a type for objects that support ``complex(x)``. Note that no arithmetic operations
176+
This is a type for objects that support :py:class:`complex(x) <complex>`. Note that no arithmetic operations
161177
are supported.
162178

163179
.. code-block:: python
164180
165181
def __complex__(self) -> complex
166182
167-
``SupportsFloat``
168-
-----------------
183+
See also :py:class:`~typing.SupportsComplex`.
169184
170-
This is a type for objects that support ``float(x)``. Note that no arithmetic operations
185+
SupportsFloat
186+
-------------
187+
188+
This is a type for objects that support :py:class:`float(x) <float>`. Note that no arithmetic operations
171189
are supported.
172190

173191
.. code-block:: python
174192
175193
def __float__(self) -> float
176194
177-
``SupportsInt``
178-
---------------
195+
See also :py:class:`~typing.SupportsFloat`.
179196
180-
This is a type for objects that support ``int(x)``. Note that no arithmetic operations
197+
SupportsInt
198+
-----------
199+
200+
This is a type for objects that support :py:class:`int(x) <int>`. Note that no arithmetic operations
181201
are supported.
182202

183203
.. code-block:: python
184204
185205
def __int__(self) -> int
186206
187-
``SupportsRound[T]``
188-
--------------------
207+
See also :py:class:`~typing.SupportsInt`.
208+
209+
SupportsRound[T]
210+
----------------
189211

190-
This is a type for objects that support ``round(x)``.
212+
This is a type for objects that support :py:func:`round(x) <round>`.
191213

192214
.. code-block:: python
193215
194216
def __round__(self) -> T
195217
218+
See also :py:class:`~typing.SupportsRound`.
219+
196220
Async protocols
197221
...............
198222

199223
These protocols can be useful in async code. See :ref:`async-and-await`
200224
for more information.
201225

202-
``Awaitable[T]``
203-
----------------
226+
Awaitable[T]
227+
------------
204228

205229
.. code-block:: python
206230
207231
def __await__(self) -> Generator[Any, None, T]
208232
209-
``AsyncIterable[T]``
210-
--------------------
233+
See also :py:class:`~typing.Awaitable`.
234+
235+
AsyncIterable[T]
236+
----------------
211237

212238
.. code-block:: python
213239
214240
def __aiter__(self) -> AsyncIterator[T]
215241
216-
``AsyncIterator[T]``
217-
--------------------
242+
See also :py:class:`~typing.AsyncIterable`.
243+
244+
AsyncIterator[T]
245+
----------------
218246

219247
.. code-block:: python
220248
221249
def __anext__(self) -> Awaitable[T]
222250
def __aiter__(self) -> AsyncIterator[T]
223251
252+
See also :py:class:`~typing.AsyncIterator`.
253+
224254
Context manager protocols
225255
.........................
226256

227257
There are two protocols for context managers -- one for regular context
228258
managers and one for async ones. These allow defining objects that can
229259
be used in ``with`` and ``async with`` statements.
230260

231-
``ContextManager[T]``
232-
---------------------
261+
ContextManager[T]
262+
-----------------
233263

234264
.. code-block:: python
235265
@@ -239,8 +269,10 @@ be used in ``with`` and ``async with`` statements.
239269
exc_value: Optional[BaseException],
240270
traceback: Optional[TracebackType]) -> Optional[bool]
241271
242-
``AsyncContextManager[T]``
243-
--------------------------
272+
See also :py:class:`~typing.ContextManager`.
273+
274+
AsyncContextManager[T]
275+
----------------------
244276

245277
.. code-block:: python
246278
@@ -250,6 +282,8 @@ be used in ``with`` and ``async with`` statements.
250282
exc_value: Optional[BaseException],
251283
traceback: Optional[TracebackType]) -> Awaitable[Optional[bool]]
252284
285+
See also :py:class:`~typing.AsyncContextManager`.
286+
253287
Simple user-defined protocols
254288
*****************************
255289

@@ -278,7 +312,7 @@ class:
278312
close_all([Resource(), open('some/file')]) # Okay!
279313
280314
``Resource`` is a subtype of the ``SupportsClose`` protocol since it defines
281-
a compatible ``close`` method. Regular file objects returned by ``open()`` are
315+
a compatible ``close`` method. Regular file objects returned by :py:func:`open` are
282316
similarly compatible with the protocol, as they support ``close()``.
283317

284318
.. note::
@@ -379,7 +413,7 @@ such as trees and linked lists:
379413
Using isinstance() with protocols
380414
*********************************
381415

382-
You can use a protocol class with ``isinstance()`` if you decorate it
416+
You can use a protocol class with :py:func:`isinstance` if you decorate it
383417
with the ``@runtime_checkable`` class decorator. The decorator adds
384418
support for basic runtime structural checks:
385419

@@ -399,11 +433,11 @@ support for basic runtime structural checks:
399433
if isinstance(mug, Portable):
400434
use(mug.handles) # Works statically and at runtime
401435
402-
``isinstance()`` also works with the :ref:`predefined protocols <predefined_protocols>`
403-
in ``typing`` such as ``Iterable``.
436+
:py:func:`isinstance` also works with the :ref:`predefined protocols <predefined_protocols>`
437+
in :py:mod:`typing` such as :py:class:`~typing.Iterable`.
404438

405439
.. note::
406-
``isinstance()`` with protocols is not completely safe at runtime.
440+
:py:func:`isinstance` with protocols is not completely safe at runtime.
407441
For example, signatures of methods are not checked. The runtime
408442
implementation only checks that all protocol members are defined.
409443

@@ -413,8 +447,8 @@ Callback protocols
413447
******************
414448

415449
Protocols can be used to define flexible callback types that are hard
416-
(or even impossible) to express using the ``Callable[...]`` syntax, such as variadic,
417-
overloaded, and complex generic callbacks. They are defined with a special ``__call__``
450+
(or even impossible) to express using the :py:data:`Callable[...] <typing.Callable>` syntax, such as variadic,
451+
overloaded, and complex generic callbacks. They are defined with a special :py:meth:`__call__ <object.__call__>`
418452
member:
419453

420454
.. code-block:: python
@@ -438,8 +472,8 @@ member:
438472
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
439473
# different name and kind in the callback
440474
441-
Callback protocols and ``Callable[...]`` types can be used interchangeably.
442-
Keyword argument names in ``__call__`` methods must be identical, unless
475+
Callback protocols and :py:data:`~typing.Callable` types can be used interchangeably.
476+
Keyword argument names in :py:meth:`__call__ <object.__call__>` methods must be identical, unless
443477
a double underscore prefix is used. For example:
444478

445479
.. code-block:: python

0 commit comments

Comments
 (0)