Debian Codegraph @

docs/source/kinds_of_types.rst

raw
1 Kinds of types
2 ==============
3
4 We've mostly restricted ourselves to built-in types until now. This
5 section introduces several additional kinds of types. You are likely
6 to need at least some of them to type check any non-trivial programs.
7
8 Class types
9 ***********
10
11 Every class is also a valid type. Any instance of a subclass is also
12 compatible with all superclasses -- it follows that every value is compatible
13 with the :py:class:`object` type (and incidentally also the ``Any`` type, discussed
14 below). Mypy analyzes the bodies of classes to determine which methods and
15 attributes are available in instances. This example uses subclassing:
16
17 .. code-block:: python
18
19 class A:
20 def f(self) -> int: # Type of self inferred (A)
21 return 2
22
23 class B(A):
24 def f(self) -> int:
25 return 3
26 def g(self) -> int:
27 return 4
28
29 def foo(a: A) -> None:
30 print(a.f()) # 3
31 a.g() # Error: "A" has no attribute "g"
32
33 foo(B()) # OK (B is a subclass of A)
34
35 The Any type
36 ************
37
38 A value with the ``Any`` type is dynamically typed. Mypy doesn't know
39 anything about the possible runtime types of such value. Any
40 operations are permitted on the value, and the operations are only checked
41 at runtime. You can use ``Any`` as an "escape hatch" when you can't use
42 a more precise type for some reason.
43
44 This should not be confused with the
45 :py:class:`object` type, which represents the set of all values.
46 Unlike ``object``, ``Any`` introduces type unsafety — see
47 :ref:`any-vs-object` for more.
48
49 ``Any`` is compatible with every other type, and vice versa. You can freely
50 assign a value of type ``Any`` to a variable with a more precise type:
51
52 .. code-block:: python
53
54 a: Any = None
55 s: str = ''
56 a = 2 # OK (assign "int" to "Any")
57 s = a # OK (assign "Any" to "str")
58
59 Declared (and inferred) types are ignored (or *erased*) at runtime. They are
60 basically treated as comments, and thus the above code does not
61 generate a runtime error, even though ``s`` gets an ``int`` value when
62 the program is run, while the declared type of ``s`` is actually
63 ``str``! You need to be careful with ``Any`` types, since they let you
64 lie to mypy, and this could easily hide bugs.
65
66 If you do not define a function return value or argument types, these
67 default to ``Any``:
68
69 .. code-block:: python
70
71 def show_heading(s) -> None:
72 print('=== ' + s + ' ===') # No static type checking, as s has type Any
73
74 show_heading(1) # OK (runtime error only; mypy won't generate an error)
75
76 You should give a statically typed function an explicit ``None``
77 return type even if it doesn't return a value, as this lets mypy catch
78 additional type errors:
79
80 .. code-block:: python
81
82 def wait(t: float): # Implicit Any return value
83 print('Waiting...')
84 time.sleep(t)
85
86 if wait(2) > 1: # Mypy doesn't catch this error!
87 ...
88
89 If we had used an explicit ``None`` return type, mypy would have caught
90 the error:
91
92 .. code-block:: python
93
94 def wait(t: float) -> None:
95 print('Waiting...')
96 time.sleep(t)
97
98 if wait(2) > 1: # Error: can't compare None and int
99 ...
100
101 The ``Any`` type is discussed in more detail in section :ref:`dynamic-typing`.
102
103 .. note::
104
105 A function without any types in the signature is dynamically
106 typed. The body of a dynamically typed function is not checked
107 statically, and local variables have implicit ``Any`` types.
108 This makes it easier to migrate legacy Python code to mypy, as
109 mypy won't complain about dynamically typed functions.
110
111 .. _tuple-types:
112
113 Tuple types
114 ***********
115
116 The type ``tuple[T1, ..., Tn]`` represents a tuple with the item types ``T1``, ..., ``Tn``:
117
118 .. code-block:: python
119
120 # Use `typing.Tuple` in Python 3.8 and earlier
121 def f(t: tuple[int, str]) -> None:
122 t = 1, 'foo' # OK
123 t = 'foo', 1 # Type check error
124
125 A tuple type of this kind has exactly a specific number of items (2 in
126 the above example). Tuples can also be used as immutable,
127 varying-length sequences. You can use the type ``tuple[T, ...]`` (with
128 a literal ``...`` -- it's part of the syntax) for this
129 purpose. Example:
130
131 .. code-block:: python
132
133 def print_squared(t: tuple[int, ...]) -> None:
134 for n in t:
135 print(n, n ** 2)
136
137 print_squared(()) # OK
138 print_squared((1, 3, 5)) # OK
139 print_squared([1, 2]) # Error: only a tuple is valid
140
141 .. note::
142
143 Usually it's a better idea to use ``Sequence[T]`` instead of ``tuple[T, ...]``, as
144 :py:class:`~collections.abc.Sequence` is also compatible with lists and other non-tuple sequences.
145
146 .. note::
147
148 ``tuple[...]`` is valid as a base class in Python 3.6 and later, and
149 always in stub files. In earlier Python versions you can sometimes work around this
150 limitation by using a named tuple as a base class (see section :ref:`named-tuples`).
151
152 .. _callable-types:
153
154 Callable types (and lambdas)
155 ****************************
156
157 You can pass around function objects and bound methods in statically
158 typed code. The type of a function that accepts arguments ``A1``, ..., ``An``
159 and returns ``Rt`` is ``Callable[[A1, ..., An], Rt]``. Example:
160
161 .. code-block:: python
162
163 from collections.abc import Callable
164
165 def twice(i: int, next: Callable[[int], int]) -> int:
166 return next(next(i))
167
168 def add(i: int) -> int:
169 return i + 1
170
171 print(twice(3, add)) # 5
172
173 .. note::
174
175 Import :py:data:`Callable[...] <typing.Callable>` from ``typing`` instead
176 of ``collections.abc`` if you use Python 3.8 or earlier.
177
178 You can only have positional arguments, and only ones without default
179 values, in callable types. These cover the vast majority of uses of
180 callable types, but sometimes this isn't quite enough. Mypy recognizes
181 a special form ``Callable[..., T]`` (with a literal ``...``) which can
182 be used in less typical cases. It is compatible with arbitrary
183 callable objects that return a type compatible with ``T``, independent
184 of the number, types or kinds of arguments. Mypy lets you call such
185 callable values with arbitrary arguments, without any checking -- in
186 this respect they are treated similar to a ``(*args: Any, **kwargs:
187 Any)`` function signature. Example:
188
189 .. code-block:: python
190
191 from collections.abc import Callable
192
193 def arbitrary_call(f: Callable[..., int]) -> int:
194 return f('x') + f(y=2) # OK
195
196 arbitrary_call(ord) # No static error, but fails at runtime
197 arbitrary_call(open) # Error: does not return an int
198 arbitrary_call(1) # Error: 'int' is not callable
199
200 In situations where more precise or complex types of callbacks are
201 necessary one can use flexible :ref:`callback protocols <callback_protocols>`.
202 Lambdas are also supported. The lambda argument and return value types
203 cannot be given explicitly; they are always inferred based on context
204 using bidirectional type inference:
205
206 .. code-block:: python
207
208 l = map(lambda x: x + 1, [1, 2, 3]) # Infer x as int and l as list[int]
209
210 If you want to give the argument or return value types explicitly, use
211 an ordinary, perhaps nested function definition.
212
213 Callables can also be used against type objects, matching their
214 ``__init__`` or ``__new__`` signature:
215
216 .. code-block:: python
217
218 from collections.abc import Callable
219
220 class C:
221 def __init__(self, app: str) -> None:
222 pass
223
224 CallableType = Callable[[str], C]
225
226 def class_or_callable(arg: CallableType) -> None:
227 inst = arg("my_app")
228 reveal_type(inst) # Revealed type is "C"
229
230 This is useful if you want ``arg`` to be either a ``Callable`` returning an
231 instance of ``C`` or the type of ``C`` itself. This also works with
232 :ref:`callback protocols <callback_protocols>`.
233
234
235 .. _union-types:
236 .. _alternative_union_syntax:
237
238 Union types
239 ***********
240
241 Python functions often accept values of two or more different
242 types. You can use :ref:`overloading <function-overloading>` to
243 represent this, but union types are often more convenient.
244
245 Use ``T1 | ... | Tn`` to construct a union
246 type. For example, if an argument has type ``int | str``, both
247 integers and strings are valid argument values.
248
249 You can use an :py:func:`isinstance` check to narrow down a union type to a
250 more specific type:
251
252 .. code-block:: python
253
254 def f(x: int | str) -> None:
255 x + 1 # Error: str + int is not valid
256 if isinstance(x, int):
257 # Here type of x is int.
258 x + 1 # OK
259 else:
260 # Here type of x is str.
261 x + 'a' # OK
262
263 f(1) # OK
264 f('x') # OK
265 f(1.1) # Error
266
267 .. note::
268
269 Operations are valid for union types only if they are valid for *every*
270 union item. This is why it's often necessary to use an :py:func:`isinstance`
271 check to first narrow down a union type to a non-union type. This also
272 means that it's recommended to avoid union types as function return types,
273 since the caller may have to use :py:func:`isinstance` before doing anything
274 interesting with the value.
275
276 Python 3.9 and older only partially support this syntax. Instead, you can
277 use the legacy ``Union[T1, ..., Tn]`` type constructor. Example:
278
279 .. code-block:: python
280
281 from typing import Union
282
283 def f(x: Union[int, str]) -> None:
284 ...
285
286 It is also possible to use the new syntax with versions of Python where it
287 isn't supported by the runtime with some limitations, if you use
288 ``from __future__ import annotations`` (see :ref:`runtime_troubles`):
289
290 .. code-block:: python
291
292 from __future__ import annotations
293
294 def f(x: int | str) -> None: # OK on Python 3.7 and later
295 ...
296
297 .. _no-strict-optional:
298 .. _strict_optional:
299
300 Optional types and the None type
301 ********************************
302
303 You can use ``T | None`` to define a type variant that allows ``None`` values,
304 such as ``int | None``. This is called an *optional type*:
305
306 .. code-block:: python
307
308 def strlen(s: str) -> int | None:
309 if not s:
310 return None # OK
311 return len(s)
312
313 def strlen_invalid(s: str) -> int:
314 if not s:
315 return None # Error: None not compatible with int
316 return len(s)
317
318 You can also use the :py:data:`~typing.Optional` type modifier, such as
319 ``Optional[int]`` (``Optional[X]`` is the shorthand for ``Union[X, None]``):
320
321 .. code-block:: python
322
323 from typing import Optional
324
325 def strlen(s: str) -> Optional[int]:
326 ...
327
328 Most operations will not be allowed on unguarded ``None`` or *optional* values
329 (values with an optional type):
330
331 .. code-block:: python
332
333 def my_inc(x: int | None) -> int:
334 return x + 1 # Error: Cannot add None and int
335
336 Instead, an explicit ``None`` check is required. Mypy has
337 powerful type inference that lets you use regular Python
338 idioms to guard against ``None`` values. For example, mypy
339 recognizes ``is None`` checks:
340
341 .. code-block:: python
342
343 def my_inc(x: int | None) -> int:
344 if x is None:
345 return 0
346 else:
347 # The inferred type of x is just int here.
348 return x + 1
349
350 Mypy will infer the type of ``x`` to be ``int`` in the else block due to the
351 check against ``None`` in the if condition.
352
353 Other supported checks for guarding against a ``None`` value include
354 ``if x is not None``, ``if x`` and ``if not x``. Additionally, mypy understands
355 ``None`` checks within logical expressions:
356
357 .. code-block:: python
358
359 def concat(x: str | None, y: str | None) -> str | None:
360 if x is not None and y is not None:
361 # Both x and y are not None here
362 return x + y
363 else:
364 return None
365
366 Sometimes mypy doesn't realize that a value is never ``None``. This notably
367 happens when a class instance can exist in a partially defined state,
368 where some attribute is initialized to ``None`` during object
369 construction, but a method assumes that the attribute is no longer ``None``. Mypy
370 will complain about the possible ``None`` value. You can use
371 ``assert x is not None`` to work around this in the method:
372
373 .. code-block:: python
374
375 class Resource:
376 path: str | None = None
377
378 def initialize(self, path: str) -> None:
379 self.path = path
380
381 def read(self) -> str:
382 # We require that the object has been initialized.
383 assert self.path is not None
384 with open(self.path) as f: # OK
385 return f.read()
386
387 r = Resource()
388 r.initialize('/foo/bar')
389 r.read()
390
391 When initializing a variable as ``None``, ``None`` is usually an
392 empty place-holder value, and the actual value has a different type.
393 This is why you need to annotate an attribute in cases like the class
394 ``Resource`` above:
395
396 .. code-block:: python
397
398 class Resource:
399 path: str | None = None
400 ...
401
402 This also works for attributes defined within methods:
403
404 .. code-block:: python
405
406 class Counter:
407 def __init__(self) -> None:
408 self.count: int | None = None
409
410 Often it's easier to not use any initial value for an attribute.
411 This way you don't need to use an optional type and can avoid ``assert ... is not None``
412 checks. No initial value is needed if you annotate an attribute in the class body:
413
414 .. code-block:: python
415
416 class Container:
417 items: list[str] # No initial value
418
419 Mypy generally uses the first assignment to a variable to
420 infer the type of the variable. However, if you assign both a ``None``
421 value and a non-``None`` value in the same scope, mypy can usually do
422 the right thing without an annotation:
423
424 .. code-block:: python
425
426 def f(i: int) -> None:
427 n = None # Inferred type 'int | None' because of the assignment below
428 if i > 0:
429 n = i
430 ...
431
432 Sometimes you may get the error "Cannot determine type of <something>". In this
433 case you should add an explicit ``... | None`` annotation.
434
435 .. note::
436
437 ``None`` is a type with only one value, ``None``. ``None`` is also used
438 as the return type for functions that don't return a value, i.e. functions
439 that implicitly return ``None``.
440
441 .. note::
442
443 The Python interpreter internally uses the name ``NoneType`` for
444 the type of ``None``, but ``None`` is always used in type
445 annotations. The latter is shorter and reads better. (``NoneType``
446 is available as :py:class:`types.NoneType` on Python 3.10+, but is
447 not exposed at all on earlier versions of Python.)
448
449 .. note::
450
451 The type ``Optional[T]`` *does not* mean a function parameter with a default value.
452 It simply means that ``None`` is a valid argument value. This is
453 a common confusion because ``None`` is a common default value for parameters,
454 and parameters with default values are sometimes called *optional* parameters
455 (or arguments).
456
457 .. _type-aliases:
458
459 Type aliases
460 ************
461
462 In certain situations, type names may end up being long and painful to type,
463 especially if they are used frequently:
464
465 .. code-block:: python
466
467 def f() -> list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]:
468 ...
469
470 When cases like this arise, you can define a type alias by simply
471 assigning the type to a variable (this is an *implicit type alias*):
472
473 .. code-block:: python
474
475 AliasType = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]
476
477 # Now we can use AliasType in place of the full name:
478
479 def f() -> AliasType:
480 ...
481
482 .. note::
483
484 A type alias does not create a new type. It's just a shorthand notation for
485 another type -- it's equivalent to the target type except for
486 :ref:`generic aliases <generic-type-aliases>`.
487
488 Python 3.12 introduced the ``type`` statement for defining *explicit type aliases*.
489 Explicit type aliases are unambiguous and can also improve readability by
490 making the intent clear:
491
492 .. code-block:: python
493
494 type AliasType = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]
495
496 # Now we can use AliasType in place of the full name:
497
498 def f() -> AliasType:
499 ...
500
501 There can be confusion about exactly when an assignment defines an implicit type alias --
502 for example, when the alias contains forward references, invalid types, or violates some other
503 restrictions on type alias declarations. Because the
504 distinction between an unannotated variable and a type alias is implicit,
505 ambiguous or incorrect type alias declarations default to defining
506 a normal variable instead of a type alias.
507
508 Aliases defined using the ``type`` statement have these properties, which
509 distinguish them from implicit type aliases:
510
511 * The definition may contain forward references without having to use string
512 literal escaping, since it is evaluated lazily.
513 * The alias can be used in type annotations, type arguments, and casts, but
514 it can't be used in contexts which require a class object. For example, it's
515 not valid as a base class and it can't be used to construct instances.
516
517 There is also use an older syntax for defining explicit type aliases (:pep:`613`):
518
519 .. code-block:: python
520
521 from typing import TypeAlias
522
523 AliasType: TypeAlias = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]
524
525 .. _named-tuples:
526
527 Named tuples
528 ************
529
530 Mypy recognizes named tuples and can type check code that defines or
531 uses them. In this example, we can detect code trying to access a
532 missing attribute:
533
534 .. code-block:: python
535
536 Point = namedtuple('Point', ['x', 'y'])
537 p = Point(x=1, y=2)
538 print(p.z) # Error: Point has no attribute 'z'
539
540 If you use :py:func:`namedtuple <collections.namedtuple>` to define your named tuple, all the items
541 are assumed to have ``Any`` types. That is, mypy doesn't know anything
542 about item types. You can use :py:class:`~typing.NamedTuple` to also define
543 item types:
544
545 .. code-block:: python
546
547 from typing import NamedTuple
548
549 Point = NamedTuple('Point', [('x', int),
550 ('y', int)])
551 p = Point(x=1, y='x') # Argument has incompatible type "str"; expected "int"
552
553 Python 3.6 introduced an alternative, class-based syntax for named tuples with types:
554
555 .. code-block:: python
556
557 from typing import NamedTuple
558
559 class Point(NamedTuple):
560 x: int
561 y: int
562
563 p = Point(x=1, y='x') # Argument has incompatible type "str"; expected "int"
564
565 .. note::
566
567 You can use the raw ``NamedTuple`` "pseudo-class" in type annotations
568 if any ``NamedTuple`` object is valid.
569
570 For example, it can be useful for deserialization:
571
572 .. code-block:: python
573
574 def deserialize_named_tuple(arg: NamedTuple) -> Dict[str, Any]:
575 return arg._asdict()
576
577 Point = namedtuple('Point', ['x', 'y'])
578 Person = NamedTuple('Person', [('name', str), ('age', int)])
579
580 deserialize_named_tuple(Point(x=1, y=2)) # ok
581 deserialize_named_tuple(Person(name='Nikita', age=18)) # ok
582
583 # Error: Argument 1 to "deserialize_named_tuple" has incompatible type
584 # "Tuple[int, int]"; expected "NamedTuple"
585 deserialize_named_tuple((1, 2))
586
587 Note that this behavior is highly experimental, non-standard,
588 and may not be supported by other type checkers and IDEs.
589
590 .. _type-of-class:
591
592 The type of class objects
593 *************************
594
595 (Freely after :pep:`PEP 484: The type of class objects
596 <484#the-type-of-class-objects>`.)
597
598 Sometimes you want to talk about class objects that inherit from a
599 given class. This can be spelled as ``type[C]`` (or, on Python 3.8 and lower,
600 :py:class:`typing.Type[C] <typing.Type>`) where ``C`` is a
601 class. In other words, when ``C`` is the name of a class, using ``C``
602 to annotate an argument declares that the argument is an instance of
603 ``C`` (or of a subclass of ``C``), but using ``type[C]`` as an
604 argument annotation declares that the argument is a class object
605 deriving from ``C`` (or ``C`` itself).
606
607 For example, assume the following classes:
608
609 .. code-block:: python
610
611 class User:
612 # Defines fields like name, email
613
614 class BasicUser(User):
615 def upgrade(self):
616 """Upgrade to Pro"""
617
618 class ProUser(User):
619 def pay(self):
620 """Pay bill"""
621
622 Note that ``ProUser`` doesn't inherit from ``BasicUser``.
623
624 Here's a function that creates an instance of one of these classes if
625 you pass it the right class object:
626
627 .. code-block:: python
628
629 def new_user(user_class):
630 user = user_class()
631 # (Here we could write the user object to a database)
632 return user
633
634 How would we annotate this function? Without the ability to parameterize ``type``, the best we
635 could do would be:
636
637 .. code-block:: python
638
639 def new_user(user_class: type) -> User:
640 # Same implementation as before
641
642 This seems reasonable, except that in the following example, mypy
643 doesn't see that the ``buyer`` variable has type ``ProUser``:
644
645 .. code-block:: python
646
647 buyer = new_user(ProUser)
648 buyer.pay() # Rejected, not a method on User
649
650 However, using the ``type[C]`` syntax and a type variable with an upper bound (see
651 :ref:`type-variable-upper-bound`) we can do better (Python 3.12 syntax):
652
653 .. code-block:: python
654
655 def new_user[U: User](user_class: type[U]) -> U:
656 # Same implementation as before
657
658 Here is the example using the legacy syntax (Python 3.11 and earlier):
659
660 .. code-block:: python
661
662 U = TypeVar('U', bound=User)
663
664 def new_user(user_class: type[U]) -> U:
665 # Same implementation as before
666
667 Now mypy will infer the correct type of the result when we call
668 ``new_user()`` with a specific subclass of ``User``:
669
670 .. code-block:: python
671
672 beginner = new_user(BasicUser) # Inferred type is BasicUser
673 beginner.upgrade() # OK
674
675 .. note::
676
677 The value corresponding to ``type[C]`` must be an actual class
678 object that's a subtype of ``C``. Its constructor must be
679 compatible with the constructor of ``C``. If ``C`` is a type
680 variable, its upper bound must be a class object.
681
682 For more details about ``type[]`` and :py:class:`typing.Type[] <typing.Type>`, see :pep:`PEP 484: The type of
683 class objects <484#the-type-of-class-objects>`.
684
685 .. _generators:
686
687 Generators
688 **********
689
690 A basic generator that only yields values can be succinctly annotated as having a return
691 type of either :py:class:`Iterator[YieldType] <typing.Iterator>` or :py:class:`Iterable[YieldType] <typing.Iterable>`. For example:
692
693 .. code-block:: python
694
695 def squares(n: int) -> Iterator[int]:
696 for i in range(n):
697 yield i * i
698
699 A good rule of thumb is to annotate functions with the most specific return
700 type possible. However, you should also take care to avoid leaking implementation
701 details into a function's public API. In keeping with these two principles, prefer
702 :py:class:`Iterator[YieldType] <typing.Iterator>` over
703 :py:class:`Iterable[YieldType] <typing.Iterable>` as the return-type annotation for a
704 generator function, as it lets mypy know that users are able to call :py:func:`next` on
705 the object returned by the function. Nonetheless, bear in mind that ``Iterable`` may
706 sometimes be the better option, if you consider it an implementation detail that
707 ``next()`` can be called on the object returned by your function.
708
709 If you want your generator to accept values via the :py:meth:`~generator.send` method or return
710 a value, on the other hand, you should use the
711 :py:class:`Generator[YieldType, SendType, ReturnType] <typing.Generator>` generic type instead of
712 either ``Iterator`` or ``Iterable``. For example:
713
714 .. code-block:: python
715
716 def echo_round() -> Generator[int, float, str]:
717 sent = yield 0
718 while sent >= 0:
719 sent = yield round(sent)
720 return 'Done'
721
722 Note that unlike many other generics in the typing module, the ``SendType`` of
723 :py:class:`~typing.Generator` behaves contravariantly, not covariantly or invariantly.
724
725 If you do not plan on receiving or returning values, then set the ``SendType``
726 or ``ReturnType`` to ``None``, as appropriate. For example, we could have
727 annotated the first example as the following:
728
729 .. code-block:: python
730
731 def squares(n: int) -> Generator[int, None, None]:
732 for i in range(n):
733 yield i * i
734
735 This is slightly different from using ``Iterator[int]`` or ``Iterable[int]``,
736 since generators have :py:meth:`~generator.close`, :py:meth:`~generator.send`, and :py:meth:`~generator.throw` methods that
737 generic iterators and iterables don't. If you plan to call these methods on the returned
738 generator, use the :py:class:`~typing.Generator` type instead of :py:class:`~typing.Iterator` or :py:class:`~typing.Iterable`.