| 1 |
.. _runtime_troubles: |
| 2 |
|
| 3 |
Annotation issues at runtime |
| 4 |
============================ |
| 5 |
|
| 6 |
Idiomatic use of type annotations can sometimes run up against what a given |
| 7 |
version of Python considers legal code. This section describes these scenarios |
| 8 |
and explains how to get your code running again. Generally speaking, we have |
| 9 |
three tools at our disposal: |
| 10 |
|
| 11 |
* Use of string literal types or type comments |
| 12 |
* Use of ``typing.TYPE_CHECKING`` |
| 13 |
* Use of ``from __future__ import annotations`` (:pep:`563`) |
| 14 |
|
| 15 |
We provide a description of these before moving onto discussion of specific |
| 16 |
problems you may encounter. |
| 17 |
|
| 18 |
.. _string-literal-types: |
| 19 |
|
| 20 |
String literal types and type comments |
| 21 |
-------------------------------------- |
| 22 |
|
| 23 |
Mypy lets you add type annotations using the (now deprecated) ``# type:`` |
| 24 |
type comment syntax. These were required with Python versions older than 3.6, |
| 25 |
since they didn't support type annotations on variables. Example: |
| 26 |
|
| 27 |
.. code-block:: python |
| 28 |
|
| 29 |
a = 1 # type: int |
| 30 |
|
| 31 |
def f(x): # type: (int) -> int |
| 32 |
return x + 1 |
| 33 |
|
| 34 |
# Alternative type comment syntax for functions with many arguments |
| 35 |
def send_email( |
| 36 |
address, # type: Union[str, List[str]] |
| 37 |
sender, # type: str |
| 38 |
cc, # type: Optional[List[str]] |
| 39 |
subject='', |
| 40 |
body=None # type: List[str] |
| 41 |
): |
| 42 |
# type: (...) -> bool |
| 43 |
|
| 44 |
Type comments can't cause runtime errors because comments are not evaluated by |
| 45 |
Python. |
| 46 |
|
| 47 |
In a similar way, using string literal types sidesteps the problem of |
| 48 |
annotations that would cause runtime errors. |
| 49 |
|
| 50 |
Any type can be entered as a string literal, and you can combine |
| 51 |
string-literal types with non-string-literal types freely: |
| 52 |
|
| 53 |
.. code-block:: python |
| 54 |
|
| 55 |
def f(a: list['A']) -> None: ... # OK, prevents NameError since A is defined later |
| 56 |
def g(n: 'int') -> None: ... # Also OK, though not useful |
| 57 |
|
| 58 |
class A: pass |
| 59 |
|
| 60 |
String literal types are never needed in ``# type:`` comments and :ref:`stub files <stub-files>`. |
| 61 |
|
| 62 |
String literal types must be defined (or imported) later *in the same module*. |
| 63 |
They cannot be used to leave cross-module references unresolved. (For dealing |
| 64 |
with import cycles, see :ref:`import-cycles`.) |
| 65 |
|
| 66 |
.. _future-annotations: |
| 67 |
|
| 68 |
Future annotations import (PEP 563) |
| 69 |
----------------------------------- |
| 70 |
|
| 71 |
Many of the issues described here are caused by Python trying to evaluate |
| 72 |
annotations. Future Python versions (potentially Python 3.14) will by default no |
| 73 |
longer attempt to evaluate function and variable annotations. This behaviour is |
| 74 |
made available in Python 3.7 and later through the use of |
| 75 |
``from __future__ import annotations``. |
| 76 |
|
| 77 |
This can be thought of as automatic string literal-ification of all function and |
| 78 |
variable annotations. Note that function and variable annotations are still |
| 79 |
required to be valid Python syntax. For more details, see :pep:`563`. |
| 80 |
|
| 81 |
.. note:: |
| 82 |
|
| 83 |
Even with the ``__future__`` import, there are some scenarios that could |
| 84 |
still require string literals or result in errors, typically involving use |
| 85 |
of forward references or generics in: |
| 86 |
|
| 87 |
* :ref:`type aliases <type-aliases>` not defined using the ``type`` statement; |
| 88 |
* :ref:`type narrowing <type-narrowing>`; |
| 89 |
* type definitions (see :py:class:`~typing.TypeVar`, :py:class:`~typing.NewType`, :py:class:`~typing.NamedTuple`); |
| 90 |
* base classes. |
| 91 |
|
| 92 |
.. code-block:: python |
| 93 |
|
| 94 |
# base class example |
| 95 |
from __future__ import annotations |
| 96 |
|
| 97 |
class A(tuple['B', 'C']): ... # String literal types needed here |
| 98 |
class B: ... |
| 99 |
class C: ... |
| 100 |
|
| 101 |
.. warning:: |
| 102 |
|
| 103 |
Some libraries may have use cases for dynamic evaluation of annotations, for |
| 104 |
instance, through use of ``typing.get_type_hints`` or ``eval``. If your |
| 105 |
annotation would raise an error when evaluated (say by using :pep:`604` |
| 106 |
syntax with Python 3.9), you may need to be careful when using such |
| 107 |
libraries. |
| 108 |
|
| 109 |
.. _typing-type-checking: |
| 110 |
|
| 111 |
typing.TYPE_CHECKING |
| 112 |
-------------------- |
| 113 |
|
| 114 |
The :py:mod:`typing` module defines a :py:data:`~typing.TYPE_CHECKING` constant |
| 115 |
that is ``False`` at runtime but treated as ``True`` while type checking. |
| 116 |
|
| 117 |
Since code inside ``if TYPE_CHECKING:`` is not executed at runtime, it provides |
| 118 |
a convenient way to tell mypy something without the code being evaluated at |
| 119 |
runtime. This is most useful for resolving :ref:`import cycles <import-cycles>`. |
| 120 |
|
| 121 |
.. _forward-references: |
| 122 |
|
| 123 |
Class name forward references |
| 124 |
----------------------------- |
| 125 |
|
| 126 |
Python does not allow references to a class object before the class is |
| 127 |
defined (aka forward reference). Thus this code does not work as expected: |
| 128 |
|
| 129 |
.. code-block:: python |
| 130 |
|
| 131 |
def f(x: A) -> None: ... # NameError: name "A" is not defined |
| 132 |
class A: ... |
| 133 |
|
| 134 |
Starting from Python 3.7, you can add ``from __future__ import annotations`` to |
| 135 |
resolve this, as discussed earlier: |
| 136 |
|
| 137 |
.. code-block:: python |
| 138 |
|
| 139 |
from __future__ import annotations |
| 140 |
|
| 141 |
def f(x: A) -> None: ... # OK |
| 142 |
class A: ... |
| 143 |
|
| 144 |
For Python 3.6 and below, you can enter the type as a string literal or type comment: |
| 145 |
|
| 146 |
.. code-block:: python |
| 147 |
|
| 148 |
def f(x: 'A') -> None: ... # OK |
| 149 |
|
| 150 |
# Also OK |
| 151 |
def g(x): # type: (A) -> None |
| 152 |
... |
| 153 |
|
| 154 |
class A: ... |
| 155 |
|
| 156 |
Of course, instead of using future annotations import or string literal types, |
| 157 |
you could move the function definition after the class definition. This is not |
| 158 |
always desirable or even possible, though. |
| 159 |
|
| 160 |
.. _import-cycles: |
| 161 |
|
| 162 |
Import cycles |
| 163 |
------------- |
| 164 |
|
| 165 |
An import cycle occurs where module A imports module B and module B |
| 166 |
imports module A (perhaps indirectly, e.g. ``A -> B -> C -> A``). |
| 167 |
Sometimes in order to add type annotations you have to add extra |
| 168 |
imports to a module and those imports cause cycles that didn't exist |
| 169 |
before. This can lead to errors at runtime like: |
| 170 |
|
| 171 |
.. code-block:: text |
| 172 |
|
| 173 |
ImportError: cannot import name 'b' from partially initialized module 'A' (most likely due to a circular import) |
| 174 |
|
| 175 |
If those cycles do become a problem when running your program, there's a trick: |
| 176 |
if the import is only needed for type annotations and you're using a) the |
| 177 |
:ref:`future annotations import<future-annotations>`, or b) string literals or type |
| 178 |
comments for the relevant annotations, you can write the imports inside ``if |
| 179 |
TYPE_CHECKING:`` so that they are not executed at runtime. Example: |
| 180 |
|
| 181 |
File ``foo.py``: |
| 182 |
|
| 183 |
.. code-block:: python |
| 184 |
|
| 185 |
from typing import TYPE_CHECKING |
| 186 |
|
| 187 |
if TYPE_CHECKING: |
| 188 |
import bar |
| 189 |
|
| 190 |
def listify(arg: 'bar.BarClass') -> 'list[bar.BarClass]': |
| 191 |
return [arg] |
| 192 |
|
| 193 |
File ``bar.py``: |
| 194 |
|
| 195 |
.. code-block:: python |
| 196 |
|
| 197 |
from foo import listify |
| 198 |
|
| 199 |
class BarClass: |
| 200 |
def listifyme(self) -> 'list[BarClass]': |
| 201 |
return listify(self) |
| 202 |
|
| 203 |
.. _not-generic-runtime: |
| 204 |
|
| 205 |
Using classes that are generic in stubs but not at runtime |
| 206 |
---------------------------------------------------------- |
| 207 |
|
| 208 |
Some classes are declared as :ref:`generic<generic-classes>` in stubs, but not |
| 209 |
at runtime. |
| 210 |
|
| 211 |
In Python 3.8 and earlier, there are several examples within the standard library, |
| 212 |
for instance, :py:class:`os.PathLike` and :py:class:`queue.Queue`. Subscripting |
| 213 |
such a class will result in a runtime error: |
| 214 |
|
| 215 |
.. code-block:: python |
| 216 |
|
| 217 |
from queue import Queue |
| 218 |
|
| 219 |
class Tasks(Queue[str]): # TypeError: 'type' object is not subscriptable |
| 220 |
... |
| 221 |
|
| 222 |
results: Queue[int] = Queue() # TypeError: 'type' object is not subscriptable |
| 223 |
|
| 224 |
To avoid errors from use of these generics in annotations, just use the |
| 225 |
:ref:`future annotations import<future-annotations>` (or string literals or type |
| 226 |
comments for Python 3.6 and below). |
| 227 |
|
| 228 |
To avoid errors when inheriting from these classes, things are a little more |
| 229 |
complicated and you need to use :ref:`typing.TYPE_CHECKING |
| 230 |
<typing-type-checking>`: |
| 231 |
|
| 232 |
.. code-block:: python |
| 233 |
|
| 234 |
from typing import TYPE_CHECKING |
| 235 |
from queue import Queue |
| 236 |
|
| 237 |
if TYPE_CHECKING: |
| 238 |
BaseQueue = Queue[str] # this is only processed by mypy |
| 239 |
else: |
| 240 |
BaseQueue = Queue # this is not seen by mypy but will be executed at runtime |
| 241 |
|
| 242 |
class Tasks(BaseQueue): # OK |
| 243 |
... |
| 244 |
|
| 245 |
task_queue: Tasks |
| 246 |
reveal_type(task_queue.get()) # Reveals str |
| 247 |
|
| 248 |
If your subclass is also generic, you can use the following (using the |
| 249 |
legacy syntax for generic classes): |
| 250 |
|
| 251 |
.. code-block:: python |
| 252 |
|
| 253 |
from typing import TYPE_CHECKING, TypeVar, Generic |
| 254 |
from queue import Queue |
| 255 |
|
| 256 |
_T = TypeVar("_T") |
| 257 |
if TYPE_CHECKING: |
| 258 |
class _MyQueueBase(Queue[_T]): pass |
| 259 |
else: |
| 260 |
class _MyQueueBase(Generic[_T], Queue): pass |
| 261 |
|
| 262 |
class MyQueue(_MyQueueBase[_T]): pass |
| 263 |
|
| 264 |
task_queue: MyQueue[str] |
| 265 |
reveal_type(task_queue.get()) # Reveals str |
| 266 |
|
| 267 |
In Python 3.9 and later, we can just inherit directly from ``Queue[str]`` or ``Queue[T]`` |
| 268 |
since its :py:class:`queue.Queue` implements :py:meth:`~object.__class_getitem__`, so |
| 269 |
the class object can be subscripted at runtime. You may still encounter issues (even if |
| 270 |
you use a recent Python version) when subclassing generic classes defined in third-party |
| 271 |
libraries if types are generic only in stubs. |
| 272 |
|
| 273 |
Using types defined in stubs but not at runtime |
| 274 |
----------------------------------------------- |
| 275 |
|
| 276 |
Sometimes stubs that you're using may define types you wish to reuse that do |
| 277 |
not exist at runtime. Importing these types naively will cause your code to fail |
| 278 |
at runtime with ``ImportError`` or ``ModuleNotFoundError``. Similar to previous |
| 279 |
sections, these can be dealt with by using :ref:`typing.TYPE_CHECKING |
| 280 |
<typing-type-checking>`: |
| 281 |
|
| 282 |
.. code-block:: python |
| 283 |
|
| 284 |
from __future__ import annotations |
| 285 |
from typing import TYPE_CHECKING |
| 286 |
if TYPE_CHECKING: |
| 287 |
from _typeshed import SupportsRichComparison |
| 288 |
|
| 289 |
def f(x: SupportsRichComparison) -> None |
| 290 |
|
| 291 |
The ``from __future__ import annotations`` is required to avoid |
| 292 |
a ``NameError`` when using the imported symbol. |
| 293 |
For more information and caveats, see the section on |
| 294 |
:ref:`future annotations <future-annotations>`. |
| 295 |
|
| 296 |
.. _generic-builtins: |
| 297 |
|
| 298 |
Using generic builtins |
| 299 |
---------------------- |
| 300 |
|
| 301 |
Starting with Python 3.9 (:pep:`585`), the type objects of many collections in |
| 302 |
the standard library support subscription at runtime. This means that you no |
| 303 |
longer have to import the equivalents from :py:mod:`typing`; you can simply use |
| 304 |
the built-in collections or those from :py:mod:`collections.abc`: |
| 305 |
|
| 306 |
.. code-block:: python |
| 307 |
|
| 308 |
from collections.abc import Sequence |
| 309 |
x: list[str] |
| 310 |
y: dict[int, str] |
| 311 |
z: Sequence[str] = x |
| 312 |
|
| 313 |
There is limited support for using this syntax in Python 3.7 and later as well: |
| 314 |
if you use ``from __future__ import annotations``, mypy will understand this |
| 315 |
syntax in annotations. However, since this will not be supported by the Python |
| 316 |
interpreter at runtime, make sure you're aware of the caveats mentioned in the |
| 317 |
notes at :ref:`future annotations import<future-annotations>`. |
| 318 |
|
| 319 |
Using X | Y syntax for Unions |
| 320 |
----------------------------- |
| 321 |
|
| 322 |
Starting with Python 3.10 (:pep:`604`), you can spell union types as |
| 323 |
``x: int | str``, instead of ``x: typing.Union[int, str]``. |
| 324 |
|
| 325 |
There is limited support for using this syntax in Python 3.7 and later as well: |
| 326 |
if you use ``from __future__ import annotations``, mypy will understand this |
| 327 |
syntax in annotations, string literal types, type comments and stub files. |
| 328 |
However, since this will not be supported by the Python interpreter at runtime |
| 329 |
(if evaluated, ``int | str`` will raise ``TypeError: unsupported operand type(s) |
| 330 |
for |: 'type' and 'type'``), make sure you're aware of the caveats mentioned in |
| 331 |
the notes at :ref:`future annotations import<future-annotations>`. |
| 332 |
|
| 333 |
Using new additions to the typing module |
| 334 |
---------------------------------------- |
| 335 |
|
| 336 |
You may find yourself wanting to use features added to the :py:mod:`typing` |
| 337 |
module in earlier versions of Python than the addition. |
| 338 |
|
| 339 |
The easiest way to do this is to install and use the ``typing_extensions`` |
| 340 |
package from PyPI for the relevant imports, for example: |
| 341 |
|
| 342 |
.. code-block:: python |
| 343 |
|
| 344 |
from typing_extensions import TypeIs |
| 345 |
|
| 346 |
If you don't want to rely on ``typing_extensions`` being installed on newer |
| 347 |
Pythons, you could alternatively use: |
| 348 |
|
| 349 |
.. code-block:: python |
| 350 |
|
| 351 |
import sys |
| 352 |
if sys.version_info >= (3, 13): |
| 353 |
from typing import TypeIs |
| 354 |
else: |
| 355 |
from typing_extensions import TypeIs |
| 356 |
|
| 357 |
This plays nicely well with following :pep:`508` dependency specification: |
| 358 |
``typing_extensions; python_version<"3.13"`` |