| 1 |
.. _error-code-list: |
| 2 |
|
| 3 |
Error codes enabled by default |
| 4 |
============================== |
| 5 |
|
| 6 |
This section documents various errors codes that mypy can generate |
| 7 |
with default options. See :ref:`error-codes` for general documentation |
| 8 |
about error codes. :ref:`error-codes-optional` documents additional |
| 9 |
error codes that you can enable. |
| 10 |
|
| 11 |
.. _code-attr-defined: |
| 12 |
|
| 13 |
Check that attribute exists [attr-defined] |
| 14 |
------------------------------------------ |
| 15 |
|
| 16 |
Mypy checks that an attribute is defined in the target class or module |
| 17 |
when using the dot operator. This applies to both getting and setting |
| 18 |
an attribute. New attributes are defined by assignments in the class |
| 19 |
body, or assignments to ``self.x`` in methods. These assignments don't |
| 20 |
generate ``attr-defined`` errors. |
| 21 |
|
| 22 |
Example: |
| 23 |
|
| 24 |
.. code-block:: python |
| 25 |
|
| 26 |
class Resource: |
| 27 |
def __init__(self, name: str) -> None: |
| 28 |
self.name = name |
| 29 |
|
| 30 |
r = Resource('x') |
| 31 |
print(r.name) # OK |
| 32 |
print(r.id) # Error: "Resource" has no attribute "id" [attr-defined] |
| 33 |
r.id = 5 # Error: "Resource" has no attribute "id" [attr-defined] |
| 34 |
|
| 35 |
This error code is also generated if an imported name is not defined |
| 36 |
in the module in a ``from ... import`` statement (as long as the |
| 37 |
target module can be found): |
| 38 |
|
| 39 |
.. code-block:: python |
| 40 |
|
| 41 |
# Error: Module "os" has no attribute "non_existent" [attr-defined] |
| 42 |
from os import non_existent |
| 43 |
|
| 44 |
A reference to a missing attribute is given the ``Any`` type. In the |
| 45 |
above example, the type of ``non_existent`` will be ``Any``, which can |
| 46 |
be important if you silence the error. |
| 47 |
|
| 48 |
.. _code-union-attr: |
| 49 |
|
| 50 |
Check that attribute exists in each union item [union-attr] |
| 51 |
----------------------------------------------------------- |
| 52 |
|
| 53 |
If you access the attribute of a value with a union type, mypy checks |
| 54 |
that the attribute is defined for *every* type in that |
| 55 |
union. Otherwise the operation can fail at runtime. This also applies |
| 56 |
to optional types. |
| 57 |
|
| 58 |
Example: |
| 59 |
|
| 60 |
.. code-block:: python |
| 61 |
|
| 62 |
class Cat: |
| 63 |
def sleep(self) -> None: ... |
| 64 |
def miaow(self) -> None: ... |
| 65 |
|
| 66 |
class Dog: |
| 67 |
def sleep(self) -> None: ... |
| 68 |
def follow_me(self) -> None: ... |
| 69 |
|
| 70 |
def func(animal: Cat | Dog) -> None: |
| 71 |
# OK: 'sleep' is defined for both Cat and Dog |
| 72 |
animal.sleep() |
| 73 |
# Error: Item "Cat" of "Cat | Dog" has no attribute "follow_me" [union-attr] |
| 74 |
animal.follow_me() |
| 75 |
|
| 76 |
You can often work around these errors by using ``assert isinstance(obj, ClassName)`` |
| 77 |
or ``assert obj is not None`` to tell mypy that you know that the type is more specific |
| 78 |
than what mypy thinks. |
| 79 |
|
| 80 |
.. _code-name-defined: |
| 81 |
|
| 82 |
Check that name is defined [name-defined] |
| 83 |
----------------------------------------- |
| 84 |
|
| 85 |
Mypy expects that all references to names have a corresponding |
| 86 |
definition in an active scope, such as an assignment, function |
| 87 |
definition or an import. This can catch missing definitions, missing |
| 88 |
imports, and typos. |
| 89 |
|
| 90 |
This example accidentally calls ``sort()`` instead of :py:func:`sorted`: |
| 91 |
|
| 92 |
.. code-block:: python |
| 93 |
|
| 94 |
x = sort([3, 2, 4]) # Error: Name "sort" is not defined [name-defined] |
| 95 |
|
| 96 |
.. _code-used-before-def: |
| 97 |
|
| 98 |
Check that a variable is not used before it's defined [used-before-def] |
| 99 |
----------------------------------------------------------------------- |
| 100 |
|
| 101 |
Mypy will generate an error if a name is used before it's defined. |
| 102 |
While the name-defined check will catch issues with names that are undefined, |
| 103 |
it will not flag if a variable is used and then defined later in the scope. |
| 104 |
used-before-def check will catch such cases. |
| 105 |
|
| 106 |
Example: |
| 107 |
|
| 108 |
.. code-block:: python |
| 109 |
|
| 110 |
print(x) # Error: Name "x" is used before definition [used-before-def] |
| 111 |
x = 123 |
| 112 |
|
| 113 |
.. _code-call-arg: |
| 114 |
|
| 115 |
Check arguments in calls [call-arg] |
| 116 |
----------------------------------- |
| 117 |
|
| 118 |
Mypy expects that the number and names of arguments match the called function. |
| 119 |
Note that argument type checks have a separate error code ``arg-type``. |
| 120 |
|
| 121 |
Example: |
| 122 |
|
| 123 |
.. code-block:: python |
| 124 |
|
| 125 |
def greet(name: str) -> None: |
| 126 |
print('hello', name) |
| 127 |
|
| 128 |
greet('jack') # OK |
| 129 |
greet('jill', 'jack') # Error: Too many arguments for "greet" [call-arg] |
| 130 |
|
| 131 |
.. _code-arg-type: |
| 132 |
|
| 133 |
Check argument types [arg-type] |
| 134 |
------------------------------- |
| 135 |
|
| 136 |
Mypy checks that argument types in a call match the declared argument |
| 137 |
types in the signature of the called function (if one exists). |
| 138 |
|
| 139 |
Example: |
| 140 |
|
| 141 |
.. code-block:: python |
| 142 |
|
| 143 |
def first(x: list[int]) -> int: |
| 144 |
return x[0] if x else 0 |
| 145 |
|
| 146 |
t = (5, 4) |
| 147 |
# Error: Argument 1 to "first" has incompatible type "tuple[int, int]"; |
| 148 |
# expected "list[int]" [arg-type] |
| 149 |
print(first(t)) |
| 150 |
|
| 151 |
.. _code-call-overload: |
| 152 |
|
| 153 |
Check calls to overloaded functions [call-overload] |
| 154 |
--------------------------------------------------- |
| 155 |
|
| 156 |
When you call an overloaded function, mypy checks that at least one of |
| 157 |
the signatures of the overload items match the argument types in the |
| 158 |
call. |
| 159 |
|
| 160 |
Example: |
| 161 |
|
| 162 |
.. code-block:: python |
| 163 |
|
| 164 |
from typing import overload |
| 165 |
|
| 166 |
@overload |
| 167 |
def inc_maybe(x: None) -> None: ... |
| 168 |
|
| 169 |
@overload |
| 170 |
def inc_maybe(x: int) -> int: ... |
| 171 |
|
| 172 |
def inc_maybe(x: int | None) -> int | None: |
| 173 |
if x is None: |
| 174 |
return None |
| 175 |
else: |
| 176 |
return x + 1 |
| 177 |
|
| 178 |
inc_maybe(None) # OK |
| 179 |
inc_maybe(5) # OK |
| 180 |
|
| 181 |
# Error: No overload variant of "inc_maybe" matches argument type "float" [call-overload] |
| 182 |
inc_maybe(1.2) |
| 183 |
|
| 184 |
.. _code-valid-type: |
| 185 |
|
| 186 |
Check validity of types [valid-type] |
| 187 |
------------------------------------ |
| 188 |
|
| 189 |
Mypy checks that each type annotation and any expression that |
| 190 |
represents a type is a valid type. Examples of valid types include |
| 191 |
classes, union types, callable types, type aliases, and literal types. |
| 192 |
Examples of invalid types include bare integer literals, functions, |
| 193 |
variables, and modules. |
| 194 |
|
| 195 |
This example incorrectly uses the function ``log`` as a type: |
| 196 |
|
| 197 |
.. code-block:: python |
| 198 |
|
| 199 |
def log(x: object) -> None: |
| 200 |
print('log:', repr(x)) |
| 201 |
|
| 202 |
# Error: Function "t.log" is not valid as a type [valid-type] |
| 203 |
def log_all(objs: list[object], f: log) -> None: |
| 204 |
for x in objs: |
| 205 |
f(x) |
| 206 |
|
| 207 |
You can use :py:class:`~collections.abc.Callable` as the type for callable objects: |
| 208 |
|
| 209 |
.. code-block:: python |
| 210 |
|
| 211 |
from collections.abc import Callable |
| 212 |
|
| 213 |
# OK |
| 214 |
def log_all(objs: list[object], f: Callable[[object], None]) -> None: |
| 215 |
for x in objs: |
| 216 |
f(x) |
| 217 |
|
| 218 |
.. _code-nonetype-type: |
| 219 |
|
| 220 |
Check that NoneType is not used as a type (annotation) [nonetype-type] |
| 221 |
---------------------------------------------------------------------- |
| 222 |
|
| 223 |
The preferred way to annotate the type of `None` is `None`. |
| 224 |
`NoneType` is equivalent, but mypy won't allow it by default. |
| 225 |
|
| 226 |
.. code-block:: python |
| 227 |
|
| 228 |
from types import NoneType |
| 229 |
def f(x: None) -> None: |
| 230 |
reveal_type(x) # note: Revealed type is "None" |
| 231 |
|
| 232 |
# error: NoneType should not be used as a type, please use None instead [nonetype-type] |
| 233 |
def g(x: NoneType) -> None: |
| 234 |
reveal_type(x) # note: Revealed type is "None" |
| 235 |
|
| 236 |
# error: NoneType should not be used as a type, please use None instead [nonetype-type] |
| 237 |
x1: NoneType = None |
| 238 |
x2: None = None # OK |
| 239 |
|
| 240 |
.. _code-metaclass: |
| 241 |
|
| 242 |
Check the validity of a class's metaclass [metaclass] |
| 243 |
----------------------------------------------------- |
| 244 |
|
| 245 |
Mypy checks whether the metaclass of a class is valid. The metaclass |
| 246 |
must be a subclass of ``type``. Further, the class hierarchy must yield |
| 247 |
a consistent metaclass. For more details, see the |
| 248 |
`Python documentation <https://docs.python.org/3.13/reference/datamodel.html#determining-the-appropriate-metaclass>`_ |
| 249 |
|
| 250 |
Note that mypy's metaclass checking is limited and may produce false-positives. |
| 251 |
See also :ref:`limitations`. |
| 252 |
|
| 253 |
Example with an error: |
| 254 |
|
| 255 |
.. code-block:: python |
| 256 |
|
| 257 |
class GoodMeta(type): |
| 258 |
pass |
| 259 |
|
| 260 |
class BadMeta: |
| 261 |
pass |
| 262 |
|
| 263 |
class A1(metaclass=GoodMeta): # OK |
| 264 |
pass |
| 265 |
|
| 266 |
class A2(metaclass=BadMeta): # Error: Metaclasses not inheriting from "type" are not supported [metaclass] |
| 267 |
pass |
| 268 |
|
| 269 |
.. _code-var-annotated: |
| 270 |
|
| 271 |
Require annotation if variable type is unclear [var-annotated] |
| 272 |
-------------------------------------------------------------- |
| 273 |
|
| 274 |
In some cases mypy can't infer the type of a variable without an |
| 275 |
explicit annotation. Mypy treats this as an error. This typically |
| 276 |
happens when you initialize a variable with an empty collection or |
| 277 |
``None``. If mypy can't infer the collection item type, mypy replaces |
| 278 |
any parts of the type it couldn't infer with ``Any`` and generates an |
| 279 |
error. |
| 280 |
|
| 281 |
Example with an error: |
| 282 |
|
| 283 |
.. code-block:: python |
| 284 |
|
| 285 |
class Bundle: |
| 286 |
def __init__(self) -> None: |
| 287 |
# Error: Need type annotation for "items" |
| 288 |
# (hint: "items: list[<type>] = ...") [var-annotated] |
| 289 |
self.items = [] |
| 290 |
|
| 291 |
reveal_type(Bundle().items) # list[Any] |
| 292 |
|
| 293 |
To address this, we add an explicit annotation: |
| 294 |
|
| 295 |
.. code-block:: python |
| 296 |
|
| 297 |
class Bundle: |
| 298 |
def __init__(self) -> None: |
| 299 |
self.items: list[str] = [] # OK |
| 300 |
|
| 301 |
reveal_type(Bundle().items) # list[str] |
| 302 |
|
| 303 |
.. _code-override: |
| 304 |
|
| 305 |
Check validity of overrides [override] |
| 306 |
-------------------------------------- |
| 307 |
|
| 308 |
Mypy checks that an overridden method or attribute is compatible with |
| 309 |
the base class. A method in a subclass must accept all arguments |
| 310 |
that the base class method accepts, and the return type must conform |
| 311 |
to the return type in the base class (Liskov substitution principle). |
| 312 |
|
| 313 |
Argument types can be more general is a subclass (i.e., they can vary |
| 314 |
contravariantly). The return type can be narrowed in a subclass |
| 315 |
(i.e., it can vary covariantly). It's okay to define additional |
| 316 |
arguments in a subclass method, as long all extra arguments have default |
| 317 |
values or can be left out (``*args``, for example). |
| 318 |
|
| 319 |
Example: |
| 320 |
|
| 321 |
.. code-block:: python |
| 322 |
|
| 323 |
class Base: |
| 324 |
def method(self, |
| 325 |
arg: int) -> int | None: |
| 326 |
... |
| 327 |
|
| 328 |
class Derived(Base): |
| 329 |
def method(self, |
| 330 |
arg: int | str) -> int: # OK |
| 331 |
... |
| 332 |
|
| 333 |
class DerivedBad(Base): |
| 334 |
# Error: Argument 1 of "method" is incompatible with "Base" [override] |
| 335 |
def method(self, |
| 336 |
arg: bool) -> int: |
| 337 |
... |
| 338 |
|
| 339 |
.. _code-return: |
| 340 |
|
| 341 |
Check that function returns a value [return] |
| 342 |
-------------------------------------------- |
| 343 |
|
| 344 |
If a function has a non-``None`` return type, mypy expects that the |
| 345 |
function always explicitly returns a value (or raises an exception). |
| 346 |
The function should not fall off the end of the function, since this |
| 347 |
is often a bug. |
| 348 |
|
| 349 |
Example: |
| 350 |
|
| 351 |
.. code-block:: python |
| 352 |
|
| 353 |
# Error: Missing return statement [return] |
| 354 |
def show(x: int) -> int: |
| 355 |
print(x) |
| 356 |
|
| 357 |
# Error: Missing return statement [return] |
| 358 |
def pred1(x: int) -> int: |
| 359 |
if x > 0: |
| 360 |
return x - 1 |
| 361 |
|
| 362 |
# OK |
| 363 |
def pred2(x: int) -> int: |
| 364 |
if x > 0: |
| 365 |
return x - 1 |
| 366 |
else: |
| 367 |
raise ValueError('not defined for zero') |
| 368 |
|
| 369 |
.. _code-empty-body: |
| 370 |
|
| 371 |
Check that functions don't have empty bodies outside stubs [empty-body] |
| 372 |
----------------------------------------------------------------------- |
| 373 |
|
| 374 |
This error code is similar to the ``[return]`` code but is emitted specifically |
| 375 |
for functions and methods with empty bodies (if they are annotated with |
| 376 |
non-trivial return type). Such a distinction exists because in some contexts |
| 377 |
an empty body can be valid, for example for an abstract method or in a stub |
| 378 |
file. Also old versions of mypy used to unconditionally allow functions with |
| 379 |
empty bodies, so having a dedicated error code simplifies cross-version |
| 380 |
compatibility. |
| 381 |
|
| 382 |
Note that empty bodies are allowed for methods in *protocols*, and such methods |
| 383 |
are considered implicitly abstract: |
| 384 |
|
| 385 |
.. code-block:: python |
| 386 |
|
| 387 |
from abc import abstractmethod |
| 388 |
from typing import Protocol |
| 389 |
|
| 390 |
class RegularABC: |
| 391 |
@abstractmethod |
| 392 |
def foo(self) -> int: |
| 393 |
pass # OK |
| 394 |
def bar(self) -> int: |
| 395 |
pass # Error: Missing return statement [empty-body] |
| 396 |
|
| 397 |
class Proto(Protocol): |
| 398 |
def bar(self) -> int: |
| 399 |
pass # OK |
| 400 |
|
| 401 |
.. _code-return-value: |
| 402 |
|
| 403 |
Check that return value is compatible [return-value] |
| 404 |
---------------------------------------------------- |
| 405 |
|
| 406 |
Mypy checks that the returned value is compatible with the type |
| 407 |
signature of the function. |
| 408 |
|
| 409 |
Example: |
| 410 |
|
| 411 |
.. code-block:: python |
| 412 |
|
| 413 |
def func(x: int) -> str: |
| 414 |
# Error: Incompatible return value type (got "int", expected "str") [return-value] |
| 415 |
return x + 1 |
| 416 |
|
| 417 |
.. _code-assignment: |
| 418 |
|
| 419 |
Check types in assignment statement [assignment] |
| 420 |
------------------------------------------------ |
| 421 |
|
| 422 |
Mypy checks that the assigned expression is compatible with the |
| 423 |
assignment target (or targets). |
| 424 |
|
| 425 |
Example: |
| 426 |
|
| 427 |
.. code-block:: python |
| 428 |
|
| 429 |
class Resource: |
| 430 |
def __init__(self, name: str) -> None: |
| 431 |
self.name = name |
| 432 |
|
| 433 |
r = Resource('A') |
| 434 |
|
| 435 |
r.name = 'B' # OK |
| 436 |
|
| 437 |
# Error: Incompatible types in assignment (expression has type "int", |
| 438 |
# variable has type "str") [assignment] |
| 439 |
r.name = 5 |
| 440 |
|
| 441 |
.. _code-method-assign: |
| 442 |
|
| 443 |
Check that assignment target is not a method [method-assign] |
| 444 |
------------------------------------------------------------ |
| 445 |
|
| 446 |
In general, assigning to a method on class object or instance (a.k.a. |
| 447 |
monkey-patching) is ambiguous in terms of types, since Python's static type |
| 448 |
system cannot express the difference between bound and unbound callable types. |
| 449 |
Consider this example: |
| 450 |
|
| 451 |
.. code-block:: python |
| 452 |
|
| 453 |
class A: |
| 454 |
def f(self) -> None: pass |
| 455 |
def g(self) -> None: pass |
| 456 |
|
| 457 |
def h(self: A) -> None: pass |
| 458 |
|
| 459 |
A.f = h # Type of h is Callable[[A], None] |
| 460 |
A().f() # This works |
| 461 |
A.f = A().g # Type of A().g is Callable[[], None] |
| 462 |
A().f() # ...but this also works at runtime |
| 463 |
|
| 464 |
To prevent the ambiguity, mypy will flag both assignments by default. If this |
| 465 |
error code is disabled, mypy will treat the assigned value in all method assignments as unbound, |
| 466 |
so only the second assignment will still generate an error. |
| 467 |
|
| 468 |
.. note:: |
| 469 |
|
| 470 |
This error code is a subcode of the more general ``[assignment]`` code. |
| 471 |
|
| 472 |
.. _code-type-var: |
| 473 |
|
| 474 |
Check type variable values [type-var] |
| 475 |
------------------------------------- |
| 476 |
|
| 477 |
Mypy checks that value of a type variable is compatible with a value |
| 478 |
restriction or the upper bound type. |
| 479 |
|
| 480 |
Example (Python 3.12 syntax): |
| 481 |
|
| 482 |
.. code-block:: python |
| 483 |
|
| 484 |
def add[T1: (int, float)](x: T1, y: T1) -> T1: |
| 485 |
return x + y |
| 486 |
|
| 487 |
add(4, 5.5) # OK |
| 488 |
|
| 489 |
# Error: Value of type variable "T1" of "add" cannot be "str" [type-var] |
| 490 |
add('x', 'y') |
| 491 |
|
| 492 |
.. _code-operator: |
| 493 |
|
| 494 |
Check uses of various operators [operator] |
| 495 |
------------------------------------------ |
| 496 |
|
| 497 |
Mypy checks that operands support a binary or unary operation, such as |
| 498 |
``+`` or ``~``. Indexing operations are so common that they have their |
| 499 |
own error code ``index`` (see below). |
| 500 |
|
| 501 |
Example: |
| 502 |
|
| 503 |
.. code-block:: python |
| 504 |
|
| 505 |
# Error: Unsupported operand types for + ("int" and "str") [operator] |
| 506 |
1 + 'x' |
| 507 |
|
| 508 |
.. _code-index: |
| 509 |
|
| 510 |
Check indexing operations [index] |
| 511 |
--------------------------------- |
| 512 |
|
| 513 |
Mypy checks that the indexed value in indexing operation such as |
| 514 |
``x[y]`` supports indexing, and that the index expression has a valid |
| 515 |
type. |
| 516 |
|
| 517 |
Example: |
| 518 |
|
| 519 |
.. code-block:: python |
| 520 |
|
| 521 |
a = {'x': 1, 'y': 2} |
| 522 |
|
| 523 |
a['x'] # OK |
| 524 |
|
| 525 |
# Error: Invalid index type "int" for "dict[str, int]"; expected type "str" [index] |
| 526 |
print(a[1]) |
| 527 |
|
| 528 |
# Error: Invalid index type "bytes" for "dict[str, int]"; expected type "str" [index] |
| 529 |
a[b'x'] = 4 |
| 530 |
|
| 531 |
.. _code-list-item: |
| 532 |
|
| 533 |
Check list items [list-item] |
| 534 |
---------------------------- |
| 535 |
|
| 536 |
When constructing a list using ``[item, ...]``, mypy checks that each item |
| 537 |
is compatible with the list type that is inferred from the surrounding |
| 538 |
context. |
| 539 |
|
| 540 |
Example: |
| 541 |
|
| 542 |
.. code-block:: python |
| 543 |
|
| 544 |
# Error: List item 0 has incompatible type "int"; expected "str" [list-item] |
| 545 |
a: list[str] = [0] |
| 546 |
|
| 547 |
.. _code-dict-item: |
| 548 |
|
| 549 |
Check dict items [dict-item] |
| 550 |
---------------------------- |
| 551 |
|
| 552 |
When constructing a dictionary using ``{key: value, ...}`` or ``dict(key=value, ...)``, |
| 553 |
mypy checks that each key and value is compatible with the dictionary type that is |
| 554 |
inferred from the surrounding context. |
| 555 |
|
| 556 |
Example: |
| 557 |
|
| 558 |
.. code-block:: python |
| 559 |
|
| 560 |
# Error: Dict entry 0 has incompatible type "str": "str"; expected "str": "int" [dict-item] |
| 561 |
d: dict[str, int] = {'key': 'value'} |
| 562 |
|
| 563 |
.. _code-typeddict-item: |
| 564 |
|
| 565 |
Check TypedDict items [typeddict-item] |
| 566 |
-------------------------------------- |
| 567 |
|
| 568 |
When constructing a TypedDict object, mypy checks that each key and value is compatible |
| 569 |
with the TypedDict type that is inferred from the surrounding context. |
| 570 |
|
| 571 |
When getting a TypedDict item, mypy checks that the key |
| 572 |
exists. When assigning to a TypedDict, mypy checks that both the |
| 573 |
key and the value are valid. |
| 574 |
|
| 575 |
Example: |
| 576 |
|
| 577 |
.. code-block:: python |
| 578 |
|
| 579 |
from typing import TypedDict |
| 580 |
|
| 581 |
class Point(TypedDict): |
| 582 |
x: int |
| 583 |
y: int |
| 584 |
|
| 585 |
# Error: Incompatible types (expression has type "float", |
| 586 |
# TypedDict item "x" has type "int") [typeddict-item] |
| 587 |
p: Point = {'x': 1.2, 'y': 4} |
| 588 |
|
| 589 |
.. _code-typeddict-unknown-key: |
| 590 |
|
| 591 |
Check TypedDict Keys [typeddict-unknown-key] |
| 592 |
-------------------------------------------- |
| 593 |
|
| 594 |
When constructing a TypedDict object, mypy checks whether the |
| 595 |
definition contains unknown keys, to catch invalid keys and |
| 596 |
misspellings. On the other hand, mypy will not generate an error when |
| 597 |
a previously constructed TypedDict value with extra keys is passed |
| 598 |
to a function as an argument, since TypedDict values support |
| 599 |
structural subtyping ("static duck typing") and the keys are assumed |
| 600 |
to have been validated at the point of construction. Example: |
| 601 |
|
| 602 |
.. code-block:: python |
| 603 |
|
| 604 |
from typing import TypedDict |
| 605 |
|
| 606 |
class Point(TypedDict): |
| 607 |
x: int |
| 608 |
y: int |
| 609 |
|
| 610 |
class Point3D(Point): |
| 611 |
z: int |
| 612 |
|
| 613 |
def add_x_coordinates(a: Point, b: Point) -> int: |
| 614 |
return a["x"] + b["x"] |
| 615 |
|
| 616 |
a: Point = {"x": 1, "y": 4} |
| 617 |
b: Point3D = {"x": 2, "y": 5, "z": 6} |
| 618 |
|
| 619 |
add_x_coordinates(a, b) # OK |
| 620 |
|
| 621 |
# Error: Extra key "z" for TypedDict "Point" [typeddict-unknown-key] |
| 622 |
add_x_coordinates(a, {"x": 1, "y": 4, "z": 5}) |
| 623 |
|
| 624 |
Setting a TypedDict item using an unknown key will also generate this |
| 625 |
error, since it could be a misspelling: |
| 626 |
|
| 627 |
.. code-block:: python |
| 628 |
|
| 629 |
a: Point = {"x": 1, "y": 2} |
| 630 |
# Error: Extra key "z" for TypedDict "Point" [typeddict-unknown-key] |
| 631 |
a["z"] = 3 |
| 632 |
|
| 633 |
Reading an unknown key will generate the more general (and serious) |
| 634 |
``typeddict-item`` error, which is likely to result in an exception at |
| 635 |
runtime: |
| 636 |
|
| 637 |
.. code-block:: python |
| 638 |
|
| 639 |
a: Point = {"x": 1, "y": 2} |
| 640 |
# Error: TypedDict "Point" has no key "z" [typeddict-item] |
| 641 |
_ = a["z"] |
| 642 |
|
| 643 |
.. note:: |
| 644 |
|
| 645 |
This error code is a subcode of the wider ``[typeddict-item]`` code. |
| 646 |
|
| 647 |
.. _code-has-type: |
| 648 |
|
| 649 |
Check that type of target is known [has-type] |
| 650 |
--------------------------------------------- |
| 651 |
|
| 652 |
Mypy sometimes generates an error when it hasn't inferred any type for |
| 653 |
a variable being referenced. This can happen for references to |
| 654 |
variables that are initialized later in the source file, and for |
| 655 |
references across modules that form an import cycle. When this |
| 656 |
happens, the reference gets an implicit ``Any`` type. |
| 657 |
|
| 658 |
In this example the definitions of ``x`` and ``y`` are circular: |
| 659 |
|
| 660 |
.. code-block:: python |
| 661 |
|
| 662 |
class Problem: |
| 663 |
def set_x(self) -> None: |
| 664 |
# Error: Cannot determine type of "y" [has-type] |
| 665 |
self.x = self.y |
| 666 |
|
| 667 |
def set_y(self) -> None: |
| 668 |
self.y = self.x |
| 669 |
|
| 670 |
To work around this error, you can add an explicit type annotation to |
| 671 |
the target variable or attribute. Sometimes you can also reorganize |
| 672 |
the code so that the definition of the variable is placed earlier than |
| 673 |
the reference to the variable in a source file. Untangling cyclic |
| 674 |
imports may also help. |
| 675 |
|
| 676 |
We add an explicit annotation to the ``y`` attribute to work around |
| 677 |
the issue: |
| 678 |
|
| 679 |
.. code-block:: python |
| 680 |
|
| 681 |
class Problem: |
| 682 |
def set_x(self) -> None: |
| 683 |
self.x = self.y # OK |
| 684 |
|
| 685 |
def set_y(self) -> None: |
| 686 |
self.y: int = self.x # Added annotation here |
| 687 |
|
| 688 |
.. _code-import: |
| 689 |
|
| 690 |
Check for an issue with imports [import] |
| 691 |
---------------------------------------- |
| 692 |
|
| 693 |
Mypy generates an error if it can't resolve an `import` statement. |
| 694 |
This is a parent error code of `import-not-found` and `import-untyped` |
| 695 |
|
| 696 |
See :ref:`ignore-missing-imports` for how to work around these errors. |
| 697 |
|
| 698 |
.. _code-import-not-found: |
| 699 |
|
| 700 |
Check that import target can be found [import-not-found] |
| 701 |
-------------------------------------------------------- |
| 702 |
|
| 703 |
Mypy generates an error if it can't find the source code or a stub file |
| 704 |
for an imported module. |
| 705 |
|
| 706 |
Example: |
| 707 |
|
| 708 |
.. code-block:: python |
| 709 |
|
| 710 |
# Error: Cannot find implementation or library stub for module named "m0dule_with_typo" [import-not-found] |
| 711 |
import m0dule_with_typo |
| 712 |
|
| 713 |
See :ref:`ignore-missing-imports` for how to work around these errors. |
| 714 |
|
| 715 |
.. _code-import-untyped: |
| 716 |
|
| 717 |
Check that import target can be found [import-untyped] |
| 718 |
-------------------------------------------------------- |
| 719 |
|
| 720 |
Mypy generates an error if it can find the source code for an imported module, |
| 721 |
but that module does not provide type annotations (via :ref:`PEP 561 <installed-packages>`). |
| 722 |
|
| 723 |
Example: |
| 724 |
|
| 725 |
.. code-block:: python |
| 726 |
|
| 727 |
# Error: Library stubs not installed for "bs4" [import-untyped] |
| 728 |
import bs4 |
| 729 |
# Error: Skipping analyzing "no_py_typed": module is installed, but missing library stubs or py.typed marker [import-untyped] |
| 730 |
import no_py_typed |
| 731 |
|
| 732 |
In some cases, these errors can be fixed by installing an appropriate |
| 733 |
stub package. See :ref:`ignore-missing-imports` for more details. |
| 734 |
|
| 735 |
.. _code-no-redef: |
| 736 |
|
| 737 |
Check that each name is defined once [no-redef] |
| 738 |
----------------------------------------------- |
| 739 |
|
| 740 |
Mypy may generate an error if you have multiple definitions for a name |
| 741 |
in the same namespace. The reason is that this is often an error, as |
| 742 |
the second definition may overwrite the first one. Also, mypy often |
| 743 |
can't be able to determine whether references point to the first or |
| 744 |
the second definition, which would compromise type checking. |
| 745 |
|
| 746 |
If you silence this error, all references to the defined name refer to |
| 747 |
the *first* definition. |
| 748 |
|
| 749 |
Example: |
| 750 |
|
| 751 |
.. code-block:: python |
| 752 |
|
| 753 |
class A: |
| 754 |
def __init__(self, x: int) -> None: ... |
| 755 |
|
| 756 |
class A: # Error: Name "A" already defined on line 1 [no-redef] |
| 757 |
def __init__(self, x: str) -> None: ... |
| 758 |
|
| 759 |
# Error: Argument 1 to "A" has incompatible type "str"; expected "int" |
| 760 |
# (the first definition wins!) |
| 761 |
A('x') |
| 762 |
|
| 763 |
.. _code-func-returns-value: |
| 764 |
|
| 765 |
Check that called function returns a value [func-returns-value] |
| 766 |
--------------------------------------------------------------- |
| 767 |
|
| 768 |
Mypy reports an error if you call a function with a ``None`` |
| 769 |
return type and don't ignore the return value, as this is |
| 770 |
usually (but not always) a programming error. |
| 771 |
|
| 772 |
In this example, the ``if f()`` check is always false since ``f`` |
| 773 |
returns ``None``: |
| 774 |
|
| 775 |
.. code-block:: python |
| 776 |
|
| 777 |
def f() -> None: |
| 778 |
... |
| 779 |
|
| 780 |
# OK: we don't do anything with the return value |
| 781 |
f() |
| 782 |
|
| 783 |
# Error: "f" does not return a value (it only ever returns None) [func-returns-value] |
| 784 |
if f(): |
| 785 |
print("not false") |
| 786 |
|
| 787 |
.. _code-abstract: |
| 788 |
|
| 789 |
Check instantiation of abstract classes [abstract] |
| 790 |
-------------------------------------------------- |
| 791 |
|
| 792 |
Mypy generates an error if you try to instantiate an abstract base |
| 793 |
class (ABC). An abstract base class is a class with at least one |
| 794 |
abstract method or attribute. (See also :py:mod:`abc` module documentation) |
| 795 |
|
| 796 |
Sometimes a class is made accidentally abstract, often due to an |
| 797 |
unimplemented abstract method. In a case like this you need to provide |
| 798 |
an implementation for the method to make the class concrete |
| 799 |
(non-abstract). |
| 800 |
|
| 801 |
Example: |
| 802 |
|
| 803 |
.. code-block:: python |
| 804 |
|
| 805 |
from abc import ABCMeta, abstractmethod |
| 806 |
|
| 807 |
class Persistent(metaclass=ABCMeta): |
| 808 |
@abstractmethod |
| 809 |
def save(self) -> None: ... |
| 810 |
|
| 811 |
class Thing(Persistent): |
| 812 |
def __init__(self) -> None: |
| 813 |
... |
| 814 |
|
| 815 |
... # No "save" method |
| 816 |
|
| 817 |
# Error: Cannot instantiate abstract class "Thing" with abstract attribute "save" [abstract] |
| 818 |
t = Thing() |
| 819 |
|
| 820 |
.. _code-type-abstract: |
| 821 |
|
| 822 |
Safe handling of abstract type object types [type-abstract] |
| 823 |
----------------------------------------------------------- |
| 824 |
|
| 825 |
Mypy always allows instantiating (calling) type objects typed as ``type[t]``, |
| 826 |
even if it is not known that ``t`` is non-abstract, since it is a common |
| 827 |
pattern to create functions that act as object factories (custom constructors). |
| 828 |
Therefore, to prevent issues described in the above section, when an abstract |
| 829 |
type object is passed where ``type[t]`` is expected, mypy will give an error. |
| 830 |
Example (Python 3.12 syntax): |
| 831 |
|
| 832 |
.. code-block:: python |
| 833 |
|
| 834 |
from abc import ABCMeta, abstractmethod |
| 835 |
|
| 836 |
class Config(metaclass=ABCMeta): |
| 837 |
@abstractmethod |
| 838 |
def get_value(self, attr: str) -> str: ... |
| 839 |
|
| 840 |
def make_many[T](typ: type[T], n: int) -> list[T]: |
| 841 |
return [typ() for _ in range(n)] # This will raise if typ is abstract |
| 842 |
|
| 843 |
# Error: Only concrete class can be given where "type[Config]" is expected [type-abstract] |
| 844 |
make_many(Config, 5) |
| 845 |
|
| 846 |
.. _code-safe-super: |
| 847 |
|
| 848 |
Check that call to an abstract method via super is valid [safe-super] |
| 849 |
--------------------------------------------------------------------- |
| 850 |
|
| 851 |
Abstract methods often don't have any default implementation, i.e. their |
| 852 |
bodies are just empty. Calling such methods in subclasses via ``super()`` |
| 853 |
will cause runtime errors, so mypy prevents you from doing so: |
| 854 |
|
| 855 |
.. code-block:: python |
| 856 |
|
| 857 |
from abc import abstractmethod |
| 858 |
class Base: |
| 859 |
@abstractmethod |
| 860 |
def foo(self) -> int: ... |
| 861 |
class Sub(Base): |
| 862 |
def foo(self) -> int: |
| 863 |
return super().foo() + 1 # error: Call to abstract method "foo" of "Base" with |
| 864 |
# trivial body via super() is unsafe [safe-super] |
| 865 |
Sub().foo() # This will crash at runtime. |
| 866 |
|
| 867 |
Mypy considers the following as trivial bodies: a ``pass`` statement, a literal |
| 868 |
ellipsis ``...``, a docstring, and a ``raise NotImplementedError`` statement. |
| 869 |
|
| 870 |
.. _code-valid-newtype: |
| 871 |
|
| 872 |
Check the target of NewType [valid-newtype] |
| 873 |
------------------------------------------- |
| 874 |
|
| 875 |
The target of a :py:class:`~typing.NewType` definition must be a class type. It can't |
| 876 |
be a union type, ``Any``, or various other special types. |
| 877 |
|
| 878 |
You can also get this error if the target has been imported from a |
| 879 |
module whose source mypy cannot find, since any such definitions are |
| 880 |
treated by mypy as values with ``Any`` types. Example: |
| 881 |
|
| 882 |
.. code-block:: python |
| 883 |
|
| 884 |
from typing import NewType |
| 885 |
|
| 886 |
# The source for "acme" is not available for mypy |
| 887 |
from acme import Entity # type: ignore |
| 888 |
|
| 889 |
# Error: Argument 2 to NewType(...) must be subclassable (got "Any") [valid-newtype] |
| 890 |
UserEntity = NewType('UserEntity', Entity) |
| 891 |
|
| 892 |
To work around the issue, you can either give mypy access to the sources |
| 893 |
for ``acme`` or create a stub file for the module. See :ref:`ignore-missing-imports` |
| 894 |
for more information. |
| 895 |
|
| 896 |
.. _code-exit-return: |
| 897 |
|
| 898 |
Check the return type of __exit__ [exit-return] |
| 899 |
----------------------------------------------- |
| 900 |
|
| 901 |
If mypy can determine that :py:meth:`__exit__ <object.__exit__>` always returns ``False``, mypy |
| 902 |
checks that the return type is *not* ``bool``. The boolean value of |
| 903 |
the return type affects which lines mypy thinks are reachable after a |
| 904 |
``with`` statement, since any :py:meth:`__exit__ <object.__exit__>` method that can return |
| 905 |
``True`` may swallow exceptions. An imprecise return type can result |
| 906 |
in mysterious errors reported near ``with`` statements. |
| 907 |
|
| 908 |
To fix this, use either ``typing.Literal[False]`` or |
| 909 |
``None`` as the return type. Returning ``None`` is equivalent to |
| 910 |
returning ``False`` in this context, since both are treated as false |
| 911 |
values. |
| 912 |
|
| 913 |
Example: |
| 914 |
|
| 915 |
.. code-block:: python |
| 916 |
|
| 917 |
class MyContext: |
| 918 |
... |
| 919 |
def __exit__(self, exc, value, tb) -> bool: # Error |
| 920 |
print('exit') |
| 921 |
return False |
| 922 |
|
| 923 |
This produces the following output from mypy: |
| 924 |
|
| 925 |
.. code-block:: text |
| 926 |
|
| 927 |
example.py:3: error: "bool" is invalid as return type for "__exit__" that always returns False |
| 928 |
example.py:3: note: Use "typing_extensions.Literal[False]" as the return type or change it to |
| 929 |
"None" |
| 930 |
example.py:3: note: If return type of "__exit__" implies that it may return True, the context |
| 931 |
manager may swallow exceptions |
| 932 |
|
| 933 |
You can use ``Literal[False]`` to fix the error: |
| 934 |
|
| 935 |
.. code-block:: python |
| 936 |
|
| 937 |
from typing import Literal |
| 938 |
|
| 939 |
class MyContext: |
| 940 |
... |
| 941 |
def __exit__(self, exc, value, tb) -> Literal[False]: # OK |
| 942 |
print('exit') |
| 943 |
return False |
| 944 |
|
| 945 |
You can also use ``None``: |
| 946 |
|
| 947 |
.. code-block:: python |
| 948 |
|
| 949 |
class MyContext: |
| 950 |
... |
| 951 |
def __exit__(self, exc, value, tb) -> None: # Also OK |
| 952 |
print('exit') |
| 953 |
|
| 954 |
.. _code-name-match: |
| 955 |
|
| 956 |
Check that naming is consistent [name-match] |
| 957 |
-------------------------------------------- |
| 958 |
|
| 959 |
The definition of a named tuple or a TypedDict must be named |
| 960 |
consistently when using the call-based syntax. Example: |
| 961 |
|
| 962 |
.. code-block:: python |
| 963 |
|
| 964 |
from typing import NamedTuple |
| 965 |
|
| 966 |
# Error: First argument to namedtuple() should be "Point2D", not "Point" |
| 967 |
Point2D = NamedTuple("Point", [("x", int), ("y", int)]) |
| 968 |
|
| 969 |
.. _code-literal-required: |
| 970 |
|
| 971 |
Check that literal is used where expected [literal-required] |
| 972 |
------------------------------------------------------------ |
| 973 |
|
| 974 |
There are some places where only a (string) literal value is expected for |
| 975 |
the purposes of static type checking, for example a ``TypedDict`` key, or |
| 976 |
a ``__match_args__`` item. Providing a ``str``-valued variable in such contexts |
| 977 |
will result in an error. Note that in many cases you can also use ``Final`` |
| 978 |
or ``Literal`` variables. Example: |
| 979 |
|
| 980 |
.. code-block:: python |
| 981 |
|
| 982 |
from typing import Final, Literal, TypedDict |
| 983 |
|
| 984 |
class Point(TypedDict): |
| 985 |
x: int |
| 986 |
y: int |
| 987 |
|
| 988 |
def test(p: Point) -> None: |
| 989 |
X: Final = "x" |
| 990 |
p[X] # OK |
| 991 |
|
| 992 |
Y: Literal["y"] = "y" |
| 993 |
p[Y] # OK |
| 994 |
|
| 995 |
key = "x" # Inferred type of key is `str` |
| 996 |
# Error: TypedDict key must be a string literal; |
| 997 |
# expected one of ("x", "y") [literal-required] |
| 998 |
p[key] |
| 999 |
|
| 1000 |
.. _code-no-overload-impl: |
| 1001 |
|
| 1002 |
Check that overloaded functions have an implementation [no-overload-impl] |
| 1003 |
------------------------------------------------------------------------- |
| 1004 |
|
| 1005 |
Overloaded functions outside of stub files must be followed by a non overloaded |
| 1006 |
implementation. |
| 1007 |
|
| 1008 |
.. code-block:: python |
| 1009 |
|
| 1010 |
from typing import overload |
| 1011 |
|
| 1012 |
@overload |
| 1013 |
def func(value: int) -> int: |
| 1014 |
... |
| 1015 |
|
| 1016 |
@overload |
| 1017 |
def func(value: str) -> str: |
| 1018 |
... |
| 1019 |
|
| 1020 |
# presence of required function below is checked |
| 1021 |
def func(value): |
| 1022 |
pass # actual implementation |
| 1023 |
|
| 1024 |
.. _code-unused-coroutine: |
| 1025 |
|
| 1026 |
Check that coroutine return value is used [unused-coroutine] |
| 1027 |
------------------------------------------------------------ |
| 1028 |
|
| 1029 |
Mypy ensures that return values of async def functions are not |
| 1030 |
ignored, as this is usually a programming error, as the coroutine |
| 1031 |
won't be executed at the call site. |
| 1032 |
|
| 1033 |
.. code-block:: python |
| 1034 |
|
| 1035 |
async def f() -> None: |
| 1036 |
... |
| 1037 |
|
| 1038 |
async def g() -> None: |
| 1039 |
f() # Error: missing await |
| 1040 |
await f() # OK |
| 1041 |
|
| 1042 |
You can work around this error by assigning the result to a temporary, |
| 1043 |
otherwise unused variable: |
| 1044 |
|
| 1045 |
.. code-block:: python |
| 1046 |
|
| 1047 |
_ = f() # No error |
| 1048 |
|
| 1049 |
.. _code-top-level-await: |
| 1050 |
|
| 1051 |
Warn about top level await expressions [top-level-await] |
| 1052 |
-------------------------------------------------------- |
| 1053 |
|
| 1054 |
This error code is separate from the general ``[syntax]`` errors, because in |
| 1055 |
some environments (e.g. IPython) a top level ``await`` is allowed. In such |
| 1056 |
environments a user may want to use ``--disable-error-code=top-level-await``, |
| 1057 |
which allows one to still have errors for other improper uses of ``await``, |
| 1058 |
for example: |
| 1059 |
|
| 1060 |
.. code-block:: python |
| 1061 |
|
| 1062 |
async def f() -> None: |
| 1063 |
... |
| 1064 |
|
| 1065 |
top = await f() # Error: "await" outside function [top-level-await] |
| 1066 |
|
| 1067 |
.. _code-await-not-async: |
| 1068 |
|
| 1069 |
Warn about await expressions used outside of coroutines [await-not-async] |
| 1070 |
------------------------------------------------------------------------- |
| 1071 |
|
| 1072 |
``await`` must be used inside a coroutine. |
| 1073 |
|
| 1074 |
.. code-block:: python |
| 1075 |
|
| 1076 |
async def f() -> None: |
| 1077 |
... |
| 1078 |
|
| 1079 |
def g() -> None: |
| 1080 |
await f() # Error: "await" outside coroutine ("async def") [await-not-async] |
| 1081 |
|
| 1082 |
.. _code-assert-type: |
| 1083 |
|
| 1084 |
Check types in assert_type [assert-type] |
| 1085 |
---------------------------------------- |
| 1086 |
|
| 1087 |
The inferred type for an expression passed to ``assert_type`` must match |
| 1088 |
the provided type. |
| 1089 |
|
| 1090 |
.. code-block:: python |
| 1091 |
|
| 1092 |
from typing_extensions import assert_type |
| 1093 |
|
| 1094 |
assert_type([1], list[int]) # OK |
| 1095 |
|
| 1096 |
assert_type([1], list[str]) # Error |
| 1097 |
|
| 1098 |
.. _code-truthy-function: |
| 1099 |
|
| 1100 |
Check that function isn't used in boolean context [truthy-function] |
| 1101 |
------------------------------------------------------------------- |
| 1102 |
|
| 1103 |
Functions will always evaluate to true in boolean contexts. |
| 1104 |
|
| 1105 |
.. code-block:: python |
| 1106 |
|
| 1107 |
def f(): |
| 1108 |
... |
| 1109 |
|
| 1110 |
if f: # Error: Function "Callable[[], Any]" could always be true in boolean context [truthy-function] |
| 1111 |
pass |
| 1112 |
|
| 1113 |
.. _code-str-format: |
| 1114 |
|
| 1115 |
Check that string formatting/interpolation is type-safe [str-format] |
| 1116 |
-------------------------------------------------------------------- |
| 1117 |
|
| 1118 |
Mypy will check that f-strings, ``str.format()`` calls, and ``%`` interpolations |
| 1119 |
are valid (when corresponding template is a literal string). This includes |
| 1120 |
checking number and types of replacements, for example: |
| 1121 |
|
| 1122 |
.. code-block:: python |
| 1123 |
|
| 1124 |
# Error: Cannot find replacement for positional format specifier 1 [str-format] |
| 1125 |
"{} and {}".format("spam") |
| 1126 |
"{} and {}".format("spam", "eggs") # OK |
| 1127 |
# Error: Not all arguments converted during string formatting [str-format] |
| 1128 |
"{} and {}".format("spam", "eggs", "cheese") |
| 1129 |
|
| 1130 |
# Error: Incompatible types in string interpolation |
| 1131 |
# (expression has type "float", placeholder has type "int") [str-format] |
| 1132 |
"{:d}".format(3.14) |
| 1133 |
|
| 1134 |
.. _code-str-bytes-safe: |
| 1135 |
|
| 1136 |
Check for implicit bytes coercions [str-bytes-safe] |
| 1137 |
------------------------------------------------------------------- |
| 1138 |
|
| 1139 |
Warn about cases where a bytes object may be converted to a string in an unexpected manner. |
| 1140 |
|
| 1141 |
.. code-block:: python |
| 1142 |
|
| 1143 |
b = b"abc" |
| 1144 |
|
| 1145 |
# Error: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". |
| 1146 |
# If this is desired behavior, use f"{x!r}" or "{!r}".format(x). |
| 1147 |
# Otherwise, decode the bytes [str-bytes-safe] |
| 1148 |
print(f"The alphabet starts with {b}") |
| 1149 |
|
| 1150 |
# Okay |
| 1151 |
print(f"The alphabet starts with {b!r}") # The alphabet starts with b'abc' |
| 1152 |
print(f"The alphabet starts with {b.decode('utf-8')}") # The alphabet starts with abc |
| 1153 |
|
| 1154 |
.. _code-str-unpack: |
| 1155 |
|
| 1156 |
Check that ``str`` is not unpacked [str-unpack] |
| 1157 |
--------------------------------------------------------- |
| 1158 |
|
| 1159 |
It can sometimes be surprising that ``str`` is iterable, especially when unpacking |
| 1160 |
in an assignment. |
| 1161 |
|
| 1162 |
Example: |
| 1163 |
|
| 1164 |
.. code-block:: python |
| 1165 |
|
| 1166 |
def print_dict(d: dict[str, str]) -> int: |
| 1167 |
# We meant to do d.items(), but instead we're unpacking the str keys of d |
| 1168 |
|
| 1169 |
# Error: Unpacking a string is disallowed |
| 1170 |
for k, v in d: |
| 1171 |
print(k, v) |
| 1172 |
|
| 1173 |
.. _code-overload-overlap: |
| 1174 |
|
| 1175 |
Check that overloaded functions don't overlap [overload-overlap] |
| 1176 |
---------------------------------------------------------------- |
| 1177 |
|
| 1178 |
Warn if multiple ``@overload`` variants overlap in potentially unsafe ways. |
| 1179 |
This guards against the following situation: |
| 1180 |
|
| 1181 |
.. code-block:: python |
| 1182 |
|
| 1183 |
from typing import overload |
| 1184 |
|
| 1185 |
class A: ... |
| 1186 |
class B(A): ... |
| 1187 |
|
| 1188 |
@overload |
| 1189 |
def foo(x: B) -> int: ... # Error: Overloaded function signatures 1 and 2 overlap with incompatible return types [overload-overlap] |
| 1190 |
@overload |
| 1191 |
def foo(x: A) -> str: ... |
| 1192 |
def foo(x): ... |
| 1193 |
|
| 1194 |
def takes_a(a: A) -> str: |
| 1195 |
return foo(a) |
| 1196 |
|
| 1197 |
a: A = B() |
| 1198 |
value = takes_a(a) |
| 1199 |
# mypy will think that value is a str, but it could actually be an int |
| 1200 |
reveal_type(value) # Revealed type is "builtins.str" |
| 1201 |
|
| 1202 |
|
| 1203 |
Note that in cases where you ignore this error, mypy will usually still infer the |
| 1204 |
types you expect. |
| 1205 |
|
| 1206 |
See :ref:`overloading <function-overloading>` for more explanation. |
| 1207 |
|
| 1208 |
|
| 1209 |
.. _code-overload-cannot-match: |
| 1210 |
|
| 1211 |
Check for overload signatures that cannot match [overload-cannot-match] |
| 1212 |
-------------------------------------------------------------------------- |
| 1213 |
|
| 1214 |
Warn if an ``@overload`` variant can never be matched, because an earlier |
| 1215 |
overload has a wider signature. For example, this can happen if the two |
| 1216 |
overloads accept the same parameters and each parameter on the first overload |
| 1217 |
has the same type or a wider type than the corresponding parameter on the second |
| 1218 |
overload. |
| 1219 |
|
| 1220 |
Example: |
| 1221 |
|
| 1222 |
.. code-block:: python |
| 1223 |
|
| 1224 |
from typing import overload, Union |
| 1225 |
|
| 1226 |
@overload |
| 1227 |
def process(response1: object, response2: object) -> object: |
| 1228 |
... |
| 1229 |
@overload |
| 1230 |
def process(response1: int, response2: int) -> int: # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader [overload-cannot-match] |
| 1231 |
... |
| 1232 |
|
| 1233 |
def process(response1: object, response2: object) -> object: |
| 1234 |
return response1 + response2 |
| 1235 |
|
| 1236 |
.. _code-annotation-unchecked: |
| 1237 |
|
| 1238 |
Notify about an annotation in an unchecked function [annotation-unchecked] |
| 1239 |
-------------------------------------------------------------------------- |
| 1240 |
|
| 1241 |
Sometimes a user may accidentally omit an annotation for a function, and mypy |
| 1242 |
will not check the body of this function (unless one uses |
| 1243 |
:option:`--check-untyped-defs <mypy --check-untyped-defs>` or |
| 1244 |
:option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`). To avoid |
| 1245 |
such situations go unnoticed, mypy will show a note, if there are any type |
| 1246 |
annotations in an unchecked function: |
| 1247 |
|
| 1248 |
.. code-block:: python |
| 1249 |
|
| 1250 |
def test_assignment(): # "-> None" return annotation is missing |
| 1251 |
# Note: By default the bodies of untyped functions are not checked, |
| 1252 |
# consider using --check-untyped-defs [annotation-unchecked] |
| 1253 |
x: int = "no way" |
| 1254 |
|
| 1255 |
Note that mypy will still exit with return code ``0``, since such behaviour is |
| 1256 |
specified by :pep:`484`. |
| 1257 |
|
| 1258 |
.. _code-prop-decorator: |
| 1259 |
|
| 1260 |
Decorator preceding property not supported [prop-decorator] |
| 1261 |
----------------------------------------------------------- |
| 1262 |
|
| 1263 |
Mypy does not yet support analysis of decorators that precede the property |
| 1264 |
decorator. If the decorator does not preserve the declared type of the property, |
| 1265 |
mypy will not infer the correct type for the declaration. If the decorator cannot |
| 1266 |
be moved after the ``@property`` decorator, then you must use a type ignore |
| 1267 |
comment: |
| 1268 |
|
| 1269 |
.. code-block:: python |
| 1270 |
|
| 1271 |
class MyClass: |
| 1272 |
@special # type: ignore[prop-decorator] |
| 1273 |
@property |
| 1274 |
def magic(self) -> str: |
| 1275 |
return "xyzzy" |
| 1276 |
|
| 1277 |
.. note:: |
| 1278 |
|
| 1279 |
For backward compatibility, this error code is a subcode of the generic ``[misc]`` code. |
| 1280 |
|
| 1281 |
.. _code-syntax: |
| 1282 |
|
| 1283 |
Report syntax errors [syntax] |
| 1284 |
----------------------------- |
| 1285 |
|
| 1286 |
If the code being checked is not syntactically valid, mypy issues a |
| 1287 |
syntax error. Most, but not all, syntax errors are *blocking errors*: |
| 1288 |
they can't be ignored with a ``# type: ignore`` comment. |
| 1289 |
|
| 1290 |
.. _code-typeddict-readonly-mutated: |
| 1291 |
|
| 1292 |
ReadOnly key of a TypedDict is mutated [typeddict-readonly-mutated] |
| 1293 |
------------------------------------------------------------------- |
| 1294 |
|
| 1295 |
Consider this example: |
| 1296 |
|
| 1297 |
.. code-block:: python |
| 1298 |
|
| 1299 |
from datetime import datetime |
| 1300 |
from typing import TypedDict |
| 1301 |
from typing_extensions import ReadOnly |
| 1302 |
|
| 1303 |
class User(TypedDict): |
| 1304 |
username: ReadOnly[str] |
| 1305 |
last_active: datetime |
| 1306 |
|
| 1307 |
user: User = {'username': 'foobar', 'last_active': datetime.now()} |
| 1308 |
user['last_active'] = datetime.now() # ok |
| 1309 |
user['username'] = 'other' # error: ReadOnly TypedDict key "key" TypedDict is mutated [typeddict-readonly-mutated] |
| 1310 |
|
| 1311 |
`PEP 705 <https://peps.python.org/pep-0705>`_ specifies |
| 1312 |
how ``ReadOnly`` special form works for ``TypedDict`` objects. |
| 1313 |
|
| 1314 |
.. _code-narrowed-type-not-subtype: |
| 1315 |
|
| 1316 |
Check that ``TypeIs`` narrows types [narrowed-type-not-subtype] |
| 1317 |
--------------------------------------------------------------- |
| 1318 |
|
| 1319 |
:pep:`742` requires that when ``TypeIs`` is used, the narrowed |
| 1320 |
type must be a subtype of the original type:: |
| 1321 |
|
| 1322 |
from typing_extensions import TypeIs |
| 1323 |
|
| 1324 |
def f(x: int) -> TypeIs[str]: # Error, str is not a subtype of int |
| 1325 |
... |
| 1326 |
|
| 1327 |
def g(x: object) -> TypeIs[str]: # OK |
| 1328 |
... |
| 1329 |
|
| 1330 |
.. _code-maybe-unrecognized-str-typeform: |
| 1331 |
|
| 1332 |
String appears in a context which expects a TypeForm [maybe-unrecognized-str-typeform] |
| 1333 |
-------------------------------------------------------------------------------------- |
| 1334 |
|
| 1335 |
TypeForm literals may contain string annotations: |
| 1336 |
|
| 1337 |
.. code-block:: python |
| 1338 |
|
| 1339 |
typx1: TypeForm = str | None |
| 1340 |
typx2: TypeForm = 'str | None' # OK |
| 1341 |
typx3: TypeForm = 'str' | None # OK |
| 1342 |
|
| 1343 |
However TypeForm literals containing a string annotation can only be recognized |
| 1344 |
by mypy in the following locations: |
| 1345 |
|
| 1346 |
.. code-block:: python |
| 1347 |
|
| 1348 |
typx_var: TypeForm = 'str | None' # assignment r-value |
| 1349 |
|
| 1350 |
def func(typx_param: TypeForm) -> TypeForm: |
| 1351 |
return 'str | None' # returned expression |
| 1352 |
|
| 1353 |
func('str | None') # callable's argument |
| 1354 |
|
| 1355 |
If you try to use a string annotation in some other location |
| 1356 |
which expects a TypeForm, the string value will always be treated as a ``str`` |
| 1357 |
even if a ``TypeForm`` would be more appropriate and this error code |
| 1358 |
will be generated: |
| 1359 |
|
| 1360 |
.. code-block:: python |
| 1361 |
|
| 1362 |
# Error: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. [maybe-unrecognized-str-typeform] |
| 1363 |
# Error: List item 0 has incompatible type "str"; expected "TypeForm[Any]" [list-item] |
| 1364 |
list_of_typx: list[TypeForm] = ['str | None', float] |
| 1365 |
|
| 1366 |
Fix the error by surrounding the entire type with ``TypeForm(...)``: |
| 1367 |
|
| 1368 |
.. code-block:: python |
| 1369 |
|
| 1370 |
list_of_typx: list[TypeForm] = [TypeForm('str | None'), float] # OK |
| 1371 |
|
| 1372 |
Similarly, if you try to use a string literal in a location which expects a |
| 1373 |
TypeForm, this error code will be generated: |
| 1374 |
|
| 1375 |
.. code-block:: python |
| 1376 |
|
| 1377 |
dict_of_typx = {'str_or_none': TypeForm(str | None)} |
| 1378 |
# Error: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. [maybe-unrecognized-str-typeform] |
| 1379 |
list_of_typx: list[TypeForm] = [dict_of_typx['str_or_none']] |
| 1380 |
|
| 1381 |
Fix the error by adding ``# type: ignore[maybe-unrecognized-str-typeform]`` |
| 1382 |
to the line with the string literal: |
| 1383 |
|
| 1384 |
.. code-block:: python |
| 1385 |
|
| 1386 |
dict_of_typx = {'str_or_none': TypeForm(str | None)} |
| 1387 |
list_of_typx: list[TypeForm] = [dict_of_typx['str_or_none']] # type: ignore[maybe-unrecognized-str-typeform] |
| 1388 |
|
| 1389 |
.. _code-misc: |
| 1390 |
|
| 1391 |
Miscellaneous checks [misc] |
| 1392 |
--------------------------- |
| 1393 |
|
| 1394 |
Mypy performs numerous other, less commonly failing checks that don't |
| 1395 |
have specific error codes. These use the ``misc`` error code. Other |
| 1396 |
than being used for multiple unrelated errors, the ``misc`` error code |
| 1397 |
is not special. For example, you can ignore all errors in this |
| 1398 |
category by using ``# type: ignore[misc]`` comment. Since these errors |
| 1399 |
are not expected to be common, it's unlikely that you'll see two |
| 1400 |
*different* errors with the ``misc`` code on a single line -- though |
| 1401 |
this can certainly happen once in a while. |
| 1402 |
|
| 1403 |
.. note:: |
| 1404 |
|
| 1405 |
Future mypy versions will likely add new error codes for some errors |
| 1406 |
that currently use the ``misc`` error code. |