| 1 |
.. _common_issues: |
| 2 |
|
| 3 |
Common issues and solutions |
| 4 |
=========================== |
| 5 |
|
| 6 |
This section has examples of cases when you need to update your code |
| 7 |
to use static typing, and ideas for working around issues if mypy |
| 8 |
doesn't work as expected. Statically typed code is often identical to |
| 9 |
normal Python code (except for type annotations), but sometimes you need |
| 10 |
to do things slightly differently. |
| 11 |
|
| 12 |
.. _annotations_needed: |
| 13 |
|
| 14 |
No errors reported for obviously wrong code |
| 15 |
------------------------------------------- |
| 16 |
|
| 17 |
There are several common reasons why obviously wrong code is not |
| 18 |
flagged as an error. |
| 19 |
|
| 20 |
**The function containing the error is not annotated.** |
| 21 |
|
| 22 |
Functions that |
| 23 |
do not have any annotations (neither for any argument nor for the |
| 24 |
return type) are not type-checked, and even the most blatant type |
| 25 |
errors (e.g. ``2 + 'a'``) pass silently. The solution is to add |
| 26 |
annotations. Where that isn't possible, functions without annotations |
| 27 |
can be checked using :option:`--check-untyped-defs <mypy --check-untyped-defs>`. |
| 28 |
|
| 29 |
Example: |
| 30 |
|
| 31 |
.. code-block:: python |
| 32 |
|
| 33 |
def foo(a): |
| 34 |
return '(' + a.split() + ')' # No error! |
| 35 |
|
| 36 |
This gives no error even though ``a.split()`` is "obviously" a list |
| 37 |
(the author probably meant ``a.strip()``). The error is reported |
| 38 |
once you add annotations: |
| 39 |
|
| 40 |
.. code-block:: python |
| 41 |
|
| 42 |
def foo(a: str) -> str: |
| 43 |
return '(' + a.split() + ')' |
| 44 |
# error: Unsupported operand types for + ("str" and "list[str]") |
| 45 |
|
| 46 |
If you don't know what types to add, you can use ``Any``, but beware: |
| 47 |
|
| 48 |
**One of the values involved has type 'Any'.** |
| 49 |
|
| 50 |
Extending the above |
| 51 |
example, if we were to leave out the annotation for ``a``, we'd get |
| 52 |
no error: |
| 53 |
|
| 54 |
.. code-block:: python |
| 55 |
|
| 56 |
def foo(a) -> str: |
| 57 |
return '(' + a.split() + ')' # No error! |
| 58 |
|
| 59 |
The reason is that if the type of ``a`` is unknown, the type of |
| 60 |
``a.split()`` is also unknown, so it is inferred as having type |
| 61 |
``Any``, and it is no error to add a string to an ``Any``. |
| 62 |
|
| 63 |
If you're having trouble debugging such situations, |
| 64 |
:ref:`reveal_type() <reveal-type>` might come in handy. |
| 65 |
|
| 66 |
Note that sometimes library stubs with imprecise type information |
| 67 |
can be a source of ``Any`` values. |
| 68 |
|
| 69 |
:py:meth:`__init__ <object.__init__>` **method has no annotated |
| 70 |
arguments and no return type annotation.** |
| 71 |
|
| 72 |
This is basically a combination of the two cases above, in that ``__init__`` |
| 73 |
without annotations can cause ``Any`` types leak into instance variables: |
| 74 |
|
| 75 |
.. code-block:: python |
| 76 |
|
| 77 |
class Bad: |
| 78 |
def __init__(self): |
| 79 |
self.value = "asdf" |
| 80 |
1 + "asdf" # No error! |
| 81 |
|
| 82 |
bad = Bad() |
| 83 |
bad.value + 1 # No error! |
| 84 |
reveal_type(bad) # Revealed type is "__main__.Bad" |
| 85 |
reveal_type(bad.value) # Revealed type is "Any" |
| 86 |
|
| 87 |
class Good: |
| 88 |
def __init__(self) -> None: # Explicitly return None |
| 89 |
self.value = value |
| 90 |
|
| 91 |
|
| 92 |
**Some imports may be silently ignored**. |
| 93 |
|
| 94 |
A common source of unexpected ``Any`` values is the |
| 95 |
:option:`--ignore-missing-imports <mypy --ignore-missing-imports>` flag. |
| 96 |
|
| 97 |
When you use :option:`--ignore-missing-imports <mypy --ignore-missing-imports>`, |
| 98 |
any imported module that cannot be found is silently replaced with ``Any``. |
| 99 |
|
| 100 |
To help debug this, simply leave out |
| 101 |
:option:`--ignore-missing-imports <mypy --ignore-missing-imports>`. |
| 102 |
As mentioned in :ref:`fix-missing-imports`, setting ``ignore_missing_imports=True`` |
| 103 |
on a per-module basis will make bad surprises less likely and is highly encouraged. |
| 104 |
|
| 105 |
Use of the :option:`--follow-imports=skip <mypy --follow-imports>` flags can also |
| 106 |
cause problems. Use of these flags is strongly discouraged and only required in |
| 107 |
relatively niche situations. See :ref:`follow-imports` for more information. |
| 108 |
|
| 109 |
**mypy considers some of your code unreachable**. |
| 110 |
|
| 111 |
See :ref:`unreachable` for more information. |
| 112 |
|
| 113 |
**A function annotated as returning a non-optional type returns 'None' |
| 114 |
and mypy doesn't complain**. |
| 115 |
|
| 116 |
.. code-block:: python |
| 117 |
|
| 118 |
def foo() -> str: |
| 119 |
return None # No error! |
| 120 |
|
| 121 |
You may have disabled strict optional checking (see |
| 122 |
:ref:`--no-strict-optional <no_strict_optional>` for more). |
| 123 |
|
| 124 |
.. _silencing_checker: |
| 125 |
|
| 126 |
Spurious errors and locally silencing the checker |
| 127 |
------------------------------------------------- |
| 128 |
|
| 129 |
You can use a ``# type: ignore`` comment to silence the type checker |
| 130 |
on a particular line. For example, let's say our code is using |
| 131 |
the C extension module ``frobnicate``, and there's no stub available. |
| 132 |
Mypy will complain about this, as it has no information about the |
| 133 |
module: |
| 134 |
|
| 135 |
.. code-block:: python |
| 136 |
|
| 137 |
import frobnicate # Error: No module "frobnicate" |
| 138 |
frobnicate.start() |
| 139 |
|
| 140 |
You can add a ``# type: ignore`` comment to tell mypy to ignore this |
| 141 |
error: |
| 142 |
|
| 143 |
.. code-block:: python |
| 144 |
|
| 145 |
import frobnicate # type: ignore |
| 146 |
frobnicate.start() # Okay! |
| 147 |
|
| 148 |
The second line is now fine, since the ignore comment causes the name |
| 149 |
``frobnicate`` to get an implicit ``Any`` type. |
| 150 |
|
| 151 |
The type ignore comment must be at the start of the comments on a line. |
| 152 |
This type ignore will not take effect: |
| 153 |
|
| 154 |
.. code-block:: python |
| 155 |
|
| 156 |
import frobnicate #example other comment # type: ignore |
| 157 |
frobnicate.start() |
| 158 |
|
| 159 |
.. note:: |
| 160 |
|
| 161 |
You can use the form ``# type: ignore[<code>]`` to only ignore |
| 162 |
specific errors on the line. This way you are less likely to |
| 163 |
silence unexpected errors that are not safe to ignore, and this |
| 164 |
will also document what the purpose of the comment is. See |
| 165 |
:ref:`error-codes` for more information. |
| 166 |
|
| 167 |
.. note:: |
| 168 |
|
| 169 |
The ``# type: ignore`` comment will only assign the implicit ``Any`` |
| 170 |
type if mypy cannot find information about that particular module. So, |
| 171 |
if we did have a stub available for ``frobnicate`` then mypy would |
| 172 |
ignore the ``# type: ignore`` comment and typecheck the stub as usual. |
| 173 |
|
| 174 |
Another option is to explicitly annotate values with type ``Any`` -- |
| 175 |
mypy will let you perform arbitrary operations on ``Any`` |
| 176 |
values. Sometimes there is no more precise type you can use for a |
| 177 |
particular value, especially if you use dynamic Python features |
| 178 |
such as :py:meth:`__getattr__ <object.__getattr__>`: |
| 179 |
|
| 180 |
.. code-block:: python |
| 181 |
|
| 182 |
class Wrapper: |
| 183 |
... |
| 184 |
def __getattr__(self, a: str) -> Any: |
| 185 |
return getattr(self._wrapped, a) |
| 186 |
|
| 187 |
Finally, you can create a stub file (``.pyi``) for a file that |
| 188 |
generates spurious errors. Mypy will only look at the stub file |
| 189 |
and ignore the implementation, since stub files take precedence |
| 190 |
over ``.py`` files. |
| 191 |
|
| 192 |
Ignoring a whole file |
| 193 |
--------------------- |
| 194 |
|
| 195 |
* To only ignore errors, use a top-level ``# mypy: ignore-errors`` comment instead. |
| 196 |
* To only ignore errors with a specific error code, use a top-level |
| 197 |
``# mypy: disable-error-code="..."`` comment. Example: ``# mypy: disable-error-code="truthy-bool, ignore-without-code"`` |
| 198 |
* To replace the contents of a module with ``Any``, use a per-module ``follow_imports = skip``. |
| 199 |
See :ref:`Following imports <follow-imports>` for details. |
| 200 |
|
| 201 |
Note that a ``# type: ignore`` comment at the top of a module (before any statements, |
| 202 |
including imports or docstrings) has the effect of ignoring the entire contents of the module. |
| 203 |
This behaviour can be surprising and result in |
| 204 |
"Module ... has no attribute ... [attr-defined]" errors. |
| 205 |
|
| 206 |
Issues with code at runtime |
| 207 |
--------------------------- |
| 208 |
|
| 209 |
Idiomatic use of type annotations can sometimes run up against what a given |
| 210 |
version of Python considers legal code. These can result in some of the |
| 211 |
following errors when trying to run your code: |
| 212 |
|
| 213 |
* ``ImportError`` from circular imports |
| 214 |
* ``NameError: name "X" is not defined`` from forward references |
| 215 |
* ``TypeError: 'type' object is not subscriptable`` from types that are not generic at runtime |
| 216 |
* ``ImportError`` or ``ModuleNotFoundError`` from use of stub definitions not available at runtime |
| 217 |
* ``TypeError: unsupported operand type(s) for |: 'type' and 'type'`` from use of new syntax |
| 218 |
|
| 219 |
For dealing with these, see :ref:`runtime_troubles`. |
| 220 |
|
| 221 |
Mypy runs are slow |
| 222 |
------------------ |
| 223 |
|
| 224 |
If your mypy runs feel slow, you should probably use the :ref:`mypy |
| 225 |
daemon <mypy_daemon>`, which can speed up incremental mypy runtimes by |
| 226 |
a factor of 10 or more. :ref:`Remote caching <remote-cache>` can |
| 227 |
make cold mypy runs several times faster. |
| 228 |
|
| 229 |
Furthermore: as of `mypy 1.13 <https://mypy-lang.blogspot.com/2024/10/mypy-113-released.html>`_, |
| 230 |
mypy allows use of the orjson library for handling the cache instead of the stdlib json, for |
| 231 |
improved performance. You can ensure the presence of orjson using the ``faster-cache`` extra: |
| 232 |
|
| 233 |
python3 -m pip install -U mypy[faster-cache] |
| 234 |
|
| 235 |
Mypy may depend on orjson by default in the future. |
| 236 |
|
| 237 |
Types of empty collections |
| 238 |
-------------------------- |
| 239 |
|
| 240 |
You often need to specify the type when you assign an empty list or |
| 241 |
dict to a new variable, as mentioned earlier: |
| 242 |
|
| 243 |
.. code-block:: python |
| 244 |
|
| 245 |
a: list[int] = [] |
| 246 |
|
| 247 |
Without the annotation mypy can't always figure out the |
| 248 |
precise type of ``a``. |
| 249 |
|
| 250 |
You can use a simple empty list literal in a dynamically typed function (as the |
| 251 |
type of ``a`` would be implicitly ``Any`` and need not be inferred), if type |
| 252 |
of the variable has been declared or inferred before, or if you perform a simple |
| 253 |
modification operation in the same scope (such as ``append`` for a list): |
| 254 |
|
| 255 |
.. code-block:: python |
| 256 |
|
| 257 |
a = [] # Okay because followed by append, inferred type list[int] |
| 258 |
for i in range(n): |
| 259 |
a.append(i * i) |
| 260 |
|
| 261 |
However, in more complex cases an explicit type annotation can be |
| 262 |
required (mypy will tell you this). Often the annotation can |
| 263 |
make your code easier to understand, so it doesn't only help mypy but |
| 264 |
everybody who is reading the code! |
| 265 |
|
| 266 |
Redefinitions with incompatible types |
| 267 |
------------------------------------- |
| 268 |
|
| 269 |
Each name within a function only has a single 'declared' type. You can |
| 270 |
reuse for loop indices etc., but if you want to use a variable with |
| 271 |
multiple types within a single function, you may need to instead use |
| 272 |
multiple variables (or maybe declare the variable with an ``Any`` type). |
| 273 |
|
| 274 |
.. code-block:: python |
| 275 |
|
| 276 |
def f() -> None: |
| 277 |
n = 1 |
| 278 |
... |
| 279 |
n = 'x' # error: Incompatible types in assignment (expression has type "str", variable has type "int") |
| 280 |
|
| 281 |
.. note:: |
| 282 |
|
| 283 |
Using the :option:`--allow-redefinition <mypy --allow-redefinition>` |
| 284 |
flag can suppress this error in several cases. |
| 285 |
|
| 286 |
Note that you can redefine a variable with a more *precise* or a more |
| 287 |
concrete type. For example, you can redefine a sequence (which does |
| 288 |
not support ``sort()``) as a list and sort it in-place: |
| 289 |
|
| 290 |
.. code-block:: python |
| 291 |
|
| 292 |
def f(x: Sequence[int]) -> None: |
| 293 |
# Type of x is Sequence[int] here; we don't know the concrete type. |
| 294 |
x = list(x) |
| 295 |
# Type of x is list[int] here. |
| 296 |
x.sort() # Okay! |
| 297 |
|
| 298 |
See :ref:`type-narrowing` for more information. |
| 299 |
|
| 300 |
.. _variance: |
| 301 |
|
| 302 |
Invariance vs covariance |
| 303 |
------------------------ |
| 304 |
|
| 305 |
Most mutable generic collections are invariant. When using the legacy |
| 306 |
``TypeVar`` syntax, mypy considers all user-defined generic classes invariant |
| 307 |
by default (see :ref:`variance-of-generics` for motivation). When using the |
| 308 |
:pep:`695` syntax (``class MyClass[T]: ...``), variance is inferred from |
| 309 |
usage rather than defaulting to invariant. |
| 310 |
|
| 311 |
The fact that mutable sequences are usually invariant can lead to some |
| 312 |
unexpected errors when combined with type inference. For example: |
| 313 |
|
| 314 |
.. code-block:: python |
| 315 |
|
| 316 |
class A: ... |
| 317 |
class B(A): ... |
| 318 |
|
| 319 |
lst = [A(), A()] # Inferred type is list[A] |
| 320 |
new_lst = [B(), B()] # inferred type is list[B] |
| 321 |
lst = new_lst # mypy will complain about this, because List is invariant |
| 322 |
|
| 323 |
Possible strategies in such situations are: |
| 324 |
|
| 325 |
* Use an explicit type annotation: |
| 326 |
|
| 327 |
.. code-block:: python |
| 328 |
|
| 329 |
new_lst: list[A] = [B(), B()] |
| 330 |
lst = new_lst # OK |
| 331 |
|
| 332 |
* Make a copy of the right hand side: |
| 333 |
|
| 334 |
.. code-block:: python |
| 335 |
|
| 336 |
lst = list(new_lst) # Also OK |
| 337 |
|
| 338 |
* Use immutable collections as annotations whenever possible: |
| 339 |
|
| 340 |
.. code-block:: python |
| 341 |
|
| 342 |
def f_bad(x: list[A]) -> A: |
| 343 |
return x[0] |
| 344 |
f_bad(new_lst) # Fails |
| 345 |
|
| 346 |
def f_good(x: Sequence[A]) -> A: |
| 347 |
return x[0] |
| 348 |
f_good(new_lst) # OK |
| 349 |
|
| 350 |
Declaring a supertype as variable type |
| 351 |
-------------------------------------- |
| 352 |
|
| 353 |
Sometimes the inferred type is a subtype (subclass) of the desired |
| 354 |
type. The type inference uses the first assignment to infer the type |
| 355 |
of a name: |
| 356 |
|
| 357 |
.. code-block:: python |
| 358 |
|
| 359 |
class Shape: ... |
| 360 |
class Circle(Shape): ... |
| 361 |
class Triangle(Shape): ... |
| 362 |
|
| 363 |
shape = Circle() # mypy infers the type of shape to be Circle |
| 364 |
shape = Triangle() # error: Incompatible types in assignment (expression has type "Triangle", variable has type "Circle") |
| 365 |
|
| 366 |
You can just give an explicit type for the variable in cases such the |
| 367 |
above example: |
| 368 |
|
| 369 |
.. code-block:: python |
| 370 |
|
| 371 |
shape: Shape = Circle() # The variable s can be any Shape, not just Circle |
| 372 |
shape = Triangle() # OK |
| 373 |
|
| 374 |
Complex type tests |
| 375 |
------------------ |
| 376 |
|
| 377 |
Mypy can usually infer the types correctly when using :py:func:`isinstance <isinstance>`, |
| 378 |
:py:func:`issubclass <issubclass>`, |
| 379 |
or ``type(obj) is some_class`` type tests, |
| 380 |
and even :ref:`user-defined type guards <type-guards>`, |
| 381 |
but for other kinds of checks you may need to add an |
| 382 |
explicit type cast: |
| 383 |
|
| 384 |
.. code-block:: python |
| 385 |
|
| 386 |
from collections.abc import Sequence |
| 387 |
from typing import cast |
| 388 |
|
| 389 |
def find_first_str(a: Sequence[object]) -> str: |
| 390 |
index = next((i for i, s in enumerate(a) if isinstance(s, str)), -1) |
| 391 |
if index < 0: |
| 392 |
raise ValueError('No str found') |
| 393 |
|
| 394 |
found = a[index] # Has type "object", despite the fact that we know it is "str" |
| 395 |
return cast(str, found) # We need an explicit cast to make mypy happy |
| 396 |
|
| 397 |
Alternatively, you can use an ``assert`` statement together with some |
| 398 |
of the supported type inference techniques: |
| 399 |
|
| 400 |
.. code-block:: python |
| 401 |
|
| 402 |
def find_first_str(a: Sequence[object]) -> str: |
| 403 |
index = next((i for i, s in enumerate(a) if isinstance(s, str)), -1) |
| 404 |
if index < 0: |
| 405 |
raise ValueError('No str found') |
| 406 |
|
| 407 |
found = a[index] # Has type "object", despite the fact that we know it is "str" |
| 408 |
assert isinstance(found, str) # Now, "found" will be narrowed to "str" |
| 409 |
return found # No need for the explicit "cast()" anymore |
| 410 |
|
| 411 |
.. note:: |
| 412 |
|
| 413 |
Note that the :py:class:`object` type used in the above example is similar |
| 414 |
to ``Object`` in Java: it only supports operations defined for *all* |
| 415 |
objects, such as equality and :py:func:`isinstance`. The type ``Any``, |
| 416 |
in contrast, supports all operations, even if they may fail at |
| 417 |
runtime. The cast above would have been unnecessary if the type of |
| 418 |
``o`` was ``Any``. |
| 419 |
|
| 420 |
.. note:: |
| 421 |
|
| 422 |
You can read more about type narrowing techniques :ref:`here <type-narrowing>`. |
| 423 |
|
| 424 |
Type inference in Mypy is designed to work well in common cases, to be |
| 425 |
predictable and to let the type checker give useful error |
| 426 |
messages. More powerful type inference strategies often have complex |
| 427 |
and difficult-to-predict failure modes and could result in very |
| 428 |
confusing error messages. The tradeoff is that you as a programmer |
| 429 |
sometimes have to give the type checker a little help. |
| 430 |
|
| 431 |
.. _version_and_platform_checks: |
| 432 |
|
| 433 |
Python version and system platform checks |
| 434 |
----------------------------------------- |
| 435 |
|
| 436 |
Mypy supports the ability to perform Python version checks and platform |
| 437 |
checks (e.g. Windows vs Posix), ignoring code paths that won't be run on |
| 438 |
the targeted Python version or platform. This allows you to more effectively |
| 439 |
typecheck code that supports multiple versions of Python or multiple operating |
| 440 |
systems. |
| 441 |
|
| 442 |
More specifically, mypy will understand the use of :py:data:`sys.version_info` and |
| 443 |
:py:data:`sys.platform` checks within ``if/elif/else`` statements. For example: |
| 444 |
|
| 445 |
.. code-block:: python |
| 446 |
|
| 447 |
import sys |
| 448 |
|
| 449 |
# Distinguishing between different versions of Python: |
| 450 |
if sys.version_info >= (3, 13): |
| 451 |
# Python 3.13+ specific definitions and imports |
| 452 |
else: |
| 453 |
# Other definitions and imports |
| 454 |
|
| 455 |
# Distinguishing between different operating systems: |
| 456 |
if sys.platform.startswith("linux"): |
| 457 |
# Linux-specific code |
| 458 |
elif sys.platform == "darwin": |
| 459 |
# Mac-specific code |
| 460 |
elif sys.platform == "win32": |
| 461 |
# Windows-specific code |
| 462 |
else: |
| 463 |
# Other systems |
| 464 |
|
| 465 |
As a special case, you can also use one of these checks in a top-level |
| 466 |
(unindented) ``assert``; this makes mypy skip the rest of the file. |
| 467 |
Example: |
| 468 |
|
| 469 |
.. code-block:: python |
| 470 |
|
| 471 |
import sys |
| 472 |
|
| 473 |
assert sys.platform != 'win32' |
| 474 |
|
| 475 |
# The rest of this file doesn't apply to Windows. |
| 476 |
|
| 477 |
Some other expressions exhibit similar behavior; in particular, |
| 478 |
:py:data:`~typing.TYPE_CHECKING`, variables named ``MYPY`` or ``TYPE_CHECKING``, and any variable |
| 479 |
whose name is passed to :option:`--always-true <mypy --always-true>` or :option:`--always-false <mypy --always-false>`. |
| 480 |
(However, ``True`` and ``False`` are not treated specially!) |
| 481 |
|
| 482 |
.. note:: |
| 483 |
|
| 484 |
Mypy currently does not support more complex checks, and does not assign |
| 485 |
any special meaning when assigning a :py:data:`sys.version_info` or :py:data:`sys.platform` |
| 486 |
check to a variable. This may change in future versions of mypy. |
| 487 |
|
| 488 |
By default, mypy will use your current version of Python and your current |
| 489 |
operating system as default values for :py:data:`sys.version_info` and |
| 490 |
:py:data:`sys.platform`. |
| 491 |
|
| 492 |
To target a different Python version, use the :option:`--python-version X.Y <mypy --python-version>` flag. |
| 493 |
For example, to verify your code typechecks if were run using Python 3.8, pass |
| 494 |
in :option:`--python-version 3.8 <mypy --python-version>` from the command line. Note that you do not need |
| 495 |
to have Python 3.8 installed to perform this check. |
| 496 |
|
| 497 |
To target a different operating system, use the :option:`--platform PLATFORM <mypy --platform>` flag. |
| 498 |
For example, to verify your code typechecks if it were run in Windows, pass |
| 499 |
in :option:`--platform win32 <mypy --platform>`. See the documentation for :py:data:`sys.platform` |
| 500 |
for examples of valid platform parameters. |
| 501 |
|
| 502 |
.. _reveal-type: |
| 503 |
|
| 504 |
Displaying the type of an expression |
| 505 |
------------------------------------ |
| 506 |
|
| 507 |
You can use ``reveal_type(expr)`` to ask mypy to display the inferred |
| 508 |
static type of an expression. This can be useful when you don't quite |
| 509 |
understand how mypy handles a particular piece of code. Example: |
| 510 |
|
| 511 |
.. code-block:: python |
| 512 |
|
| 513 |
reveal_type((1, 'hello')) # Revealed type is "tuple[builtins.int, builtins.str]" |
| 514 |
|
| 515 |
You can also use ``reveal_locals()`` at any line in a file |
| 516 |
to see the types of all local variables at once. Example: |
| 517 |
|
| 518 |
.. code-block:: python |
| 519 |
|
| 520 |
a = 1 |
| 521 |
b = 'one' |
| 522 |
reveal_locals() |
| 523 |
# Revealed local types are: |
| 524 |
# a: builtins.int |
| 525 |
# b: builtins.str |
| 526 |
.. note:: |
| 527 |
|
| 528 |
``reveal_type`` and ``reveal_locals`` are handled specially by mypy during |
| 529 |
type checking, and don't have to be defined or imported. |
| 530 |
|
| 531 |
However, if you want to run your code, |
| 532 |
you'll have to remove any ``reveal_type`` and ``reveal_locals`` |
| 533 |
calls from your program or else Python will give you an error at runtime. |
| 534 |
|
| 535 |
Alternatively, you can import ``reveal_type`` from ``typing_extensions`` |
| 536 |
or ``typing`` (on Python 3.11 and newer) |
| 537 |
|
| 538 |
.. _silencing-linters: |
| 539 |
|
| 540 |
Silencing linters |
| 541 |
----------------- |
| 542 |
|
| 543 |
In some cases, linters will complain about unused imports or code. In |
| 544 |
these cases, you can silence them with a comment after type comments, or on |
| 545 |
the same line as the import: |
| 546 |
|
| 547 |
.. code-block:: python |
| 548 |
|
| 549 |
# to silence complaints about unused imports |
| 550 |
from typing import List # noqa |
| 551 |
a = None # type: List[int] |
| 552 |
|
| 553 |
|
| 554 |
To silence the linter on the same line as a type comment |
| 555 |
put the linter comment *after* the type comment: |
| 556 |
|
| 557 |
.. code-block:: python |
| 558 |
|
| 559 |
a = some_complex_thing() # type: ignore # noqa |
| 560 |
|
| 561 |
Covariant subtyping of mutable protocol members is rejected |
| 562 |
----------------------------------------------------------- |
| 563 |
|
| 564 |
Mypy rejects this because this is potentially unsafe. |
| 565 |
Consider this example: |
| 566 |
|
| 567 |
.. code-block:: python |
| 568 |
|
| 569 |
from typing import Protocol |
| 570 |
|
| 571 |
class P(Protocol): |
| 572 |
x: float |
| 573 |
|
| 574 |
def fun(arg: P) -> None: |
| 575 |
arg.x = 3.14 |
| 576 |
|
| 577 |
class C: |
| 578 |
x = 42 |
| 579 |
c = C() |
| 580 |
fun(c) # This is not safe |
| 581 |
c.x << 5 # Since this will fail! |
| 582 |
|
| 583 |
To work around this problem consider whether "mutating" is actually part |
| 584 |
of a protocol. If not, then one can use a :py:class:`@property <property>` in |
| 585 |
the protocol definition: |
| 586 |
|
| 587 |
.. code-block:: python |
| 588 |
|
| 589 |
from typing import Protocol |
| 590 |
|
| 591 |
class P(Protocol): |
| 592 |
@property |
| 593 |
def x(self) -> float: |
| 594 |
pass |
| 595 |
|
| 596 |
def fun(arg: P) -> None: |
| 597 |
... |
| 598 |
|
| 599 |
class C: |
| 600 |
x = 42 |
| 601 |
fun(C()) # OK |
| 602 |
|
| 603 |
Dealing with conflicting names |
| 604 |
------------------------------ |
| 605 |
|
| 606 |
Suppose you have a class with a method whose name is the same as an |
| 607 |
imported (or built-in) type, and you want to use the type in another |
| 608 |
method signature. E.g.: |
| 609 |
|
| 610 |
.. code-block:: python |
| 611 |
|
| 612 |
class Message: |
| 613 |
def bytes(self): |
| 614 |
... |
| 615 |
def register(self, path: bytes): # error: Invalid type "mod.Message.bytes" |
| 616 |
... |
| 617 |
|
| 618 |
The third line elicits an error because mypy sees the argument type |
| 619 |
``bytes`` as a reference to the method by that name. Other than |
| 620 |
renaming the method, a workaround is to use an alias: |
| 621 |
|
| 622 |
.. code-block:: python |
| 623 |
|
| 624 |
bytes_ = bytes |
| 625 |
class Message: |
| 626 |
def bytes(self): |
| 627 |
... |
| 628 |
def register(self, path: bytes_): |
| 629 |
... |
| 630 |
|
| 631 |
Using a development mypy build |
| 632 |
------------------------------ |
| 633 |
|
| 634 |
You can install the latest development version of mypy from source. Clone the |
| 635 |
`mypy repository on GitHub <https://github.com/python/mypy>`_, and then run |
| 636 |
``pip install`` locally: |
| 637 |
|
| 638 |
.. code-block:: text |
| 639 |
|
| 640 |
git clone https://github.com/python/mypy.git |
| 641 |
cd mypy |
| 642 |
python3 -m pip install --upgrade . |
| 643 |
|
| 644 |
To install a development version of mypy that is mypyc-compiled, see the |
| 645 |
instructions at the `mypyc wheels repo <https://github.com/mypyc/mypy_mypyc-wheels>`_. |
| 646 |
|
| 647 |
Variables vs type aliases |
| 648 |
------------------------- |
| 649 |
|
| 650 |
Mypy has both *type aliases* and variables with types like ``type[...]``. These are |
| 651 |
subtly different, and it's important to understand how they differ to avoid pitfalls. |
| 652 |
|
| 653 |
1. A variable with type ``type[...]`` is defined using an assignment with an |
| 654 |
explicit type annotation: |
| 655 |
|
| 656 |
.. code-block:: python |
| 657 |
|
| 658 |
class A: ... |
| 659 |
tp: type[A] = A |
| 660 |
|
| 661 |
2. You can define a type alias using an assignment without an explicit type annotation |
| 662 |
at the top level of a module: |
| 663 |
|
| 664 |
.. code-block:: python |
| 665 |
|
| 666 |
class A: ... |
| 667 |
Alias = A |
| 668 |
|
| 669 |
You can also use ``TypeAlias`` (:pep:`613`) to define an *explicit type alias*: |
| 670 |
|
| 671 |
.. code-block:: python |
| 672 |
|
| 673 |
from typing import TypeAlias |
| 674 |
|
| 675 |
class A: ... |
| 676 |
Alias: TypeAlias = A |
| 677 |
|
| 678 |
You should always use ``TypeAlias`` to define a type alias in a class body or |
| 679 |
inside a function. |
| 680 |
|
| 681 |
The main difference is that the target of an alias is precisely known statically, and this |
| 682 |
means that they can be used in type annotations and other *type contexts*. Type aliases |
| 683 |
can't be defined conditionally (unless using |
| 684 |
:ref:`supported Python version and platform checks <version_and_platform_checks>`): |
| 685 |
|
| 686 |
.. code-block:: python |
| 687 |
|
| 688 |
class A: ... |
| 689 |
class B: ... |
| 690 |
|
| 691 |
if random() > 0.5: |
| 692 |
Alias = A |
| 693 |
else: |
| 694 |
# error: Cannot assign multiple types to name "Alias" without an |
| 695 |
# explicit "Type[...]" annotation |
| 696 |
Alias = B |
| 697 |
|
| 698 |
tp: type[object] # "tp" is a variable with a type object value |
| 699 |
if random() > 0.5: |
| 700 |
tp = A |
| 701 |
else: |
| 702 |
tp = B # This is OK |
| 703 |
|
| 704 |
def fun1(x: Alias) -> None: ... # OK |
| 705 |
def fun2(x: tp) -> None: ... # Error: "tp" is not valid as a type |
| 706 |
|
| 707 |
Incompatible overrides |
| 708 |
---------------------- |
| 709 |
|
| 710 |
It's unsafe to override a method with a more specific argument type, |
| 711 |
as it violates the `Liskov substitution principle |
| 712 |
<https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle>`_. |
| 713 |
For return types, it's unsafe to override a method with a more general |
| 714 |
return type. |
| 715 |
|
| 716 |
Other incompatible signature changes in method overrides, such as |
| 717 |
adding an extra required parameter, or removing an optional parameter, |
| 718 |
will also generate errors. The signature of a method in a subclass |
| 719 |
should accept all valid calls to the base class method. Mypy |
| 720 |
treats a subclass as a subtype of the base class. An instance of a |
| 721 |
subclass is valid everywhere where an instance of the base class is |
| 722 |
valid. |
| 723 |
|
| 724 |
This example demonstrates both safe and unsafe overrides: |
| 725 |
|
| 726 |
.. code-block:: python |
| 727 |
|
| 728 |
from collections.abc import Sequence, Iterable |
| 729 |
|
| 730 |
class A: |
| 731 |
def test(self, t: Sequence[int]) -> Sequence[str]: |
| 732 |
... |
| 733 |
|
| 734 |
class GeneralizedArgument(A): |
| 735 |
# A more general argument type is okay |
| 736 |
def test(self, t: Iterable[int]) -> Sequence[str]: # OK |
| 737 |
... |
| 738 |
|
| 739 |
class NarrowerArgument(A): |
| 740 |
# A more specific argument type isn't accepted |
| 741 |
def test(self, t: list[int]) -> Sequence[str]: # Error |
| 742 |
... |
| 743 |
|
| 744 |
class NarrowerReturn(A): |
| 745 |
# A more specific return type is fine |
| 746 |
def test(self, t: Sequence[int]) -> list[str]: # OK |
| 747 |
... |
| 748 |
|
| 749 |
class GeneralizedReturn(A): |
| 750 |
# A more general return type is an error |
| 751 |
def test(self, t: Sequence[int]) -> Iterable[str]: # Error |
| 752 |
... |
| 753 |
|
| 754 |
You can use ``# type: ignore[override]`` to silence the error. Add it |
| 755 |
to the line that generates the error, if you decide that type safety is |
| 756 |
not necessary: |
| 757 |
|
| 758 |
.. code-block:: python |
| 759 |
|
| 760 |
class NarrowerArgument(A): |
| 761 |
def test(self, t: list[int]) -> Sequence[str]: # type: ignore[override] |
| 762 |
... |
| 763 |
|
| 764 |
.. _unreachable: |
| 765 |
|
| 766 |
Unreachable code |
| 767 |
---------------- |
| 768 |
|
| 769 |
Mypy may consider some code as *unreachable*, even if it might not be |
| 770 |
immediately obvious why. It's important to note that mypy will *not* |
| 771 |
type check such code. Consider this example: |
| 772 |
|
| 773 |
.. code-block:: python |
| 774 |
|
| 775 |
class Foo: |
| 776 |
bar: str = '' |
| 777 |
|
| 778 |
def bar() -> None: |
| 779 |
foo: Foo = Foo() |
| 780 |
return |
| 781 |
x: int = 'abc' # Unreachable -- no error |
| 782 |
|
| 783 |
It's easy to see that any statement after ``return`` is unreachable, |
| 784 |
and hence mypy will not complain about the mistyped code below |
| 785 |
it. For a more subtle example, consider this code: |
| 786 |
|
| 787 |
.. code-block:: python |
| 788 |
|
| 789 |
class Foo: |
| 790 |
bar: str = '' |
| 791 |
|
| 792 |
def bar() -> None: |
| 793 |
foo: Foo = Foo() |
| 794 |
assert foo.bar is None |
| 795 |
x: int = 'abc' # Unreachable -- no error |
| 796 |
|
| 797 |
Again, mypy will not report any errors. The type of ``foo.bar`` is |
| 798 |
``str``, and mypy reasons that it can never be ``None``. Hence the |
| 799 |
``assert`` statement will always fail and the statement below will |
| 800 |
never be executed. (Note that in Python, ``None`` is not an empty |
| 801 |
reference but an object of type ``None``.) |
| 802 |
|
| 803 |
In this example mypy will go on to check the last line and report an |
| 804 |
error, since mypy thinks that the condition could be either True or |
| 805 |
False: |
| 806 |
|
| 807 |
.. code-block:: python |
| 808 |
|
| 809 |
class Foo: |
| 810 |
bar: str = '' |
| 811 |
|
| 812 |
def bar() -> None: |
| 813 |
foo: Foo = Foo() |
| 814 |
if not foo.bar: |
| 815 |
return |
| 816 |
x: int = 'abc' # Reachable -- error |
| 817 |
|
| 818 |
If you use the :option:`--warn-unreachable <mypy --warn-unreachable>` flag, mypy will generate |
| 819 |
an error about each unreachable code block. |
| 820 |
|
| 821 |
Narrowing and inner functions |
| 822 |
----------------------------- |
| 823 |
|
| 824 |
Because closures in Python are late-binding (https://docs.python-guide.org/writing/gotchas/#late-binding-closures), |
| 825 |
mypy will not narrow the type of a captured variable in an inner function. |
| 826 |
This is best understood via an example: |
| 827 |
|
| 828 |
.. code-block:: python |
| 829 |
|
| 830 |
def foo(x: int | None) -> Callable[[], int]: |
| 831 |
if x is None: |
| 832 |
x = 5 |
| 833 |
print(x + 1) # mypy correctly deduces x must be an int here |
| 834 |
def inner() -> int: |
| 835 |
return x + 1 # but (correctly) complains about this line |
| 836 |
|
| 837 |
x = None # because x could later be assigned None |
| 838 |
return inner |
| 839 |
|
| 840 |
inner = foo(5) |
| 841 |
inner() # this will raise an error when called |
| 842 |
|
| 843 |
To get this code to type check, you could assign ``y = x`` after ``x`` has been |
| 844 |
narrowed, and use ``y`` in the inner function, or add an assert in the inner |
| 845 |
function. |
| 846 |
|
| 847 |
.. _incorrect-self: |
| 848 |
|
| 849 |
Incorrect use of ``Self`` |
| 850 |
------------------------- |
| 851 |
|
| 852 |
``Self`` is not the type of the current class; it's a type variable with upper |
| 853 |
bound of the current class. That is, it represents the type of the current class |
| 854 |
or of potential subclasses. |
| 855 |
|
| 856 |
.. code-block:: python |
| 857 |
|
| 858 |
from typing import Self |
| 859 |
|
| 860 |
class Foo: |
| 861 |
@classmethod |
| 862 |
def constructor(cls) -> Self: |
| 863 |
# Instead, either call cls() or change the annotation to -> Foo |
| 864 |
return Foo() # error: Incompatible return value type (got "Foo", expected "Self") |
| 865 |
|
| 866 |
class Bar(Foo): |
| 867 |
... |
| 868 |
|
| 869 |
reveal_type(Foo.constructor()) # note: Revealed type is "Foo" |
| 870 |
# In the context of the subclass Bar, the Self return type promises |
| 871 |
# that the return value will be Bar |
| 872 |
reveal_type(Bar.constructor()) # note: Revealed type is "Bar" |