Debian Codegraph @

docs/source/error_code_list2.rst

raw
1 .. _error-codes-optional:
2
3 Error codes for optional checks
4 ===============================
5
6 This section documents various errors codes that mypy generates only
7 if you enable certain options. See :ref:`error-codes` for general
8 documentation about error codes and their configuration.
9 :ref:`error-code-list` documents error codes that are enabled by default.
10
11 .. note::
12
13 The examples in this section use :ref:`inline configuration
14 <inline-config>` to specify mypy options. You can also set the same
15 options by using a :ref:`configuration file <config-file>` or
16 :ref:`command-line options <command-line>`.
17
18 .. _code-type-arg:
19
20 Check that type arguments exist [type-arg]
21 ------------------------------------------
22
23 If you use :option:`--disallow-any-generics <mypy --disallow-any-generics>`, mypy requires that each generic
24 type has values for each type argument. For example, the types ``list`` or
25 ``dict`` would be rejected. You should instead use types like ``list[int]`` or
26 ``dict[str, int]``. Any omitted generic type arguments get implicit ``Any``
27 values. The type ``list`` is equivalent to ``list[Any]``, and so on.
28
29 Example:
30
31 .. code-block:: python
32
33 # mypy: disallow-any-generics
34
35 # Error: Missing type arguments for generic type "list" [type-arg]
36 def remove_dups(items: list) -> list:
37 ...
38
39 .. _code-no-untyped-def:
40
41 Check that every function has an annotation [no-untyped-def]
42 ------------------------------------------------------------
43
44 If you use :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`, mypy requires that all functions
45 have annotations (either a Python 3 annotation or a type comment).
46
47 Example:
48
49 .. code-block:: python
50
51 # mypy: disallow-untyped-defs
52
53 def inc(x): # Error: Function is missing a type annotation [no-untyped-def]
54 return x + 1
55
56 def inc_ok(x: int) -> int: # OK
57 return x + 1
58
59 class Counter:
60 # Error: Function is missing a type annotation [no-untyped-def]
61 def __init__(self):
62 self.value = 0
63
64 class CounterOk:
65 # OK: An explicit "-> None" is needed if "__init__" takes no arguments
66 def __init__(self) -> None:
67 self.value = 0
68
69 .. _code-redundant-cast:
70
71 Check that cast is not redundant [redundant-cast]
72 -------------------------------------------------
73
74 If you use :option:`--warn-redundant-casts <mypy --warn-redundant-casts>`, mypy will generate an error if the source
75 type of a cast is the same as the target type.
76
77 Example:
78
79 .. code-block:: python
80
81 # mypy: warn-redundant-casts
82
83 from typing import cast
84
85 Count = int
86
87 def example(x: Count) -> int:
88 # Error: Redundant cast to "int" [redundant-cast]
89 return cast(int, x)
90
91 .. _code-redundant-self:
92
93 Check that methods do not have redundant Self annotations [redundant-self]
94 --------------------------------------------------------------------------
95
96 If a method uses the ``Self`` type in the return type or the type of a
97 non-self argument, there is no need to annotate the ``self`` argument
98 explicitly. Such annotations are allowed by :pep:`673` but are
99 redundant. If you enable this error code, mypy will generate an error if
100 there is a redundant ``Self`` type.
101
102 Example:
103
104 .. code-block:: python
105
106 # mypy: enable-error-code="redundant-self"
107
108 from typing import Self
109
110 class C:
111 # Error: Redundant "Self" annotation for the first method argument
112 def copy(self: Self) -> Self:
113 return type(self)()
114
115 .. _code-comparison-overlap:
116
117 Check that comparisons are overlapping [comparison-overlap]
118 -----------------------------------------------------------
119
120 If you use :option:`--strict-equality <mypy --strict-equality>`, mypy will generate an error if it
121 thinks that a comparison operation is always true or false. These are
122 often bugs. Sometimes mypy is too picky and the comparison can
123 actually be useful. Instead of disabling strict equality checking
124 everywhere, you can use ``# type: ignore[comparison-overlap]`` to
125 ignore the issue on a particular line only.
126
127 Example:
128
129 .. code-block:: python
130
131 # mypy: strict-equality
132
133 def is_magic(x: bytes) -> bool:
134 # Error: Non-overlapping equality check (left operand type: "bytes",
135 # right operand type: "str") [comparison-overlap]
136 return x == 'magic'
137
138 We can fix the error by changing the string literal to a bytes
139 literal:
140
141 .. code-block:: python
142
143 # mypy: strict-equality
144
145 def is_magic(x: bytes) -> bool:
146 return x == b'magic' # OK
147
148 :option:`--strict-equality <mypy --strict-equality>` does not include comparisons with
149 ``None``:
150
151 .. code-block:: python
152
153 # mypy: strict-equality
154
155 def is_none(x: str) -> bool:
156 return x is None # OK
157
158 If you want such checks, you must also activate
159 :option:`--strict-equality-for-none <mypy --strict-equality-for-none>` (we might merge
160 these two options later).
161
162 .. code-block:: python
163
164 # mypy: strict-equality strict-equality-for-none
165
166 def is_none(x: str) -> bool:
167 # Error: Non-overlapping identity check
168 # (left operand type: "str", right operand type: "None")
169 return x is None
170
171 .. _code-no-untyped-call:
172
173 Check that no untyped functions are called [no-untyped-call]
174 ------------------------------------------------------------
175
176 If you use :option:`--disallow-untyped-calls <mypy --disallow-untyped-calls>`, mypy generates an error when you
177 call an unannotated function in an annotated function.
178
179 Example:
180
181 .. code-block:: python
182
183 # mypy: disallow-untyped-calls
184
185 def do_it() -> None:
186 # Error: Call to untyped function "bad" in typed context [no-untyped-call]
187 bad()
188
189 def bad():
190 ...
191
192 .. _code-no-any-return:
193
194 Check that function does not return Any value [no-any-return]
195 -------------------------------------------------------------
196
197 If you use :option:`--warn-return-any <mypy --warn-return-any>`, mypy generates an error if you return a
198 value with an ``Any`` type in a function that is annotated to return a
199 non-``Any`` value.
200
201 Example:
202
203 .. code-block:: python
204
205 # mypy: warn-return-any
206
207 def fields(s):
208 return s.split(',')
209
210 def first_field(x: str) -> str:
211 # Error: Returning Any from function declared to return "str" [no-any-return]
212 return fields(x)[0]
213
214 .. _code-no-any-unimported:
215
216 Check that types have no Any components due to missing imports [no-any-unimported]
217 ----------------------------------------------------------------------------------
218
219 If you use :option:`--disallow-any-unimported <mypy --disallow-any-unimported>`, mypy generates an error if a component of
220 a type becomes ``Any`` because mypy couldn't resolve an import. These "stealth"
221 ``Any`` types can be surprising and accidentally cause imprecise type checking.
222
223 In this example, we assume that mypy can't find the module ``animals``, which means
224 that ``Cat`` falls back to ``Any`` in a type annotation:
225
226 .. code-block:: python
227
228 # mypy: disallow-any-unimported
229
230 from animals import Cat # type: ignore
231
232 # Error: Argument 1 to "feed" becomes "Any" due to an unfollowed import [no-any-unimported]
233 def feed(cat: Cat) -> None:
234 ...
235
236 .. _code-unreachable:
237
238 Check that statement or expression is unreachable [unreachable]
239 ---------------------------------------------------------------
240
241 If you use :option:`--warn-unreachable <mypy --warn-unreachable>`, mypy generates an error if it
242 thinks that a statement or expression will never be executed. In most cases, this is due to
243 incorrect control flow or conditional checks that are accidentally always true or false.
244
245 .. code-block:: python
246
247 # mypy: warn-unreachable
248
249 def example(x: int) -> None:
250 # Error: Right operand of "or" is never evaluated [unreachable]
251 assert isinstance(x, int) or x == 'unused'
252
253 return
254 # Error: Statement is unreachable [unreachable]
255 print('unreachable')
256
257 .. _code-deprecated:
258
259 Check that imported or used feature is deprecated [deprecated]
260 --------------------------------------------------------------
261
262 If you use :option:`--enable-error-code deprecated <mypy --enable-error-code>`,
263 mypy generates an error if your code imports a deprecated feature explicitly with a
264 ``from mod import depr`` statement or uses a deprecated feature imported otherwise or defined
265 locally. Features are considered deprecated when decorated with ``warnings.deprecated``, as
266 specified in `PEP 702 <https://peps.python.org/pep-0702>`_.
267 Use the :option:`--report-deprecated-as-note <mypy --report-deprecated-as-note>` option to
268 turn all such errors into notes.
269 Use :option:`--deprecated-calls-exclude <mypy --deprecated-calls-exclude>` to hide warnings
270 for specific functions, classes and packages.
271
272 .. note::
273
274 The ``warnings`` module provides the ``@deprecated`` decorator since Python 3.13.
275 To use it with older Python versions, import it from ``typing_extensions`` instead.
276
277 Examples:
278
279 .. code-block:: python
280
281 # mypy: report-deprecated-as-error
282
283 # Error: abc.abstractproperty is deprecated: Deprecated, use 'property' with 'abstractmethod' instead
284 from abc import abstractproperty
285
286 from typing_extensions import deprecated
287
288 @deprecated("use new_function")
289 def old_function() -> None:
290 print("I am old")
291
292 # Error: __main__.old_function is deprecated: use new_function
293 old_function()
294 old_function() # type: ignore[deprecated]
295
296
297 .. _code-redundant-expr:
298
299 Check that expression is redundant [redundant-expr]
300 ---------------------------------------------------
301
302 If you use :option:`--enable-error-code redundant-expr <mypy --enable-error-code>`,
303 mypy generates an error if it thinks that an expression is redundant.
304
305 .. code-block:: python
306
307 # mypy: enable-error-code="redundant-expr"
308
309 def example(x: int) -> None:
310 # Error: Left operand of "and" is always true [redundant-expr]
311 if isinstance(x, int) and x > 0:
312 pass
313
314 # Error: If condition is always true [redundant-expr]
315 1 if isinstance(x, int) else 0
316
317 # Error: If condition in comprehension is always true [redundant-expr]
318 [i for i in range(x) if isinstance(i, int)]
319
320
321 .. _code-possibly-undefined:
322
323 Warn about variables that are defined only in some execution paths [possibly-undefined]
324 ---------------------------------------------------------------------------------------
325
326 If you use :option:`--enable-error-code possibly-undefined <mypy --enable-error-code>`,
327 mypy generates an error if it cannot verify that a variable will be defined in
328 all execution paths. This includes situations when a variable definition
329 appears in a loop, in a conditional branch, in an except handler, etc. For
330 example:
331
332 .. code-block:: python
333
334 # mypy: enable-error-code="possibly-undefined"
335
336 from collections.abc import Iterable
337
338 def test(values: Iterable[int], flag: bool) -> None:
339 if flag:
340 a = 1
341 z = a + 1 # Error: Name "a" may be undefined [possibly-undefined]
342
343 for v in values:
344 b = v
345 z = b + 1 # Error: Name "b" may be undefined [possibly-undefined]
346
347 .. _code-truthy-bool:
348
349 Check that expression is not implicitly true in boolean context [truthy-bool]
350 -----------------------------------------------------------------------------
351
352 Warn when the type of an expression in a boolean context does not
353 implement ``__bool__`` or ``__len__``. Unless one of these is
354 implemented by a subtype, the expression will always be considered
355 true, and there may be a bug in the condition.
356
357 As an exception, the ``object`` type is allowed in a boolean context.
358 Using an iterable value in a boolean context has a separate error code
359 (see below).
360
361 .. code-block:: python
362
363 # mypy: enable-error-code="truthy-bool"
364
365 class Foo:
366 pass
367 foo = Foo()
368 # Error: "foo" has type "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context
369 if foo:
370 ...
371
372 .. _code-truthy-iterable:
373
374 Check that iterable is not implicitly true in boolean context [truthy-iterable]
375 -------------------------------------------------------------------------------
376
377 Generate an error if a value of type ``Iterable`` is used as a boolean
378 condition, since ``Iterable`` does not implement ``__len__`` or ``__bool__``.
379
380 Example:
381
382 .. code-block:: python
383
384 from collections.abc import Iterable
385
386 def transform(items: Iterable[int]) -> list[int]:
387 # Error: "items" has type "Iterable[int]" which can always be true in boolean context. Consider using "Collection[int]" instead. [truthy-iterable]
388 if not items:
389 return [42]
390 return [x + 1 for x in items]
391
392 If ``transform`` is called with a ``Generator`` argument, such as
393 ``int(x) for x in []``, this function would not return ``[42]`` unlike
394 what might be intended. Of course, it's possible that ``transform`` is
395 only called with ``list`` or other container objects, and the ``if not
396 items`` check is actually valid. If that is the case, it is
397 recommended to annotate ``items`` as ``Collection[int]`` instead of
398 ``Iterable[int]``.
399
400 .. _code-ignore-without-code:
401
402 Check that ``# type: ignore`` include an error code [ignore-without-code]
403 -------------------------------------------------------------------------
404
405 Warn when a ``# type: ignore`` comment does not specify any error codes.
406 This clarifies the intent of the ignore and ensures that only the
407 expected errors are silenced.
408
409 Example:
410
411 .. code-block:: python
412
413 # mypy: enable-error-code="ignore-without-code"
414
415 class Foo:
416 def __init__(self, name: str) -> None:
417 self.name = name
418
419 f = Foo('foo')
420
421 # This line has a typo that mypy can't help with as both:
422 # - the expected error 'assignment', and
423 # - the unexpected error 'attr-defined'
424 # are silenced.
425 # Error: "type: ignore" comment without error code (consider "type: ignore[attr-defined]" instead)
426 f.nme = 42 # type: ignore
427
428 # This line warns correctly about the typo in the attribute name
429 # Error: "Foo" has no attribute "nme"; maybe "name"?
430 f.nme = 42 # type: ignore[assignment]
431
432 .. _code-unused-awaitable:
433
434 Check that awaitable return value is used [unused-awaitable]
435 ------------------------------------------------------------
436
437 If you use :option:`--enable-error-code unused-awaitable <mypy --enable-error-code>`,
438 mypy generates an error if you don't use a returned value that defines ``__await__``.
439
440 Example:
441
442 .. code-block:: python
443
444 # mypy: enable-error-code="unused-awaitable"
445
446 import asyncio
447
448 async def f() -> int: ...
449
450 async def g() -> None:
451 # Error: Value of type "Task[int]" must be used
452 # Are you missing an await?
453 asyncio.create_task(f())
454
455 You can assign the value to a temporary, otherwise unused variable to
456 silence the error:
457
458 .. code-block:: python
459
460 async def g() -> None:
461 _ = asyncio.create_task(f()) # No error
462
463 .. _code-unused-ignore:
464
465 Check that ``# type: ignore`` comment is used [unused-ignore]
466 -------------------------------------------------------------
467
468 If you use :option:`--enable-error-code unused-ignore <mypy --enable-error-code>`,
469 or :option:`--warn-unused-ignores <mypy --warn-unused-ignores>`
470 mypy generates an error if you don't use a ``# type: ignore`` comment, i.e. if
471 there is a comment, but there would be no error generated by mypy on this line
472 anyway.
473
474 Example:
475
476 .. code-block:: python
477
478 # Use "mypy --warn-unused-ignores ..."
479
480 def add(a: int, b: int) -> int:
481 # Error: unused "type: ignore" comment
482 return a + b # type: ignore
483
484 Note that due to a specific nature of this comment, the only way to selectively
485 silence it, is to include the error code explicitly. Also note that this error is
486 not shown if the ``# type: ignore`` is not used due to code being statically
487 unreachable (e.g. due to platform or version checks).
488
489 Example:
490
491 .. code-block:: python
492
493 # Use "mypy --warn-unused-ignores ..."
494
495 import sys
496
497 try:
498 # The "[unused-ignore]" is needed to get a clean mypy run
499 # on both Python 3.8, and 3.9 where this module was added
500 import graphlib # type: ignore[import,unused-ignore]
501 except ImportError:
502 pass
503
504 if sys.version_info >= (3, 9):
505 # The following will not generate an error on either
506 # Python 3.8, or Python 3.9
507 42 + "testing..." # type: ignore
508
509 .. _code-explicit-override:
510
511 Check that ``@override`` is used when overriding a base class method [explicit-override]
512 ----------------------------------------------------------------------------------------
513
514 If you use :option:`--enable-error-code explicit-override <mypy --enable-error-code>`
515 mypy generates an error if you override a base class method without using the
516 ``@override`` decorator. An error will not be emitted for overrides of ``__init__``
517 or ``__new__``. See `PEP 698 <https://peps.python.org/pep-0698/#strict-enforcement-per-project>`_.
518
519 .. note::
520
521 Starting with Python 3.12, the ``@override`` decorator can be imported from ``typing``.
522 To use it with older Python versions, import it from ``typing_extensions`` instead.
523
524 Example:
525
526 .. code-block:: python
527
528 # mypy: enable-error-code="explicit-override"
529
530 from typing import override
531
532 class Parent:
533 def f(self, x: int) -> None:
534 pass
535
536 def g(self, y: int) -> None:
537 pass
538
539
540 class Child(Parent):
541 def f(self, x: int) -> None: # Error: Missing @override decorator
542 pass
543
544 @override
545 def g(self, y: int) -> None:
546 pass
547
548 .. _code-mutable-override:
549
550 Check that overrides of mutable attributes are safe [mutable-override]
551 ----------------------------------------------------------------------
552
553 ``mutable-override`` will enable the check for unsafe overrides of mutable attributes.
554 For historical reasons, and because this is a relatively common pattern in Python,
555 this check is not enabled by default. The example below is unsafe, and will be
556 flagged when this error code is enabled:
557
558 .. code-block:: python
559
560 from typing import Any
561
562 class C:
563 x: float
564 y: float
565 z: float
566
567 class D(C):
568 x: int # Error: Covariant override of a mutable attribute
569 # (base class "C" defined the type as "float",
570 # expression has type "int") [mutable-override]
571 y: float # OK
572 z: Any # OK
573
574 def f(c: C) -> None:
575 c.x = 1.1
576 d = D()
577 f(d)
578 d.x >> 1 # This will crash at runtime, because d.x is now float, not an int
579
580 .. _code-unimported-reveal:
581
582 Check that ``reveal_type`` is imported from typing or typing_extensions [unimported-reveal]
583 -------------------------------------------------------------------------------------------
584
585 Mypy used to have ``reveal_type`` as a special builtin
586 that only existed during type-checking.
587 In runtime it fails with expected ``NameError``,
588 which can cause real problem in production, hidden from mypy.
589
590 But, in Python3.11 :py:func:`typing.reveal_type` was added.
591 ``typing_extensions`` ported this helper to all supported Python versions.
592
593 Now users can actually import ``reveal_type`` to make the runtime code safe.
594
595 .. note::
596
597 Starting with Python 3.11, the ``reveal_type`` function can be imported from ``typing``.
598 To use it with older Python versions, import it from ``typing_extensions`` instead.
599
600 .. code-block:: python
601
602 # mypy: enable-error-code="unimported-reveal"
603
604 x = 1
605 reveal_type(x) # Note: Revealed type is "builtins.int" \
606 # Error: Name "reveal_type" is not defined
607
608 Correct usage:
609
610 .. code-block:: python
611
612 # mypy: enable-error-code="unimported-reveal"
613 from typing import reveal_type # or `typing_extensions`
614
615 x = 1
616 # This won't raise an error:
617 reveal_type(x) # Note: Revealed type is "builtins.int"
618
619 When this code is enabled, using ``reveal_locals`` is always an error,
620 because there's no way one can import it.
621
622
623 .. _code-explicit-any:
624
625 Check that explicit Any type annotations are not allowed [explicit-any]
626 -----------------------------------------------------------------------
627
628 If you use :option:`--disallow-any-explicit <mypy --disallow-any-explicit>`, mypy generates an error
629 if you use an explicit ``Any`` type annotation.
630
631 Example:
632
633 .. code-block:: python
634
635 # mypy: disallow-any-explicit
636 from typing import Any
637 x: Any = 1 # Error: Explicit "Any" type annotation [explicit-any]
638
639
640 .. _code-exhaustive-match:
641
642 Check that match statements match exhaustively [exhaustive-match]
643 -----------------------------------------------------------------------
644
645 If enabled with :option:`--enable-error-code exhaustive-match <mypy --enable-error-code>`,
646 mypy generates an error if a match statement does not match all possible cases/types.
647
648
649 Example:
650
651 .. code-block:: python
652
653 import enum
654
655
656 class Color(enum.Enum):
657 RED = 1
658 BLUE = 2
659
660 val: Color = Color.RED
661
662 # OK without --enable-error-code exhaustive-match
663 match val:
664 case Color.RED:
665 print("red")
666
667 # With --enable-error-code exhaustive-match
668 # Error: Match statement has unhandled case for values of type "Literal[Color.BLUE]"
669 match val:
670 case Color.RED:
671 print("red")
672
673 # OK with or without --enable-error-code exhaustive-match, since all cases are handled
674 match val:
675 case Color.RED:
676 print("red")
677 case _:
678 print("other")
679
680 .. _code-untyped-decorator:
681
682 Error if an untyped decorator makes a typed function effectively untyped [untyped-decorator]
683 --------------------------------------------------------------------------------------------
684
685 If enabled with :option:`--disallow-untyped-decorators <mypy --disallow-untyped-decorators>`
686 mypy generates an error if a typed function is wrapped by an untyped decorator
687 (as this would effectively remove the benefits of typing the function).
688
689 Example:
690
691 .. code-block:: python
692
693 def printing_decorator(func):
694 def wrapper(*args, **kwds):
695 print("Calling", func)
696 return func(*args, **kwds)
697 return wrapper
698 # A decorated function.
699 @printing_decorator # E: Untyped decorator makes function "add_forty_two" untyped [untyped-decorator]
700 def add_forty_two(value: int) -> int:
701 return value + 42