Debian Codegraph @

docs/source/protocols.rst

raw
1 .. _protocol-types:
2
3 Protocols and structural subtyping
4 ==================================
5
6 The Python type system supports two ways of deciding whether two objects are
7 compatible as types: nominal subtyping and structural subtyping.
8
9 *Nominal* subtyping is strictly based on the class hierarchy. If class ``Dog``
10 inherits class ``Animal``, it's a subtype of ``Animal``. Instances of ``Dog``
11 can be used when ``Animal`` instances are expected. This form of subtyping
12 is what Python's type system predominantly uses: it's easy to
13 understand and produces clear and concise error messages, and matches how the
14 native :py:func:`isinstance <isinstance>` check works -- based on class
15 hierarchy.
16
17 *Structural* subtyping is based on the operations that can be performed with an
18 object. Class ``Dog`` is a structural subtype of class ``Animal`` if the former
19 has all attributes and methods of the latter, and with compatible types.
20
21 Structural subtyping can be seen as a static equivalent of duck typing, which is
22 well known to Python programmers. See :pep:`544` for the detailed specification
23 of protocols and structural subtyping in Python.
24
25 .. _predefined_protocols:
26
27 Predefined protocols
28 ********************
29
30 The :py:mod:`collections.abc`, :py:mod:`typing` and other stdlib modules define
31 various protocol classes that correspond to common Python protocols, such as
32 :py:class:`Iterable[T] <collections.abc.Iterable>`. If a class
33 defines a suitable :py:meth:`__iter__ <object.__iter__>` method, mypy understands that it
34 implements the iterable protocol and is compatible with :py:class:`Iterable[T] <collections.abc.Iterable>`.
35 For example, ``IntList`` below is iterable, over ``int`` values:
36
37 .. code-block:: python
38
39 from __future__ import annotations
40
41 from collections.abc import Iterator, Iterable
42
43 class IntList:
44 def __init__(self, value: int, next: IntList | None) -> None:
45 self.value = value
46 self.next = next
47
48 def __iter__(self) -> Iterator[int]:
49 current = self
50 while current:
51 yield current.value
52 current = current.next
53
54 def print_numbered(items: Iterable[int]) -> None:
55 for n, x in enumerate(items):
56 print(n + 1, x)
57
58 x = IntList(3, IntList(5, None))
59 print_numbered(x) # OK
60 print_numbered([4, 5]) # Also OK
61
62 :ref:`predefined_protocols_reference` lists various protocols defined in
63 :py:mod:`collections.abc` and :py:mod:`typing` and the signatures of the corresponding methods
64 you need to define to implement each protocol.
65
66 .. note::
67 ``typing`` also contains deprecated aliases to protocols and ABCs defined in
68 :py:mod:`collections.abc`, such as :py:class:`Iterable[T] <typing.Iterable>`.
69
70 Simple user-defined protocols
71 *****************************
72
73 You can define your own protocol class by inheriting the special ``Protocol``
74 class:
75
76 .. code-block:: python
77
78 from collections.abc import Iterable
79 from typing import Protocol
80
81 class SupportsClose(Protocol):
82 # Empty method body (explicit '...')
83 def close(self) -> None: ...
84
85 class Resource: # No SupportsClose base class!
86
87 def close(self) -> None:
88 self.resource.release()
89
90 # ... other methods ...
91
92 def close_all(items: Iterable[SupportsClose]) -> None:
93 for item in items:
94 item.close()
95
96 close_all([Resource(), open('some/file')]) # OK
97
98 ``Resource`` is a subtype of the ``SupportsClose`` protocol since it defines
99 a compatible ``close`` method. Regular file objects returned by :py:func:`open` are
100 similarly compatible with the protocol, as they support ``close()``.
101
102 Defining subprotocols and subclassing protocols
103 ***********************************************
104
105 You can also define subprotocols. Existing protocols can be extended
106 and merged using multiple inheritance. Example:
107
108 .. code-block:: python
109
110 # ... continuing from the previous example
111
112 class SupportsRead(Protocol):
113 def read(self, amount: int) -> bytes: ...
114
115 class TaggedReadableResource(SupportsClose, SupportsRead, Protocol):
116 label: str
117
118 class AdvancedResource(Resource):
119 def __init__(self, label: str) -> None:
120 self.label = label
121
122 def read(self, amount: int) -> bytes:
123 # some implementation
124 ...
125
126 resource: TaggedReadableResource
127 resource = AdvancedResource('handle with care') # OK
128
129 Note that inheriting from an existing protocol does not automatically
130 turn the subclass into a protocol -- it just creates a regular
131 (non-protocol) class or ABC that implements the given protocol (or
132 protocols). The ``Protocol`` base class must always be explicitly
133 present if you are defining a protocol:
134
135 .. code-block:: python
136
137 class NotAProtocol(SupportsClose): # This is NOT a protocol
138 new_attr: int
139
140 class Concrete:
141 new_attr: int = 0
142
143 def close(self) -> None:
144 ...
145
146 # Error: nominal subtyping used by default
147 x: NotAProtocol = Concrete() # Error!
148
149 You can also include default implementations of methods in
150 protocols. If you explicitly subclass these protocols you can inherit
151 these default implementations.
152
153 Explicitly including a protocol as a
154 base class is also a way of documenting that your class implements a
155 particular protocol, and it forces mypy to verify that your class
156 implementation is actually compatible with the protocol. In particular,
157 omitting a value for an attribute or a method body will make it implicitly
158 abstract:
159
160 .. code-block:: python
161
162 class SomeProto(Protocol):
163 attr: int # Note, no right hand side
164 def method(self) -> str: ... # Literally just ... here
165
166 class ExplicitSubclass(SomeProto):
167 pass
168
169 ExplicitSubclass() # error: Cannot instantiate abstract class 'ExplicitSubclass'
170 # with abstract attributes 'attr' and 'method'
171
172 Similarly, explicitly assigning to a protocol instance can be a way to ask the
173 type checker to verify that your class implements a protocol:
174
175 .. code-block:: python
176
177 _proto: SomeProto = cast(ExplicitSubclass, None)
178
179 Invariance of protocol attributes
180 *********************************
181
182 A common issue with protocols is that protocol attributes are invariant.
183 For example:
184
185 .. code-block:: python
186
187 class Box(Protocol):
188 content: object
189
190 class IntBox:
191 content: int
192
193 def takes_box(box: Box) -> None: ...
194
195 takes_box(IntBox()) # error: Argument 1 to "takes_box" has incompatible type "IntBox"; expected "Box"
196 # note: Following member(s) of "IntBox" have conflicts:
197 # note: content: expected "object", got "int"
198
199 This is because ``Box`` defines ``content`` as a mutable attribute.
200 Here's why this is problematic:
201
202 .. code-block:: python
203
204 def takes_box_evil(box: Box) -> None:
205 box.content = "asdf" # This is bad, since box.content is supposed to be an object
206
207 my_int_box = IntBox()
208 takes_box_evil(my_int_box)
209 my_int_box.content + 1 # Oops, TypeError!
210
211 This can be fixed by declaring ``content`` to be read-only in the ``Box``
212 protocol using ``@property``:
213
214 .. code-block:: python
215
216 class Box(Protocol):
217 @property
218 def content(self) -> object: ...
219
220 class IntBox:
221 content: int
222
223 def takes_box(box: Box) -> None: ...
224
225 takes_box(IntBox(42)) # OK
226
227 Recursive protocols
228 *******************
229
230 Protocols can be recursive (self-referential) and mutually
231 recursive. This is useful for declaring abstract recursive collections
232 such as trees and linked lists:
233
234 .. code-block:: python
235
236 from __future__ import annotations
237
238 from typing import Protocol
239
240 class TreeLike(Protocol):
241 value: int
242
243 @property
244 def left(self) -> TreeLike | None: ...
245
246 @property
247 def right(self) -> TreeLike | None: ...
248
249 class SimpleTree:
250 def __init__(self, value: int) -> None:
251 self.value = value
252 self.left: SimpleTree | None = None
253 self.right: SimpleTree | None = None
254
255 root: TreeLike = SimpleTree(0) # OK
256
257 Using isinstance() with protocols
258 *********************************
259
260 You can use a protocol class with :py:func:`isinstance` if you decorate it
261 with the ``@runtime_checkable`` class decorator. The decorator adds
262 rudimentary support for runtime structural checks:
263
264 .. code-block:: python
265
266 from typing import Protocol, runtime_checkable
267
268 @runtime_checkable
269 class Portable(Protocol):
270 handles: int
271
272 class Mug:
273 def __init__(self) -> None:
274 self.handles = 1
275
276 def use(handles: int) -> None: ...
277
278 mug = Mug()
279 if isinstance(mug, Portable): # Works at runtime!
280 use(mug.handles)
281
282 :py:func:`isinstance` also works with the :ref:`predefined protocols <predefined_protocols>`
283 in :py:mod:`typing` such as :py:class:`~typing.Iterable`.
284
285 .. warning::
286 :py:func:`isinstance` with protocols is not completely safe at runtime.
287 For example, signatures of methods are not checked. The runtime
288 implementation only checks that all protocol members exist,
289 not that they have the correct type. :py:func:`issubclass` with protocols
290 will only check for the existence of methods.
291
292 .. note::
293 :py:func:`isinstance` with protocols can also be surprisingly slow.
294 In many cases, you're better served by using :py:func:`hasattr` to
295 check for the presence of attributes.
296
297 .. _callback_protocols:
298
299 Callback protocols
300 ******************
301
302 Protocols can be used to define flexible callback types that are hard
303 (or even impossible) to express using the
304 :py:class:`Callable[...] <collections.abc.Callable>` syntax,
305 such as variadic, overloaded, and complex generic callbacks. They are defined with a
306 special :py:meth:`__call__ <object.__call__>` member:
307
308 .. code-block:: python
309
310 from collections.abc import Iterable
311 from typing import Optional, Protocol
312
313 class Combiner(Protocol):
314 def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...
315
316 def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
317 for item in data:
318 ...
319
320 def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
321 ...
322 def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
323 ...
324
325 batch_proc([], good_cb) # OK
326 batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
327 # different name and kind in the callback
328
329 Callback protocols and :py:class:`~collections.abc.Callable` types can be used mostly interchangeably.
330 Parameter names in :py:meth:`__call__ <object.__call__>` methods must be identical, unless
331 the parameters are positional-only. Example (using the legacy syntax for generic functions):
332
333 .. code-block:: python
334
335 from collections.abc import Callable
336 from typing import Protocol, TypeVar
337
338 T = TypeVar('T')
339
340 class Copy(Protocol):
341 # '/' marks the end of positional-only parameters
342 def __call__(self, origin: T, /) -> T: ...
343
344 copy_a: Callable[[T], T]
345 copy_b: Copy
346
347 copy_a = copy_b # OK
348 copy_b = copy_a # Also OK
349
350 Binding of types in protocol attributes
351 ***************************************
352
353 All protocol attributes annotations are treated as externally visible types
354 of those attributes. This means that for example callables are not bound,
355 and descriptors are not invoked:
356
357 .. code-block:: python
358
359 from typing import Callable, Protocol, overload
360
361 class Integer:
362 @overload
363 def __get__(self, instance: None, owner: object) -> Integer: ...
364 @overload
365 def __get__(self, instance: object, owner: object) -> int: ...
366 # <some implementation>
367
368 class Example(Protocol):
369 foo: Callable[[object], int]
370 bar: Integer
371
372 ex: Example
373 reveal_type(ex.foo) # Revealed type is Callable[[object], int]
374 reveal_type(ex.bar) # Revealed type is Integer
375
376 In other words, protocol attribute types are handled as they would appear in a
377 ``self`` attribute annotation in a regular class. If you want some protocol
378 attributes to be handled as though they were defined at class level, you should
379 declare them explicitly using ``ClassVar[...]``. Continuing previous example:
380
381 .. code-block:: python
382
383 from typing import ClassVar
384
385 class OtherExample(Protocol):
386 # This style is *not recommended*, but may be needed to reuse
387 # some complex callable types. Otherwise use regular methods.
388 foo: ClassVar[Callable[[object], int]]
389 # This may be needed to mimic descriptor access on Type[...] types,
390 # otherwise use a plain "bar: int" style.
391 bar: ClassVar[Integer]
392
393 ex2: OtherExample
394 reveal_type(ex2.foo) # Revealed type is Callable[[], int]
395 reveal_type(ex2.bar) # Revealed type is int
396
397 .. _predefined_protocols_reference:
398
399 Predefined protocol reference
400 *****************************
401
402 Iteration protocols
403 ...................
404
405 The iteration protocols are useful in many contexts. For example, they allow
406 iteration of objects in for loops.
407
408 collections.abc.Iterable[T]
409 ---------------------------
410
411 The :ref:`example above <predefined_protocols>` has a simple implementation of an
412 :py:meth:`__iter__ <object.__iter__>` method.
413
414 .. code-block:: python
415
416 def __iter__(self) -> Iterator[T]
417
418 See also :py:class:`~collections.abc.Iterable`.
419
420 collections.abc.Iterator[T]
421 ---------------------------
422
423 .. code-block:: python
424
425 def __next__(self) -> T
426 def __iter__(self) -> Iterator[T]
427
428 See also :py:class:`~collections.abc.Iterator`.
429
430 Collection protocols
431 ....................
432
433 Many of these are implemented by built-in container types such as
434 :py:class:`list` and :py:class:`dict`, and these are also useful for user-defined
435 collection objects.
436
437 collections.abc.Sized
438 ---------------------
439
440 This is a type for objects that support :py:func:`len(x) <len>`.
441
442 .. code-block:: python
443
444 def __len__(self) -> int
445
446 See also :py:class:`~collections.abc.Sized`.
447
448 collections.abc.Container[T]
449 ----------------------------
450
451 This is a type for objects that support the ``in`` operator.
452
453 .. code-block:: python
454
455 def __contains__(self, x: object) -> bool
456
457 See also :py:class:`~collections.abc.Container`.
458
459 collections.abc.Collection[T]
460 -----------------------------
461
462 .. code-block:: python
463
464 def __len__(self) -> int
465 def __iter__(self) -> Iterator[T]
466 def __contains__(self, x: object) -> bool
467
468 See also :py:class:`~collections.abc.Collection`.
469
470 One-off protocols
471 .................
472
473 These protocols are typically only useful with a single standard
474 library function or class.
475
476 collections.abc.Reversible[T]
477 -----------------------------
478
479 This is a type for objects that support :py:func:`reversed(x) <reversed>`.
480
481 .. code-block:: python
482
483 def __reversed__(self) -> Iterator[T]
484
485 See also :py:class:`~collections.abc.Reversible`.
486
487 typing.SupportsAbs[T]
488 ---------------------
489
490 This is a type for objects that support :py:func:`abs(x) <abs>`. ``T`` is the type of
491 value returned by :py:func:`abs(x) <abs>`.
492
493 .. code-block:: python
494
495 def __abs__(self) -> T
496
497 See also :py:class:`~typing.SupportsAbs`.
498
499 typing.SupportsBytes
500 --------------------
501
502 This is a type for objects that support :py:class:`bytes(x) <bytes>`.
503
504 .. code-block:: python
505
506 def __bytes__(self) -> bytes
507
508 See also :py:class:`~typing.SupportsBytes`.
509
510 .. _supports-int-etc:
511
512 typing.SupportsComplex
513 ----------------------
514
515 This is a type for objects that support :py:class:`complex(x) <complex>`. Note that no arithmetic operations
516 are supported.
517
518 .. code-block:: python
519
520 def __complex__(self) -> complex
521
522 See also :py:class:`~typing.SupportsComplex`.
523
524 typing.SupportsFloat
525 --------------------
526
527 This is a type for objects that support :py:class:`float(x) <float>`. Note that no arithmetic operations
528 are supported.
529
530 .. code-block:: python
531
532 def __float__(self) -> float
533
534 See also :py:class:`~typing.SupportsFloat`.
535
536 typing.SupportsInt
537 ------------------
538
539 This is a type for objects that support :py:class:`int(x) <int>`. Note that no arithmetic operations
540 are supported.
541
542 .. code-block:: python
543
544 def __int__(self) -> int
545
546 See also :py:class:`~typing.SupportsInt`.
547
548 typing.SupportsRound[T]
549 -----------------------
550
551 This is a type for objects that support :py:func:`round(x) <round>`.
552
553 .. code-block:: python
554
555 def __round__(self) -> T
556
557 See also :py:class:`~typing.SupportsRound`.
558
559 Async protocols
560 ...............
561
562 These protocols can be useful in async code. See :ref:`async-and-await`
563 for more information.
564
565 collections.abc.Awaitable[T]
566 ----------------------------
567
568 .. code-block:: python
569
570 def __await__(self) -> Generator[Any, None, T]
571
572 See also :py:class:`~collections.abc.Awaitable`.
573
574 collections.abc.AsyncIterable[T]
575 --------------------------------
576
577 .. code-block:: python
578
579 def __aiter__(self) -> AsyncIterator[T]
580
581 See also :py:class:`~collections.abc.AsyncIterable`.
582
583 collections.abc.AsyncIterator[T]
584 --------------------------------
585
586 .. code-block:: python
587
588 def __anext__(self) -> Awaitable[T]
589 def __aiter__(self) -> AsyncIterator[T]
590
591 See also :py:class:`~collections.abc.AsyncIterator`.
592
593 Context manager protocols
594 .........................
595
596 There are two protocols for context managers -- one for regular context
597 managers and one for async ones. These allow defining objects that can
598 be used in ``with`` and ``async with`` statements.
599
600 contextlib.AbstractContextManager[T]
601 ------------------------------------
602
603 .. code-block:: python
604
605 def __enter__(self) -> T
606 def __exit__(self,
607 exc_type: type[BaseException] | None,
608 exc_value: BaseException | None,
609 traceback: TracebackType | None) -> bool | None
610
611 See also :py:class:`~contextlib.AbstractContextManager`.
612
613 contextlib.AbstractAsyncContextManager[T]
614 -----------------------------------------
615
616 .. code-block:: python
617
618 def __aenter__(self) -> Awaitable[T]
619 def __aexit__(self,
620 exc_type: type[BaseException] | None,
621 exc_value: BaseException | None,
622 traceback: TracebackType | None) -> Awaitable[bool | None]
623
624 See also :py:class:`~contextlib.AbstractAsyncContextManager`.