Debian Codegraph @

docs/source/more_types.rst

raw
1 More types
2 ==========
3
4 This section introduces a few additional kinds of types, including :py:data:`~typing.NoReturn`,
5 :py:class:`~typing.NewType`, and types for async code. It also discusses
6 how to give functions more precise types using overloads. All of these are only
7 situationally useful, so feel free to skip this section and come back when you
8 have a need for some of them.
9
10 Here's a quick summary of what's covered here:
11
12 * :py:data:`~typing.NoReturn` lets you tell mypy that a function never returns normally.
13
14 * :py:class:`~typing.NewType` lets you define a variant of a type that is treated as a
15 separate type by mypy but is identical to the original type at runtime.
16 For example, you can have ``UserId`` as a variant of ``int`` that is
17 just an ``int`` at runtime.
18
19 * :py:func:`@overload <typing.overload>` lets you define a function that can accept multiple distinct
20 signatures. This is useful if you need to encode a relationship between the
21 arguments and the return type that would be difficult to express normally.
22
23 * Async types let you type check programs using ``async`` and ``await``.
24
25 .. _noreturn:
26
27 The NoReturn type
28 *****************
29
30 Mypy provides support for functions that never return. For
31 example, a function that unconditionally raises an exception:
32
33 .. code-block:: python
34
35 from typing import NoReturn
36
37 def stop() -> NoReturn:
38 raise Exception('no way')
39
40 Mypy will ensure that functions annotated as returning :py:data:`~typing.NoReturn`
41 truly never return, either implicitly or explicitly. Mypy will also
42 recognize that the code after calls to such functions is unreachable
43 and will behave accordingly:
44
45 .. code-block:: python
46
47 def f(x: int) -> int:
48 if x == 0:
49 return x
50 stop()
51 return 'whatever works' # No error in an unreachable block
52
53 In earlier Python versions you need to install ``typing_extensions`` using
54 pip to use :py:data:`~typing.NoReturn` in your code. Python 3 command line:
55
56 .. code-block:: text
57
58 python3 -m pip install --upgrade typing-extensions
59
60 .. _newtypes:
61
62 NewTypes
63 ********
64
65 There are situations where you may want to avoid programming errors by
66 creating simple derived classes that are only used to distinguish
67 certain values from base class instances. Example:
68
69 .. code-block:: python
70
71 class UserId(int):
72 pass
73
74 def get_by_user_id(user_id: UserId):
75 ...
76
77 However, this approach introduces some runtime overhead. To avoid this, the typing
78 module provides a helper object :py:class:`~typing.NewType` that creates simple unique types with
79 almost zero runtime overhead. Mypy will treat the statement
80 ``Derived = NewType('Derived', Base)`` as being roughly equivalent to the following
81 definition:
82
83 .. code-block:: python
84
85 class Derived(Base):
86 def __init__(self, _x: Base) -> None:
87 ...
88
89 However, at runtime, ``NewType('Derived', Base)`` will return a dummy callable that
90 simply returns its argument:
91
92 .. code-block:: python
93
94 def Derived(_x):
95 return _x
96
97 Mypy will require explicit casts from ``int`` where ``UserId`` is expected, while
98 implicitly casting from ``UserId`` where ``int`` is expected. Examples:
99
100 .. code-block:: python
101
102 from typing import NewType
103
104 UserId = NewType('UserId', int)
105
106 def name_by_id(user_id: UserId) -> str:
107 ...
108
109 UserId('user') # Fails type check
110
111 name_by_id(42) # Fails type check
112 name_by_id(UserId(42)) # OK
113
114 num: int = UserId(5) + 1
115
116 :py:class:`~typing.NewType` accepts exactly two arguments. The first argument must be a string literal
117 containing the name of the new type and must equal the name of the variable to which the new
118 type is assigned. The second argument must be a properly subclassable class, i.e.,
119 not a type construct like a :ref:`union type <union-types>`, etc.
120
121 The callable returned by :py:class:`~typing.NewType` accepts only one argument; this is equivalent to
122 supporting only one constructor accepting an instance of the base class (see above).
123 Example:
124
125 .. code-block:: python
126
127 from typing import NewType
128
129 class PacketId:
130 def __init__(self, major: int, minor: int) -> None:
131 self._major = major
132 self._minor = minor
133
134 TcpPacketId = NewType('TcpPacketId', PacketId)
135
136 packet = PacketId(100, 100)
137 tcp_packet = TcpPacketId(packet) # OK
138
139 tcp_packet = TcpPacketId(127, 0) # Fails in type checker and at runtime
140
141 You cannot use :py:func:`isinstance` or :py:func:`issubclass` on the object returned by
142 :py:class:`~typing.NewType`, nor can you subclass an object returned by :py:class:`~typing.NewType`.
143
144 .. note::
145
146 Unlike type aliases, :py:class:`~typing.NewType` will create an entirely new and
147 unique type when used. The intended purpose of :py:class:`~typing.NewType` is to help you
148 detect cases where you accidentally mixed together the old base type and the
149 new derived type.
150
151 For example, the following will successfully typecheck when using type
152 aliases:
153
154 .. code-block:: python
155
156 UserId = int
157
158 def name_by_id(user_id: UserId) -> str:
159 ...
160
161 name_by_id(3) # ints and UserId are synonymous
162
163 But a similar example using :py:class:`~typing.NewType` will not typecheck:
164
165 .. code-block:: python
166
167 from typing import NewType
168
169 UserId = NewType('UserId', int)
170
171 def name_by_id(user_id: UserId) -> str:
172 ...
173
174 name_by_id(3) # int is not the same as UserId
175
176 .. _function-overloading:
177
178 Function overloading
179 ********************
180
181 Sometimes the arguments and types in a function depend on each other
182 in ways that can't be captured with a :ref:`union types <union-types>`. For example, suppose
183 we want to write a function that can accept x-y coordinates. If we pass
184 in just a single x-y coordinate, we return a ``ClickEvent`` object. However,
185 if we pass in two x-y coordinates, we return a ``DragEvent`` object.
186
187 Our first attempt at writing this function might look like this:
188
189 .. code-block:: python
190
191 def mouse_event(x1: int,
192 y1: int,
193 x2: int | None = None,
194 y2: int | None = None) -> ClickEvent | DragEvent:
195 if x2 is None and y2 is None:
196 return ClickEvent(x1, y1)
197 elif x2 is not None and y2 is not None:
198 return DragEvent(x1, y1, x2, y2)
199 else:
200 raise TypeError("Bad arguments")
201
202 While this function signature works, it's too loose: it implies ``mouse_event``
203 could return either object regardless of the number of arguments
204 we pass in. It also does not prohibit a caller from passing in the wrong
205 number of ints: mypy would treat calls like ``mouse_event(1, 2, 20)`` as being
206 valid, for example.
207
208 We can do better by using :pep:`overloading <484#function-method-overloading>`
209 which lets us give the same function multiple type annotations (signatures)
210 to more accurately describe the function's behavior:
211
212 .. code-block:: python
213
214 from typing import overload
215
216 # Overload *variants* for 'mouse_event'.
217 # These variants give extra information to the type checker.
218 # They are ignored at runtime.
219
220 @overload
221 def mouse_event(x1: int, y1: int) -> ClickEvent: ...
222 @overload
223 def mouse_event(x1: int, y1: int, x2: int, y2: int) -> DragEvent: ...
224
225 # The actual *implementation* of 'mouse_event'.
226 # The implementation contains the actual runtime logic.
227 #
228 # It may or may not have type hints. If it does, mypy
229 # will check the body of the implementation against the
230 # type hints.
231 #
232 # Mypy will also check and make sure the signature is
233 # consistent with the provided variants.
234
235 def mouse_event(x1: int,
236 y1: int,
237 x2: int | None = None,
238 y2: int | None = None) -> ClickEvent | DragEvent:
239 if x2 is None and y2 is None:
240 return ClickEvent(x1, y1)
241 elif x2 is not None and y2 is not None:
242 return DragEvent(x1, y1, x2, y2)
243 else:
244 raise TypeError("Bad arguments")
245
246 This allows mypy to understand calls to ``mouse_event`` much more precisely.
247 For example, mypy will understand that ``mouse_event(5, 25)`` will
248 always have a return type of ``ClickEvent`` and will report errors for
249 calls like ``mouse_event(5, 25, 2)``.
250
251 As another example, suppose we want to write a custom container class that
252 implements the :py:meth:`__getitem__ <object.__getitem__>` method (``[]`` bracket indexing). If this
253 method receives an integer we return a single item. If it receives a
254 ``slice``, we return a :py:class:`~collections.abc.Sequence` of items.
255
256 We can precisely encode this relationship between the argument and the
257 return type by using overloads like so (Python 3.12 syntax):
258
259 .. code-block:: python
260
261 from collections.abc import Sequence
262 from typing import overload
263
264 class MyList[T](Sequence[T]):
265 @overload
266 def __getitem__(self, index: int) -> T: ...
267
268 @overload
269 def __getitem__(self, index: slice) -> Sequence[T]: ...
270
271 def __getitem__(self, index: int | slice) -> T | Sequence[T]:
272 if isinstance(index, int):
273 # Return a T here
274 elif isinstance(index, slice):
275 # Return a sequence of Ts here
276 else:
277 raise TypeError(...)
278
279 Here is the same example using the legacy syntax (Python 3.11 and earlier):
280
281 .. code-block:: python
282
283 from collections.abc import Sequence
284 from typing import TypeVar, overload
285
286 T = TypeVar('T')
287
288 class MyList(Sequence[T]):
289 @overload
290 def __getitem__(self, index: int) -> T: ...
291
292 @overload
293 def __getitem__(self, index: slice) -> Sequence[T]: ...
294
295 def __getitem__(self, index: int | slice) -> T | Sequence[T]:
296 if isinstance(index, int):
297 # Return a T here
298 elif isinstance(index, slice):
299 # Return a sequence of Ts here
300 else:
301 raise TypeError(...)
302
303 .. note::
304
305 If you just need to constrain a type variable to certain types or
306 subtypes, you can use a :ref:`value-constrained type variable
307 <value-constrained-type-variables>`.
308
309 The default values of a function's arguments don't affect its signature -- only
310 the absence or presence of a default value does. So in order to reduce
311 redundancy, it's possible to replace default values in overload definitions with
312 ``...`` as a placeholder:
313
314 .. code-block:: python
315
316 from typing import overload
317
318 class M: ...
319
320 @overload
321 def get_model(model_or_pk: M, flag: bool = ...) -> M: ...
322 @overload
323 def get_model(model_or_pk: int, flag: bool = ...) -> M | None: ...
324
325 def get_model(model_or_pk: int | M, flag: bool = True) -> M | None:
326 ...
327
328
329 Runtime behavior
330 ----------------
331
332 An overloaded function must consist of two or more overload *variants*
333 followed by an *implementation*. The variants and the implementations
334 must be adjacent in the code: think of them as one indivisible unit.
335
336 The variant bodies must all be empty; only the implementation is allowed
337 to contain code. This is because at runtime, the variants are completely
338 ignored: they're overridden by the final implementation function.
339
340 This means that an overloaded function is still an ordinary Python
341 function! There is no automatic dispatch handling and you must manually
342 handle the different types in the implementation (e.g. by using
343 ``if`` statements and :py:func:`isinstance <isinstance>` checks).
344
345 If you are adding an overload within a stub file, the implementation
346 function should be omitted: stubs do not contain runtime logic.
347
348 .. note::
349
350 While we can leave the variant body empty using the ``pass`` keyword,
351 the more common convention is to instead use the ellipsis (``...``) literal.
352
353 Type checking calls to overloads
354 --------------------------------
355
356 When you call an overloaded function, mypy will infer the correct return
357 type by picking the best matching variant, after taking into consideration
358 both the argument types and arity. However, a call is never type
359 checked against the implementation. This is why mypy will report calls
360 like ``mouse_event(5, 25, 3)`` as being invalid even though it matches the
361 implementation signature.
362
363 If there are multiple equally good matching variants, mypy will select
364 the variant that was defined first. For example, consider the following
365 program:
366
367 .. code-block:: python
368
369 # For Python 3.8 and below you must use `typing.List` instead of `list`. e.g.
370 # from typing import List
371 from typing import overload
372
373 @overload
374 def summarize(data: list[int]) -> float: ...
375
376 @overload
377 def summarize(data: list[str]) -> str: ...
378
379 def summarize(data):
380 if not data:
381 return 0.0
382 elif isinstance(data[0], int):
383 # Do int specific code
384 else:
385 # Do str-specific code
386
387 # What is the type of 'output'? float or str?
388 output = summarize([])
389
390 The ``summarize([])`` call matches both variants: an empty list could
391 be either a ``list[int]`` or a ``list[str]``. In this case, mypy
392 will break the tie by picking the first matching variant: ``output``
393 will have an inferred type of ``float``. The implementer is responsible
394 for making sure ``summarize`` breaks ties in the same way at runtime.
395
396 However, there are two exceptions to the "pick the first match" rule.
397 First, if multiple variants match due to an argument being of type
398 ``Any``, mypy will make the inferred type also be ``Any``:
399
400 .. code-block:: python
401
402 dynamic_var: Any = some_dynamic_function()
403
404 # output2 is of type 'Any'
405 output2 = summarize(dynamic_var)
406
407 Second, if multiple variants match due to one or more of the arguments
408 being a union, mypy will make the inferred type be the union of the
409 matching variant returns:
410
411 .. code-block:: python
412
413 some_list: list[int] | list[str]
414
415 # output3 is of type 'float | str'
416 output3 = summarize(some_list)
417
418 .. note::
419
420 Due to the "pick the first match" rule, changing the order of your
421 overload variants can change how mypy type checks your program.
422
423 To minimize potential issues, we recommend that you:
424
425 1. Make sure your overload variants are listed in the same order as
426 the runtime checks (e.g. :py:func:`isinstance <isinstance>` checks) in your implementation.
427 2. Order your variants and runtime checks from most to least specific.
428 (See the following section for an example).
429
430 Type checking the variants
431 --------------------------
432
433 Mypy will perform several checks on your overload variant definitions
434 to ensure they behave as expected. First, mypy will check and make sure
435 that no overload variant is shadowing a subsequent one. For example,
436 consider the following function which adds together two ``Expression``
437 objects, and contains a special-case to handle receiving two ``Literal``
438 types:
439
440 .. code-block:: python
441
442 from typing import overload
443
444 class Expression:
445 # ...snip...
446
447 class Literal(Expression):
448 # ...snip...
449
450 # Warning -- the first overload variant shadows the second!
451
452 @overload
453 def add(left: Expression, right: Expression) -> Expression: ...
454
455 @overload
456 def add(left: Literal, right: Literal) -> Literal: ...
457
458 def add(left: Expression, right: Expression) -> Expression:
459 # ...snip...
460
461 While this code snippet is technically type-safe, it does contain an
462 anti-pattern: the second variant will never be selected! If we try calling
463 ``add(Literal(3), Literal(4))``, mypy will always pick the first variant
464 and evaluate the function call to be of type ``Expression``, not ``Literal``.
465 This is because ``Literal`` is a subtype of ``Expression``, which means
466 the "pick the first match" rule will always halt after considering the
467 first overload.
468
469 Because having an overload variant that can never be matched is almost
470 certainly a mistake, mypy will report an error. To fix the error, we can
471 either 1) delete the second overload or 2) swap the order of the overloads:
472
473 .. code-block:: python
474
475 # Everything is ok now -- the variants are correctly ordered
476 # from most to least specific.
477
478 @overload
479 def add(left: Literal, right: Literal) -> Literal: ...
480
481 @overload
482 def add(left: Expression, right: Expression) -> Expression: ...
483
484 def add(left: Expression, right: Expression) -> Expression:
485 # ...snip...
486
487 Mypy will also type check the different variants and flag any overloads
488 that have inherently unsafely overlapping variants. For example, consider
489 the following unsafe overload definition:
490
491 .. code-block:: python
492
493 from typing import overload
494
495 @overload
496 def unsafe_func(x: int) -> int: ...
497
498 @overload
499 def unsafe_func(x: object) -> str: ...
500
501 def unsafe_func(x: object) -> int | str:
502 if isinstance(x, int):
503 return 42
504 else:
505 return "some string"
506
507 On the surface, this function definition appears to be fine. However, it will
508 result in a discrepancy between the inferred type and the actual runtime type
509 when we try using it like so:
510
511 .. code-block:: python
512
513 some_obj: object = 42
514 unsafe_func(some_obj) + " danger danger" # Type checks, yet crashes at runtime!
515
516 Since ``some_obj`` is of type :py:class:`object`, mypy will decide that ``unsafe_func``
517 must return something of type ``str`` and concludes the above will type check.
518 But in reality, ``unsafe_func`` will return an int, causing the code to crash
519 at runtime!
520
521 To prevent these kinds of issues, mypy will detect and prohibit inherently unsafely
522 overlapping overloads on a best-effort basis. Two variants are considered unsafely
523 overlapping when both of the following are true:
524
525 1. All of the arguments of the first variant are potentially compatible with the second.
526 2. The return type of the first variant is *not* compatible with (e.g. is not a
527 subtype of) the second.
528
529 So in this example, the ``int`` argument in the first variant is a subtype of
530 the ``object`` argument in the second, yet the ``int`` return type is not a subtype of
531 ``str``. Both conditions are true, so mypy will correctly flag ``unsafe_func`` as
532 being unsafe.
533
534 Note that in cases where you ignore the overlapping overload error, mypy will usually
535 still infer the types you expect at callsites.
536
537 However, mypy will not detect *all* unsafe uses of overloads. For example,
538 suppose we modify the above snippet so it calls ``summarize`` instead of
539 ``unsafe_func``:
540
541 .. code-block:: python
542
543 some_list: list[str] = []
544 summarize(some_list) + "danger danger" # Type safe, yet crashes at runtime!
545
546 We run into a similar issue here. This program type checks if we look just at the
547 annotations on the overloads. But since ``summarize(...)`` is designed to be biased
548 towards returning a float when it receives an empty list, this program will actually
549 crash during runtime.
550
551 The reason mypy does not flag definitions like ``summarize`` as being potentially
552 unsafe is because if it did, it would be extremely difficult to write a safe
553 overload. For example, suppose we define an overload with two variants that accept
554 types ``A`` and ``B`` respectively. Even if those two types were completely unrelated,
555 the user could still potentially trigger a runtime error similar to the ones above by
556 passing in a value of some third type ``C`` that inherits from both ``A`` and ``B``.
557
558 Thankfully, these types of situations are relatively rare. What this does mean,
559 however, is that you should exercise caution when designing or using an overloaded
560 function that can potentially receive values that are an instance of two seemingly
561 unrelated types.
562
563
564 Type checking the implementation
565 --------------------------------
566
567 The body of an implementation is type-checked against the
568 type hints provided on the implementation. For example, in the
569 ``MyList`` example up above, the code in the body is checked with
570 argument list ``index: int | slice`` and a return type of
571 ``T | Sequence[T]``. If there are no annotations on the
572 implementation, then the body is not type checked. If you want to
573 force mypy to check the body anyways, use the :option:`--check-untyped-defs <mypy --check-untyped-defs>`
574 flag (:ref:`more details here <untyped-definitions-and-calls>`).
575
576 The variants must also be compatible with the implementation
577 type hints. In the ``MyList`` example, mypy will check that the
578 parameter type ``int`` and the return type ``T`` are compatible with
579 ``int | slice`` and ``T | Sequence`` for the
580 first variant. For the second variant it verifies the parameter
581 type ``slice`` and the return type ``Sequence[T]`` are compatible
582 with ``int | slice`` and ``T | Sequence``.
583
584 .. note::
585
586 The overload semantics documented above are new as of mypy 0.620.
587
588 Previously, mypy used to perform type erasure on all overload variants. For
589 example, the ``summarize`` example from the previous section used to be
590 illegal because ``list[str]`` and ``list[int]`` both erased to just ``list[Any]``.
591 This restriction was removed in mypy 0.620.
592
593 Mypy also previously used to select the best matching variant using a different
594 algorithm. If this algorithm failed to find a match, it would default to returning
595 ``Any``. The new algorithm uses the "pick the first match" rule and will fall back
596 to returning ``Any`` only if the input arguments also contain ``Any``.
597
598
599 Conditional overloads
600 ---------------------
601
602 Sometimes it is useful to define overloads conditionally.
603 Common use cases include types that are unavailable at runtime or that
604 only exist in a certain Python version. All existing overload rules still apply.
605 For example, there must be at least two overloads.
606
607 .. note::
608
609 Mypy can only infer a limited number of conditions.
610 Supported ones currently include :py:data:`~typing.TYPE_CHECKING`, ``MYPY``,
611 :ref:`version_and_platform_checks`, :option:`--always-true <mypy --always-true>`,
612 and :option:`--always-false <mypy --always-false>` values.
613
614 .. code-block:: python
615
616 from typing import TYPE_CHECKING, Any, overload
617
618 if TYPE_CHECKING:
619 class A: ...
620 class B: ...
621
622
623 if TYPE_CHECKING:
624 @overload
625 def func(var: A) -> A: ...
626
627 @overload
628 def func(var: B) -> B: ...
629
630 def func(var: Any) -> Any:
631 return var
632
633
634 reveal_type(func(A())) # Revealed type is "A"
635
636 .. code-block:: python
637
638 # flags: --python-version 3.10
639 import sys
640 from typing import Any, overload
641
642 class A: ...
643 class B: ...
644 class C: ...
645 class D: ...
646
647
648 if sys.version_info < (3, 7):
649 @overload
650 def func(var: A) -> A: ...
651
652 elif sys.version_info >= (3, 10):
653 @overload
654 def func(var: B) -> B: ...
655
656 else:
657 @overload
658 def func(var: C) -> C: ...
659
660 @overload
661 def func(var: D) -> D: ...
662
663 def func(var: Any) -> Any:
664 return var
665
666
667 reveal_type(func(B())) # Revealed type is "B"
668 reveal_type(func(C())) # No overload variant of "func" matches argument type "C"
669 # Possible overload variants:
670 # def func(var: B) -> B
671 # def func(var: D) -> D
672 # Revealed type is "Any"
673
674
675 .. note::
676
677 In the last example, mypy is executed with
678 :option:`--python-version 3.10 <mypy --python-version>`.
679 Therefore, the condition ``sys.version_info >= (3, 10)`` will match and
680 the overload for ``B`` will be added.
681 The overloads for ``A`` and ``C`` are ignored!
682 The overload for ``D`` is not defined conditionally and thus is also added.
683
684 When mypy cannot infer a condition to be always ``True`` or always ``False``,
685 an error is emitted.
686
687 .. code-block:: python
688
689 from typing import Any, overload
690
691 class A: ...
692 class B: ...
693
694
695 def g(bool_var: bool) -> None:
696 if bool_var: # Condition can't be inferred, unable to merge overloads
697 @overload
698 def func(var: A) -> A: ...
699
700 @overload
701 def func(var: B) -> B: ...
702
703 def func(var: Any) -> Any: ...
704
705 reveal_type(func(A())) # Revealed type is "Any"
706
707
708 .. _advanced_self:
709
710 Advanced uses of self-types
711 ***************************
712
713 Normally, mypy doesn't require annotations for the first arguments of instance and
714 class methods. However, they may be needed to have more precise static typing
715 for certain programming patterns.
716
717 Restricted methods in generic classes
718 -------------------------------------
719
720 In generic classes some methods may be allowed to be called only
721 for certain values of type arguments (Python 3.12 syntax):
722
723 .. code-block:: python
724
725 class Tag[T]:
726 item: T
727
728 def uppercase_item(self: Tag[str]) -> str:
729 return self.item.upper()
730
731 def label(ti: Tag[int], ts: Tag[str]) -> None:
732 ti.uppercase_item() # E: Invalid self argument "Tag[int]" to attribute function
733 # "uppercase_item" with type "Callable[[Tag[str]], str]"
734 ts.uppercase_item() # This is OK
735
736 This pattern also allows matching on nested types in situations where the type
737 argument is itself generic (Python 3.12 syntax):
738
739 .. code-block:: python
740
741 from collections.abc import Sequence
742
743 class Storage[T]:
744 def __init__(self, content: T) -> None:
745 self._content = content
746
747 def first_chunk[S](self: Storage[Sequence[S]]) -> S:
748 return self._content[0]
749
750 page: Storage[list[str]]
751 page.first_chunk() # OK, type is "str"
752
753 Storage(0).first_chunk() # Error: Invalid self argument "Storage[int]" to attribute function
754 # "first_chunk" with type "Callable[[Storage[Sequence[S]]], S]"
755
756 Finally, one can use overloads on self-type to express precise types of
757 some tricky methods (Python 3.12 syntax):
758
759 .. code-block:: python
760
761 from collections.abc import Callable
762 from typing import overload
763
764 class Tag[T]:
765 @overload
766 def export(self: Tag[str]) -> str: ...
767 @overload
768 def export(self, converter: Callable[[T], str]) -> str: ...
769
770 def export(self, converter=None):
771 if isinstance(self.item, str):
772 return self.item
773 return converter(self.item)
774
775 In particular, an :py:meth:`~object.__init__` method overloaded on self-type
776 may be useful to annotate generic class constructors where type arguments
777 depend on constructor parameters in a non-trivial way, see e.g. :py:class:`~subprocess.Popen`.
778
779 Mixin classes
780 -------------
781
782 Using host class protocol as a self-type in mixin methods allows
783 more code re-usability for static typing of mixin classes. For example,
784 one can define a protocol that defines common functionality for
785 host classes instead of adding required abstract methods to every mixin:
786
787 .. code-block:: python
788
789 class Lockable(Protocol):
790 @property
791 def lock(self) -> Lock: ...
792
793 class AtomicCloseMixin:
794 def atomic_close(self: Lockable) -> int:
795 with self.lock:
796 # perform actions
797
798 class AtomicOpenMixin:
799 def atomic_open(self: Lockable) -> int:
800 with self.lock:
801 # perform actions
802
803 class File(AtomicCloseMixin, AtomicOpenMixin):
804 def __init__(self) -> None:
805 self.lock = Lock()
806
807 class Bad(AtomicCloseMixin):
808 pass
809
810 f = File()
811 b: Bad
812 f.atomic_close() # OK
813 b.atomic_close() # Error: Invalid self type for "atomic_close"
814
815 Note that the explicit self-type is *required* to be a protocol whenever it
816 is not a supertype of the current class. In this case mypy will check the validity
817 of the self-type only at the call site.
818
819 Precise typing of alternative constructors
820 ------------------------------------------
821
822 Some classes may define alternative constructors. If these
823 classes are generic, self-type allows giving them precise
824 signatures (Python 3.12 syntax):
825
826 .. code-block:: python
827
828 from typing import Self
829
830 class Base[T]:
831 def __init__(self, item: T) -> None:
832 self.item = item
833
834 @classmethod
835 def make_pair(cls, item: T) -> tuple[Self, Self]:
836 return cls(item), cls(item)
837
838 class Sub[T](Base[T]):
839 ...
840
841 pair = Sub.make_pair('yes') # Type is "tuple[Sub[str], Sub[str]]"
842 bad = Sub[int].make_pair('no') # Error: Argument 1 to "make_pair" of "Base"
843 # has incompatible type "str"; expected "int"
844
845 .. _async-and-await:
846
847 Typing async/await
848 ******************
849
850 Mypy lets you type coroutines that use the ``async/await`` syntax.
851 For more information regarding coroutines, see :pep:`492` and the
852 `asyncio documentation <python:library/asyncio>`_.
853
854 Functions defined using ``async def`` are typed similar to normal functions.
855 The return type annotation should be the same as the type of the value you
856 expect to get back when ``await``-ing the coroutine.
857
858 .. code-block:: python
859
860 import asyncio
861
862 async def format_string(tag: str, count: int) -> str:
863 return f'T-minus {count} ({tag})'
864
865 async def countdown(tag: str, count: int) -> str:
866 while count > 0:
867 my_str = await format_string(tag, count) # type is inferred to be str
868 print(my_str)
869 await asyncio.sleep(0.1)
870 count -= 1
871 return "Blastoff!"
872
873 asyncio.run(countdown("Millennium Falcon", 5))
874
875 The result of calling an ``async def`` function *without awaiting* will
876 automatically be inferred to be a value of type
877 :py:class:`Coroutine[Any, Any, T] <collections.abc.Coroutine>`, which is a subtype of
878 :py:class:`Awaitable[T] <collections.abc.Awaitable>`:
879
880 .. code-block:: python
881
882 my_coroutine = countdown("Millennium Falcon", 5)
883 reveal_type(my_coroutine) # Revealed type is "typing.Coroutine[Any, Any, builtins.str]"
884
885 .. _async-iterators:
886
887 Asynchronous iterators
888 ----------------------
889
890 If you have an asynchronous iterator, you can use the
891 :py:class:`~collections.abc.AsyncIterator` type in your annotations:
892
893 .. code-block:: python
894
895 from collections.abc import AsyncIterator
896 from typing import Optional
897 import asyncio
898
899 class arange:
900 def __init__(self, start: int, stop: int, step: int) -> None:
901 self.start = start
902 self.stop = stop
903 self.step = step
904 self.count = start - step
905
906 def __aiter__(self) -> AsyncIterator[int]:
907 return self
908
909 async def __anext__(self) -> int:
910 self.count += self.step
911 if self.count == self.stop:
912 raise StopAsyncIteration
913 else:
914 return self.count
915
916 async def run_countdown(tag: str, countdown: AsyncIterator[int]) -> str:
917 async for i in countdown:
918 print(f'T-minus {i} ({tag})')
919 await asyncio.sleep(0.1)
920 return "Blastoff!"
921
922 asyncio.run(run_countdown("Serenity", arange(5, 0, -1)))
923
924 Async generators (introduced in :pep:`525`) are an easy way to create
925 async iterators:
926
927 .. code-block:: python
928
929 from collections.abc import AsyncGenerator
930 from typing import Optional
931 import asyncio
932
933 # Could also type this as returning AsyncIterator[int]
934 async def arange(start: int, stop: int, step: int) -> AsyncGenerator[int, None]:
935 current = start
936 while (step > 0 and current < stop) or (step < 0 and current > stop):
937 yield current
938 current += step
939
940 asyncio.run(run_countdown("Battlestar Galactica", arange(5, 0, -1)))
941
942 One common confusion is that the presence of a ``yield`` statement in an
943 ``async def`` function has an effect on the type of the function:
944
945 .. code-block:: python
946
947 from collections.abc import AsyncIterator
948
949 async def arange(stop: int) -> AsyncIterator[int]:
950 # When called, arange gives you an async iterator
951 # Equivalent to Callable[[int], AsyncIterator[int]]
952 i = 0
953 while i < stop:
954 yield i
955 i += 1
956
957 async def coroutine(stop: int) -> AsyncIterator[int]:
958 # When called, coroutine gives you something you can await to get an async iterator
959 # Equivalent to Callable[[int], Coroutine[Any, Any, AsyncIterator[int]]]
960 return arange(stop)
961
962 async def main() -> None:
963 reveal_type(arange(5)) # Revealed type is "typing.AsyncIterator[builtins.int]"
964 reveal_type(coroutine(5)) # Revealed type is "typing.Coroutine[Any, Any, typing.AsyncIterator[builtins.int]]"
965
966 await arange(5) # Error: Incompatible types in "await" (actual type "AsyncIterator[int]", expected type "Awaitable[Any]")
967 reveal_type(await coroutine(5)) # Revealed type is "typing.AsyncIterator[builtins.int]"
968
969 This can sometimes come up when trying to define base classes, Protocols or overloads:
970
971 .. code-block:: python
972
973 from collections.abc import AsyncIterator
974 from typing import Protocol, overload
975
976 class LauncherIncorrect(Protocol):
977 # Because launch does not have yield, this has type
978 # Callable[[], Coroutine[Any, Any, AsyncIterator[int]]]
979 # instead of
980 # Callable[[], AsyncIterator[int]]
981 async def launch(self) -> AsyncIterator[int]:
982 raise NotImplementedError
983
984 class LauncherCorrect(Protocol):
985 def launch(self) -> AsyncIterator[int]:
986 raise NotImplementedError
987
988 class LauncherAlsoCorrect(Protocol):
989 async def launch(self) -> AsyncIterator[int]:
990 raise NotImplementedError
991 if False:
992 yield 0
993
994 # The type of the overloads is independent of the implementation.
995 # In particular, their type is not affected by whether or not the
996 # implementation contains a `yield`.
997 # Use of `def`` makes it clear the type is Callable[..., AsyncIterator[int]],
998 # whereas with `async def` it would be Callable[..., Coroutine[Any, Any, AsyncIterator[int]]]
999 @overload
1000 def launch(*, count: int = ...) -> AsyncIterator[int]: ...
1001 @overload
1002 def launch(*, time: float = ...) -> AsyncIterator[int]: ...
1003
1004 async def launch(*, count: int = 0, time: float = 0) -> AsyncIterator[int]:
1005 # The implementation of launch is an async generator and contains a yield
1006 yield 0