Debian Codegraph @

docs/source/type_narrowing.rst

raw
1 .. _type-narrowing:
2
3 Type narrowing
4 ==============
5
6 This section is dedicated to several type narrowing
7 techniques which are supported by mypy.
8
9 Type narrowing is when you convince a type checker that a broader type is actually more specific, for instance, that an object of type ``Shape`` is actually of the narrower type ``Square``.
10
11 The following type narrowing techniques are available:
12
13 - :ref:`type-narrowing-expressions`
14 - :ref:`casts`
15 - :ref:`type-guards`
16 - :ref:`typeis`
17
18
19 .. _type-narrowing-expressions:
20
21 Type narrowing expressions
22 --------------------------
23
24 The simplest way to narrow a type is to use one of the supported expressions:
25
26 - :py:func:`isinstance` like in :code:`isinstance(obj, float)` will narrow ``obj`` to have ``float`` type
27 - :py:func:`issubclass` like in :code:`issubclass(cls, MyClass)` will narrow ``cls`` to be ``Type[MyClass]``
28 - :py:class:`type` like in :code:`type(obj) is int` will narrow ``obj`` to have ``int`` type
29 - :py:func:`callable` like in :code:`callable(obj)` will narrow object to callable type
30 - :code:`obj is not None` will narrow object to its :ref:`non-optional form <strict_optional>`
31
32 Type narrowing is contextual. For example, based on the condition, mypy will narrow an expression only within an ``if`` branch:
33
34 .. code-block:: python
35
36 def function(arg: object):
37 if isinstance(arg, int):
38 # Type is narrowed within the ``if`` branch only
39 reveal_type(arg) # Revealed type: "builtins.int"
40 elif isinstance(arg, str) or isinstance(arg, bool):
41 # Type is narrowed differently within this ``elif`` branch:
42 reveal_type(arg) # Revealed type: "builtins.str | builtins.bool"
43
44 # Subsequent narrowing operations will narrow the type further
45 if isinstance(arg, bool):
46 reveal_type(arg) # Revealed type: "builtins.bool"
47
48 # Back outside of the ``if`` statement, the type isn't narrowed:
49 reveal_type(arg) # Revealed type: "builtins.object"
50
51 Mypy understands the implications ``return`` or exception raising can have
52 for what type an object could be:
53
54 .. code-block:: python
55
56 def function(arg: int | str):
57 if isinstance(arg, int):
58 return
59
60 # `arg` can't be `int` at this point:
61 reveal_type(arg) # Revealed type: "builtins.str"
62
63 We can also use ``assert`` to narrow types in the same context:
64
65 .. code-block:: python
66
67 def function(arg: Any):
68 assert isinstance(arg, int)
69 reveal_type(arg) # Revealed type: "builtins.int"
70
71 .. note::
72
73 With :option:`--warn-unreachable <mypy --warn-unreachable>`
74 narrowing types to some impossible state will be treated as an error.
75
76 .. code-block:: python
77
78 def function(arg: int):
79 # error: Subclass of "int" and "str" cannot exist:
80 # would have incompatible method signatures
81 assert isinstance(arg, str)
82
83 # error: Statement is unreachable
84 print("so mypy concludes the assert will always trigger")
85
86 Without ``--warn-unreachable`` mypy will simply not check code it deems to be
87 unreachable. See :ref:`unreachable` for more information.
88
89 .. code-block:: python
90
91 x: int = 1
92 assert isinstance(x, str)
93 reveal_type(x) # Revealed type is "builtins.int"
94 print(x + '!') # Typechecks with `mypy`, but fails in runtime.
95
96
97 issubclass
98 ~~~~~~~~~~
99
100 Mypy can also use :py:func:`issubclass`
101 for better type inference when working with types and metaclasses:
102
103 .. code-block:: python
104
105 class MyCalcMeta(type):
106 @classmethod
107 def calc(cls) -> int:
108 ...
109
110 def f(o: object) -> None:
111 t = type(o) # We must use a variable here
112 reveal_type(t) # Revealed type is "builtins.type"
113
114 if issubclass(t, MyCalcMeta): # `issubclass(type(o), MyCalcMeta)` won't work
115 reveal_type(t) # Revealed type is "Type[MyCalcMeta]"
116 t.calc() # Okay
117
118 callable
119 ~~~~~~~~
120
121 Mypy knows what types are callable and which ones are not during type checking.
122 So, we know what ``callable()`` will return. For example:
123
124 .. code-block:: python
125
126 from collections.abc import Callable
127
128 x: Callable[[], int]
129
130 if callable(x):
131 reveal_type(x) # N: Revealed type is "def () -> builtins.int"
132 else:
133 ... # Will never be executed and will raise error with `--warn-unreachable`
134
135 The ``callable`` function can even split union types into
136 callable and non-callable parts:
137
138 .. code-block:: python
139
140 from collections.abc import Callable
141
142 x: int | Callable[[], int]
143
144 if callable(x):
145 reveal_type(x) # N: Revealed type is "def () -> builtins.int"
146 else:
147 reveal_type(x) # N: Revealed type is "builtins.int"
148
149 .. _casts:
150
151 Casts
152 -----
153
154 Mypy supports type casts that are usually used to coerce a statically
155 typed value to a subtype. Unlike languages such as Java or C#,
156 however, mypy casts are only used as hints for the type checker, and they
157 don't perform a runtime type check. Use the function :py:func:`~typing.cast`
158 to perform a cast:
159
160 .. code-block:: python
161
162 from typing import cast
163
164 o: object = [1]
165 x = cast(list[int], o) # OK
166 y = cast(list[str], o) # OK (cast performs no actual runtime check)
167
168 To support runtime checking of casts such as the above, we'd have to check
169 the types of all list items, which would be very inefficient for large lists.
170 Casts are used to silence spurious
171 type checker warnings and give the type checker a little help when it can't
172 quite understand what is going on.
173
174 .. note::
175
176 You can use an assertion if you want to perform an actual runtime check:
177
178 .. code-block:: python
179
180 def foo(o: object) -> None:
181 print(o + 5) # Error: can't add 'object' and 'int'
182 assert isinstance(o, int)
183 print(o + 5) # OK: type of 'o' is 'int' here
184
185 You don't need a cast for expressions with type ``Any``, or when
186 assigning to a variable with type ``Any``, as was explained earlier.
187 You can also use ``Any`` as the cast target type -- this lets you perform
188 any operations on the result. For example:
189
190 .. code-block:: python
191
192 from typing import cast, Any
193
194 x = 1
195 x.whatever() # Type check error
196 y = cast(Any, x)
197 y.whatever() # Type check OK (runtime error)
198
199
200 .. _type-guards:
201
202 User-Defined Type Guards
203 ------------------------
204
205 Mypy supports User-Defined Type Guards (:pep:`647`).
206
207 A type guard is a way for programs to influence conditional
208 type narrowing employed by a type checker based on runtime checks.
209
210 Basically, a ``TypeGuard`` is a "smart" alias for a ``bool`` type.
211 Let's have a look at the regular ``bool`` example:
212
213 .. code-block:: python
214
215 def is_str_list(val: list[object]) -> bool:
216 """Determines whether all objects in the list are strings"""
217 return all(isinstance(x, str) for x in val)
218
219 def func1(val: list[object]) -> None:
220 if is_str_list(val):
221 reveal_type(val) # Reveals list[object]
222 print(" ".join(val)) # Error: incompatible type
223
224 The same example with ``TypeGuard``:
225
226 .. code-block:: python
227
228 from typing import TypeGuard
229
230 def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
231 """Determines whether all objects in the list are strings"""
232 return all(isinstance(x, str) for x in val)
233
234 def func1(val: list[object]) -> None:
235 if is_str_list(val):
236 reveal_type(val) # list[str]
237 print(" ".join(val)) # ok
238
239 How does it work? ``TypeGuard`` narrows the first function argument (``val``)
240 to the type specified as the first type parameter (``list[str]``).
241
242 .. note::
243
244 Narrowing is
245 `not strict <https://www.python.org/dev/peps/pep-0647/#enforcing-strict-narrowing>`_.
246 For example, you can narrow ``str`` to ``int``:
247
248 .. code-block:: python
249
250 def f(value: str) -> TypeGuard[int]:
251 return True
252
253 Note: since strict narrowing is not enforced, it's easy
254 to break type safety.
255
256 However, there are many ways a determined or uninformed developer can
257 subvert type safety -- most commonly by using cast or Any.
258 If a Python developer takes the time to learn about and implement
259 user-defined type guards within their code,
260 it is safe to assume that they are interested in type safety
261 and will not write their type guard functions in a way
262 that will undermine type safety or produce nonsensical results.
263
264 Generic TypeGuards
265 ~~~~~~~~~~~~~~~~~~
266
267 ``TypeGuard`` can also work with generic types (Python 3.12 syntax):
268
269 .. code-block:: python
270
271 from typing import TypeGuard # use `typing_extensions` for `python<3.10`
272
273 def is_two_element_tuple[T](val: tuple[T, ...]) -> TypeGuard[tuple[T, T]]:
274 return len(val) == 2
275
276 def func(names: tuple[str, ...]):
277 if is_two_element_tuple(names):
278 reveal_type(names) # tuple[str, str]
279 else:
280 reveal_type(names) # tuple[str, ...]
281
282 TypeGuards with parameters
283 ~~~~~~~~~~~~~~~~~~~~~~~~~~
284
285 Type guard functions can accept extra arguments (Python 3.12 syntax):
286
287 .. code-block:: python
288
289 from typing import TypeGuard # use `typing_extensions` for `python<3.10`
290
291 def is_set_of[T](val: set[Any], type: type[T]) -> TypeGuard[set[T]]:
292 return all(isinstance(x, type) for x in val)
293
294 items: set[Any]
295 if is_set_of(items, str):
296 reveal_type(items) # set[str]
297
298 TypeGuards as methods
299 ~~~~~~~~~~~~~~~~~~~~~
300
301 A method can also serve as a ``TypeGuard``:
302
303 .. code-block:: python
304
305 class StrValidator:
306 def is_valid(self, instance: object) -> TypeGuard[str]:
307 return isinstance(instance, str)
308
309 def func(to_validate: object) -> None:
310 if StrValidator().is_valid(to_validate):
311 reveal_type(to_validate) # Revealed type is "builtins.str"
312
313 .. note::
314
315 Note, that ``TypeGuard``
316 `does not narrow <https://www.python.org/dev/peps/pep-0647/#narrowing-of-implicit-self-and-cls-parameters>`_
317 types of ``self`` or ``cls`` implicit arguments.
318
319 If narrowing of ``self`` or ``cls`` is required,
320 the value can be passed as an explicit argument to a type guard function:
321
322 .. code-block:: python
323
324 class Parent:
325 def method(self) -> None:
326 reveal_type(self) # Revealed type is "Parent"
327 if is_child(self):
328 reveal_type(self) # Revealed type is "Child"
329
330 class Child(Parent):
331 ...
332
333 def is_child(instance: Parent) -> TypeGuard[Child]:
334 return isinstance(instance, Child)
335
336 Assignment expressions as TypeGuards
337 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
338
339 Sometimes you might need to create a new variable and narrow it
340 to some specific type at the same time.
341 This can be achieved by using ``TypeGuard`` together
342 with `:= operator <https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions>`_.
343
344 .. code-block:: python
345
346 from typing import TypeGuard # use `typing_extensions` for `python<3.10`
347
348 def is_float(a: object) -> TypeGuard[float]:
349 return isinstance(a, float)
350
351 def main(a: object) -> None:
352 if is_float(x := a):
353 reveal_type(x) # N: Revealed type is 'builtins.float'
354 reveal_type(a) # N: Revealed type is 'builtins.object'
355 reveal_type(x) # N: Revealed type is 'builtins.object'
356 reveal_type(a) # N: Revealed type is 'builtins.object'
357
358 What happens here?
359
360 1. We create a new variable ``x`` and assign a value of ``a`` to it
361 2. We run ``is_float()`` type guard on ``x``
362 3. It narrows ``x`` to be ``float`` in the ``if`` context and does not touch ``a``
363
364 .. note::
365
366 The same will work with ``isinstance(x := a, float)`` as well.
367
368
369 .. _typeis:
370
371 TypeIs
372 ------
373
374 Mypy supports TypeIs (:pep:`742`).
375
376 A `TypeIs narrowing function <https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeis>`_
377 allows you to define custom type checks that can narrow the type of a variable
378 in `both the if and else <https://docs.python.org/3.13/library/typing.html#typing.TypeIs>`_
379 branches of a conditional, similar to how the built-in isinstance() function works.
380
381 TypeIs is new in Python 3.13 — for use in older Python versions, use the backport
382 from `typing_extensions <https://typing-extensions.readthedocs.io/en/latest/>`_
383
384 Consider the following example using TypeIs:
385
386 .. code-block:: python
387
388 from typing import TypeIs
389
390 def is_str(x: object) -> TypeIs[str]:
391 return isinstance(x, str)
392
393 def process(x: int | str) -> None:
394 if is_str(x):
395 reveal_type(x) # Revealed type is 'str'
396 print(x.upper()) # Valid: x is str
397 else:
398 reveal_type(x) # Revealed type is 'int'
399 print(x + 1) # Valid: x is int
400
401 In this example, the function is_str is a type narrowing function
402 that returns TypeIs[str]. When used in an if statement, x is narrowed
403 to str in the if branch and to int in the else branch.
404
405 Key points:
406
407
408 - The function must accept at least one positional argument.
409
410 - The return type is annotated as ``TypeIs[T]``, where ``T`` is the type you
411 want to narrow to.
412
413 - The function must return a ``bool`` value.
414
415 - In the ``if`` branch (when the function returns ``True``), the type of the
416 argument is narrowed to the intersection of its original type and ``T``.
417
418 - In the ``else`` branch (when the function returns ``False``), the type of
419 the argument is narrowed to the intersection of its original type and the
420 complement of ``T``.
421
422
423 TypeIs vs TypeGuard
424 ~~~~~~~~~~~~~~~~~~~
425
426 While both TypeIs and TypeGuard allow you to define custom type narrowing
427 functions, they differ in important ways:
428
429 - **Type narrowing behavior**: TypeIs narrows the type in both the if and else branches,
430 whereas TypeGuard narrows only in the if branch.
431
432 - **Compatibility requirement**: TypeIs requires that the narrowed type T be
433 compatible with the input type of the function. TypeGuard does not have this restriction.
434
435 - **Type inference**: With TypeIs, the type checker may infer a more precise type by
436 combining existing type information with T.
437
438 Here's an example demonstrating the behavior with TypeGuard:
439
440 .. code-block:: python
441
442 from typing import TypeGuard, reveal_type
443
444 def is_str(x: object) -> TypeGuard[str]:
445 return isinstance(x, str)
446
447 def process(x: int | str) -> None:
448 if is_str(x):
449 reveal_type(x) # Revealed type is "builtins.str"
450 print(x.upper()) # ok: x is str
451 else:
452 reveal_type(x) # Revealed type is "Union[builtins.int, builtins.str]"
453 print(x + 1) # ERROR: Unsupported operand types for + ("str" and "int") [operator]
454
455 Generic TypeIs
456 ~~~~~~~~~~~~~~
457
458 ``TypeIs`` functions can also work with generic types:
459
460 .. code-block:: python
461
462 from typing import TypeVar, TypeIs
463
464 T = TypeVar('T')
465
466 def is_two_element_tuple(val: tuple[T, ...]) -> TypeIs[tuple[T, T]]:
467 return len(val) == 2
468
469 def process(names: tuple[str, ...]) -> None:
470 if is_two_element_tuple(names):
471 reveal_type(names) # Revealed type is 'tuple[str, str]'
472 else:
473 reveal_type(names) # Revealed type is 'tuple[str, ...]'
474
475
476 TypeIs with Additional Parameters
477 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
478 TypeIs functions can accept additional parameters beyond the first.
479 The type narrowing applies only to the first argument.
480
481 .. code-block:: python
482
483 from typing import Any, TypeVar, reveal_type, TypeIs
484
485 T = TypeVar('T')
486
487 def is_instance_of(val: Any, typ: type[T]) -> TypeIs[T]:
488 return isinstance(val, typ)
489
490 def process(x: Any) -> None:
491 if is_instance_of(x, int):
492 reveal_type(x) # Revealed type is 'int'
493 print(x + 1) # ok
494 else:
495 reveal_type(x) # Revealed type is 'Any'
496
497 TypeIs in Methods
498 ~~~~~~~~~~~~~~~~~
499
500 A method can also serve as a ``TypeIs`` function. Note that in instance or
501 class methods, the type narrowing applies to the second parameter
502 (after ``self`` or ``cls``).
503
504 .. code-block:: python
505
506 class Validator:
507 def is_valid(self, instance: object) -> TypeIs[str]:
508 return isinstance(instance, str)
509
510 def process(self, to_validate: object) -> None:
511 if Validator().is_valid(to_validate):
512 reveal_type(to_validate) # Revealed type is 'str'
513 print(to_validate.upper()) # ok: to_validate is str
514
515
516 Assignment Expressions with TypeIs
517 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
518
519 You can use the assignment expression operator ``:=`` with ``TypeIs`` to create a new variable and narrow its type simultaneously.
520
521 .. code-block:: python
522
523 from typing import TypeIs, reveal_type
524
525 def is_float(x: object) -> TypeIs[float]:
526 return isinstance(x, float)
527
528 def main(a: object) -> None:
529 if is_float(x := a):
530 reveal_type(x) # Revealed type is 'float'
531 # x is narrowed to float in this block
532 print(x + 1.0)
533
534
535 Limitations
536 -----------
537
538 Mypy's analysis is limited to individual symbols and it will not track
539 relationships between symbols. For example, in the following code
540 it's easy to deduce that if :code:`a` is None then :code:`b` must not be,
541 therefore :code:`a or b` will always be an instance of :code:`C`,
542 but Mypy will not be able to tell that:
543
544 .. code-block:: python
545
546 class C:
547 pass
548
549 def f(a: C | None, b: C | None) -> C:
550 if a is not None or b is not None:
551 return a or b # Incompatible return value type (got "C | None", expected "C")
552 return C()
553
554 Tracking these sort of cross-variable conditions in a type checker would add significant complexity
555 and performance overhead.
556
557 You can use an ``assert`` to convince the type checker, override it with a :ref:`cast <casts>`
558 or rewrite the function to be slightly more verbose:
559
560 .. code-block:: python
561
562 def f(a: C | None, b: C | None) -> C:
563 if a is not None:
564 return a
565 elif b is not None:
566 return b
567 return C()