| 1 |
Generics |
| 2 |
======== |
| 3 |
|
| 4 |
This section explains how you can define your own generic classes that take |
| 5 |
one or more type arguments, similar to built-in types such as ``list[T]``. |
| 6 |
User-defined generics are a moderately advanced feature and you can get far |
| 7 |
without ever using them -- feel free to skip this section and come back later. |
| 8 |
|
| 9 |
.. _generic-classes: |
| 10 |
|
| 11 |
Defining generic classes |
| 12 |
************************ |
| 13 |
|
| 14 |
The built-in collection classes are generic classes. Generic types |
| 15 |
accept one or more type arguments within ``[...]``, which can be |
| 16 |
arbitrary types. For example, the type ``dict[int, str]`` has the |
| 17 |
type arguments ``int`` and ``str``, and ``list[int]`` has the type |
| 18 |
argument ``int``. |
| 19 |
|
| 20 |
Programs can also define new generic classes. Here is a very simple |
| 21 |
generic class that represents a stack (using the syntax introduced in |
| 22 |
Python 3.12): |
| 23 |
|
| 24 |
.. code-block:: python |
| 25 |
|
| 26 |
class Stack[T]: |
| 27 |
def __init__(self) -> None: |
| 28 |
# Create an empty list with items of type T |
| 29 |
self.items: list[T] = [] |
| 30 |
|
| 31 |
def push(self, item: T) -> None: |
| 32 |
self.items.append(item) |
| 33 |
|
| 34 |
def pop(self) -> T: |
| 35 |
return self.items.pop() |
| 36 |
|
| 37 |
def empty(self) -> bool: |
| 38 |
return not self.items |
| 39 |
|
| 40 |
There are two syntax variants for defining generic classes in Python. |
| 41 |
Python 3.12 introduced a |
| 42 |
`new dedicated syntax <https://docs.python.org/3/whatsnew/3.12.html#pep-695-type-parameter-syntax>`_ |
| 43 |
for defining generic classes (and also functions and type aliases, which |
| 44 |
we will discuss later). The above example used the new syntax. Most examples are |
| 45 |
given using both the new and the old (or legacy) syntax variants. |
| 46 |
Unless mentioned otherwise, they work the same -- but the new syntax |
| 47 |
is more readable and more convenient. |
| 48 |
|
| 49 |
Here is the same example using the old syntax (required for Python 3.11 |
| 50 |
and earlier, but also supported on newer Python versions): |
| 51 |
|
| 52 |
.. code-block:: python |
| 53 |
|
| 54 |
from typing import TypeVar, Generic |
| 55 |
|
| 56 |
T = TypeVar('T') # Define type variable "T" |
| 57 |
|
| 58 |
class Stack(Generic[T]): |
| 59 |
def __init__(self) -> None: |
| 60 |
# Create an empty list with items of type T |
| 61 |
self.items: list[T] = [] |
| 62 |
|
| 63 |
def push(self, item: T) -> None: |
| 64 |
self.items.append(item) |
| 65 |
|
| 66 |
def pop(self) -> T: |
| 67 |
return self.items.pop() |
| 68 |
|
| 69 |
def empty(self) -> bool: |
| 70 |
return not self.items |
| 71 |
|
| 72 |
.. note:: |
| 73 |
|
| 74 |
There are currently no plans to deprecate the legacy syntax. |
| 75 |
You can freely mix code using the new and old syntax variants, |
| 76 |
even within a single file (but *not* within a single class). |
| 77 |
|
| 78 |
The ``Stack`` class can be used to represent a stack of any type: |
| 79 |
``Stack[int]``, ``Stack[tuple[int, str]]``, etc. You can think of |
| 80 |
``Stack[int]`` as referring to the definition of ``Stack`` above, |
| 81 |
but with all instances of ``T`` replaced with ``int``. |
| 82 |
|
| 83 |
Using ``Stack`` is similar to built-in container types: |
| 84 |
|
| 85 |
.. code-block:: python |
| 86 |
|
| 87 |
# Construct an empty Stack[int] instance |
| 88 |
stack = Stack[int]() |
| 89 |
stack.push(2) |
| 90 |
stack.pop() |
| 91 |
|
| 92 |
# error: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int" |
| 93 |
stack.push('x') |
| 94 |
|
| 95 |
stack2: Stack[str] = Stack() |
| 96 |
stack2.push('x') |
| 97 |
|
| 98 |
Construction of instances of generic types is type checked (Python 3.12 syntax): |
| 99 |
|
| 100 |
.. code-block:: python |
| 101 |
|
| 102 |
class Box[T]: |
| 103 |
def __init__(self, content: T) -> None: |
| 104 |
self.content = content |
| 105 |
|
| 106 |
Box(1) # OK, inferred type is Box[int] |
| 107 |
Box[int](1) # Also OK |
| 108 |
|
| 109 |
# error: Argument 1 to "Box" has incompatible type "str"; expected "int" |
| 110 |
Box[int]('some string') |
| 111 |
|
| 112 |
Here is the definition of ``Box`` using the legacy syntax (Python 3.11 and earlier): |
| 113 |
|
| 114 |
.. code-block:: python |
| 115 |
|
| 116 |
from typing import TypeVar, Generic |
| 117 |
|
| 118 |
T = TypeVar('T') |
| 119 |
|
| 120 |
class Box(Generic[T]): |
| 121 |
def __init__(self, content: T) -> None: |
| 122 |
self.content = content |
| 123 |
|
| 124 |
.. note:: |
| 125 |
|
| 126 |
Before moving on, let's clarify some terminology. |
| 127 |
The name ``T`` in ``class Stack[T]`` or ``class Stack(Generic[T])`` |
| 128 |
declares a *type parameter* ``T`` (of class ``Stack``). |
| 129 |
``T`` is also called a *type variable*, especially in a type annotation, |
| 130 |
such as in the signature of ``push`` above. |
| 131 |
When the type ``Stack[...]`` is used in a type annotation, the type |
| 132 |
within square brackets is called a *type argument*. |
| 133 |
This is similar to the distinction between function parameters and arguments. |
| 134 |
|
| 135 |
.. _generic-subclasses: |
| 136 |
|
| 137 |
Defining subclasses of generic classes |
| 138 |
************************************** |
| 139 |
|
| 140 |
User-defined generic classes and generic classes defined in :py:mod:`typing` |
| 141 |
can be used as a base class for another class (generic or non-generic). For |
| 142 |
example (Python 3.12 syntax): |
| 143 |
|
| 144 |
.. code-block:: python |
| 145 |
|
| 146 |
from typing import Mapping, Iterator |
| 147 |
|
| 148 |
# This is a generic subclass of Mapping |
| 149 |
class MyMap[KT, VT](Mapping[KT, VT]): |
| 150 |
def __getitem__(self, k: KT) -> VT: ... |
| 151 |
def __iter__(self) -> Iterator[KT]: ... |
| 152 |
def __len__(self) -> int: ... |
| 153 |
|
| 154 |
items: MyMap[str, int] # OK |
| 155 |
|
| 156 |
# This is a non-generic subclass of dict |
| 157 |
class StrDict(dict[str, str]): |
| 158 |
def __str__(self) -> str: |
| 159 |
return f'StrDict({super().__str__()})' |
| 160 |
|
| 161 |
data: StrDict[int, int] # Error! StrDict is not generic |
| 162 |
data2: StrDict # OK |
| 163 |
|
| 164 |
# This is a user-defined generic class |
| 165 |
class Receiver[T]: |
| 166 |
def accept(self, value: T) -> None: ... |
| 167 |
|
| 168 |
# This is a generic subclass of Receiver |
| 169 |
class AdvancedReceiver[T](Receiver[T]): ... |
| 170 |
|
| 171 |
Here is the above example using the legacy syntax (Python 3.11 and earlier): |
| 172 |
|
| 173 |
.. code-block:: python |
| 174 |
|
| 175 |
from typing import Generic, TypeVar, Mapping, Iterator |
| 176 |
|
| 177 |
KT = TypeVar('KT') |
| 178 |
VT = TypeVar('VT') |
| 179 |
|
| 180 |
# This is a generic subclass of Mapping |
| 181 |
class MyMap(Mapping[KT, VT]): |
| 182 |
def __getitem__(self, k: KT) -> VT: ... |
| 183 |
def __iter__(self) -> Iterator[KT]: ... |
| 184 |
def __len__(self) -> int: ... |
| 185 |
|
| 186 |
items: MyMap[str, int] # OK |
| 187 |
|
| 188 |
# This is a non-generic subclass of dict |
| 189 |
class StrDict(dict[str, str]): |
| 190 |
def __str__(self) -> str: |
| 191 |
return f'StrDict({super().__str__()})' |
| 192 |
|
| 193 |
data: StrDict[int, int] # Error! StrDict is not generic |
| 194 |
data2: StrDict # OK |
| 195 |
|
| 196 |
# This is a user-defined generic class |
| 197 |
class Receiver(Generic[T]): |
| 198 |
def accept(self, value: T) -> None: ... |
| 199 |
|
| 200 |
# This is a generic subclass of Receiver |
| 201 |
class AdvancedReceiver(Receiver[T]): ... |
| 202 |
|
| 203 |
.. note:: |
| 204 |
|
| 205 |
You have to add an explicit :py:class:`~collections.abc.Mapping` base class |
| 206 |
if you want mypy to consider a user-defined class as a mapping (and |
| 207 |
:py:class:`~collections.abc.Sequence` for sequences, etc.). This is because |
| 208 |
mypy doesn't use *structural subtyping* for these ABCs, unlike simpler protocols |
| 209 |
like :py:class:`~collections.abc.Iterable`, which use |
| 210 |
:ref:`structural subtyping <protocol-types>`. |
| 211 |
|
| 212 |
When using the legacy syntax, :py:class:`Generic <typing.Generic>` can be omitted |
| 213 |
from bases if there are |
| 214 |
other base classes that include type variables, such as ``Mapping[KT, VT]`` |
| 215 |
in the above example. If you include ``Generic[...]`` in bases, then |
| 216 |
it should list all type variables present in other bases (or more, |
| 217 |
if needed). The order of type parameters is defined by the following |
| 218 |
rules: |
| 219 |
|
| 220 |
* If ``Generic[...]`` is present, then the order of parameters is |
| 221 |
always determined by their order in ``Generic[...]``. |
| 222 |
* If there are no ``Generic[...]`` in bases, then all type parameters |
| 223 |
are collected in the lexicographic order (i.e. by first appearance). |
| 224 |
|
| 225 |
Example: |
| 226 |
|
| 227 |
.. code-block:: python |
| 228 |
|
| 229 |
from typing import Generic, TypeVar, Any |
| 230 |
|
| 231 |
T = TypeVar('T') |
| 232 |
S = TypeVar('S') |
| 233 |
U = TypeVar('U') |
| 234 |
|
| 235 |
class One(Generic[T]): ... |
| 236 |
class Another(Generic[T]): ... |
| 237 |
|
| 238 |
class First(One[T], Another[S]): ... |
| 239 |
class Second(One[T], Another[S], Generic[S, U, T]): ... |
| 240 |
|
| 241 |
x: First[int, str] # Here T is bound to int, S is bound to str |
| 242 |
y: Second[int, str, Any] # Here T is Any, S is int, and U is str |
| 243 |
|
| 244 |
When using the Python 3.12 syntax, all type parameters must always be |
| 245 |
explicitly defined immediately after the class name within ``[...]``, and the |
| 246 |
``Generic[...]`` base class is never used. |
| 247 |
|
| 248 |
.. _generic-functions: |
| 249 |
|
| 250 |
Generic functions |
| 251 |
***************** |
| 252 |
|
| 253 |
Functions can also be generic, i.e. they can have type parameters (Python 3.12 syntax): |
| 254 |
|
| 255 |
.. code-block:: python |
| 256 |
|
| 257 |
from collections.abc import Sequence |
| 258 |
|
| 259 |
# A generic function! |
| 260 |
def first[T](seq: Sequence[T]) -> T: |
| 261 |
return seq[0] |
| 262 |
|
| 263 |
Here is the same example using the legacy syntax (Python 3.11 and earlier): |
| 264 |
|
| 265 |
.. code-block:: python |
| 266 |
|
| 267 |
from typing import TypeVar, Sequence |
| 268 |
|
| 269 |
T = TypeVar('T') |
| 270 |
|
| 271 |
# A generic function! |
| 272 |
def first(seq: Sequence[T]) -> T: |
| 273 |
return seq[0] |
| 274 |
|
| 275 |
As with generic classes, the type parameter ``T`` can be replaced with any |
| 276 |
type. That means ``first`` can be passed an argument with any sequence type, |
| 277 |
and the return type is derived from the sequence item type. Example: |
| 278 |
|
| 279 |
.. code-block:: python |
| 280 |
|
| 281 |
reveal_type(first([1, 2, 3])) # Revealed type is "builtins.int" |
| 282 |
reveal_type(first(('a', 'b'))) # Revealed type is "builtins.str" |
| 283 |
|
| 284 |
When using the legacy syntax, a single definition of a type variable |
| 285 |
(such as ``T`` above) can be used in multiple generic functions or |
| 286 |
classes. In this example we use the same type variable in two generic |
| 287 |
functions to declare type parameters: |
| 288 |
|
| 289 |
.. code-block:: python |
| 290 |
|
| 291 |
from typing import TypeVar, Sequence |
| 292 |
|
| 293 |
T = TypeVar('T') # Define type variable |
| 294 |
|
| 295 |
def first(seq: Sequence[T]) -> T: |
| 296 |
return seq[0] |
| 297 |
|
| 298 |
def last(seq: Sequence[T]) -> T: |
| 299 |
return seq[-1] |
| 300 |
|
| 301 |
Since the Python 3.12 syntax is more concise, it doesn't need (or have) |
| 302 |
an equivalent way of sharing type parameter definitions. |
| 303 |
|
| 304 |
A variable cannot have a type variable in its type unless the type |
| 305 |
variable is bound in a containing generic class or function. |
| 306 |
|
| 307 |
When calling a generic function, you can't explicitly pass the values of |
| 308 |
type parameters as type arguments. The values of type parameters are always |
| 309 |
inferred by mypy. This is not valid: |
| 310 |
|
| 311 |
.. code-block:: python |
| 312 |
|
| 313 |
first[int]([1, 2]) # Error: can't use [...] with generic function |
| 314 |
|
| 315 |
If you really need this, you can define a generic class with a ``__call__`` |
| 316 |
method. |
| 317 |
|
| 318 |
.. _type-variable-upper-bound: |
| 319 |
|
| 320 |
Type variables with upper bounds |
| 321 |
******************************** |
| 322 |
|
| 323 |
A type variable can also be restricted to having values that are |
| 324 |
subtypes of a specific type. This type is called the upper bound of |
| 325 |
the type variable, and it is specified using ``T: <bound>`` when using the |
| 326 |
Python 3.12 syntax. In the definition of a generic function or a generic |
| 327 |
class that uses such a type variable ``T``, the type represented by ``T`` |
| 328 |
is assumed to be a subtype of its upper bound, so you can use methods |
| 329 |
of the upper bound on values of type ``T`` (Python 3.12 syntax): |
| 330 |
|
| 331 |
.. code-block:: python |
| 332 |
|
| 333 |
from typing import SupportsAbs |
| 334 |
|
| 335 |
def max_by_abs[T: SupportsAbs[float]](*xs: T) -> T: |
| 336 |
# We can use abs(), because T is a subtype of SupportsAbs[float]. |
| 337 |
return max(xs, key=abs) |
| 338 |
|
| 339 |
An upper bound can also be specified with the ``bound=...`` keyword |
| 340 |
argument to :py:class:`~typing.TypeVar`. |
| 341 |
Here is the example using the legacy syntax (Python 3.11 and earlier): |
| 342 |
|
| 343 |
.. code-block:: python |
| 344 |
|
| 345 |
from typing import TypeVar, SupportsAbs |
| 346 |
|
| 347 |
T = TypeVar('T', bound=SupportsAbs[float]) |
| 348 |
|
| 349 |
def max_by_abs(*xs: T) -> T: |
| 350 |
return max(xs, key=abs) |
| 351 |
|
| 352 |
In a call to such a function, the type ``T`` must be replaced by a |
| 353 |
type that is a subtype of its upper bound. Continuing the example |
| 354 |
above: |
| 355 |
|
| 356 |
.. code-block:: python |
| 357 |
|
| 358 |
max_by_abs(-3.5, 2) # Okay, has type 'float' |
| 359 |
max_by_abs(5+6j, 7) # Okay, has type 'complex' |
| 360 |
max_by_abs('a', 'b') # Error: 'str' is not a subtype of SupportsAbs[float] |
| 361 |
|
| 362 |
Type parameters of generic classes may also have upper bounds, which |
| 363 |
restrict the valid values for the type parameter in the same way. |
| 364 |
|
| 365 |
.. _generic-methods-and-generic-self: |
| 366 |
|
| 367 |
Generic methods and generic self |
| 368 |
******************************** |
| 369 |
|
| 370 |
You can also define generic methods. In |
| 371 |
particular, the ``self`` parameter may also be generic, allowing a |
| 372 |
method to return the most precise type known at the point of access. |
| 373 |
In this way, for example, you can type check a chain of setter |
| 374 |
methods (Python 3.12 syntax): |
| 375 |
|
| 376 |
.. code-block:: python |
| 377 |
|
| 378 |
class Shape: |
| 379 |
def set_scale[T: Shape](self: T, scale: float) -> T: |
| 380 |
self.scale = scale |
| 381 |
return self |
| 382 |
|
| 383 |
class Circle(Shape): |
| 384 |
def set_radius(self, r: float) -> 'Circle': |
| 385 |
self.radius = r |
| 386 |
return self |
| 387 |
|
| 388 |
class Square(Shape): |
| 389 |
def set_width(self, w: float) -> 'Square': |
| 390 |
self.width = w |
| 391 |
return self |
| 392 |
|
| 393 |
circle: Circle = Circle().set_scale(0.5).set_radius(2.7) |
| 394 |
square: Square = Square().set_scale(0.5).set_width(3.2) |
| 395 |
|
| 396 |
Without using generic ``self``, the last two lines could not be type |
| 397 |
checked properly, since the return type of ``set_scale`` would be |
| 398 |
``Shape``, which doesn't define ``set_radius`` or ``set_width``. |
| 399 |
|
| 400 |
When using the legacy syntax, just use a type variable in the |
| 401 |
method signature that is different from class type parameters (if any |
| 402 |
are defined). Here is the above example using the legacy |
| 403 |
syntax (3.11 and earlier): |
| 404 |
|
| 405 |
.. code-block:: python |
| 406 |
|
| 407 |
from typing import TypeVar |
| 408 |
|
| 409 |
T = TypeVar('T', bound='Shape') |
| 410 |
|
| 411 |
class Shape: |
| 412 |
def set_scale(self: T, scale: float) -> T: |
| 413 |
self.scale = scale |
| 414 |
return self |
| 415 |
|
| 416 |
class Circle(Shape): |
| 417 |
def set_radius(self, r: float) -> 'Circle': |
| 418 |
self.radius = r |
| 419 |
return self |
| 420 |
|
| 421 |
class Square(Shape): |
| 422 |
def set_width(self, w: float) -> 'Square': |
| 423 |
self.width = w |
| 424 |
return self |
| 425 |
|
| 426 |
circle: Circle = Circle().set_scale(0.5).set_radius(2.7) |
| 427 |
square: Square = Square().set_scale(0.5).set_width(3.2) |
| 428 |
|
| 429 |
Other uses include factory methods, such as copy and deserialization methods. |
| 430 |
For class methods, you can also define generic ``cls``, using ``type[T]`` |
| 431 |
or :py:class:`Type[T] <typing.Type>` (Python 3.12 syntax): |
| 432 |
|
| 433 |
.. code-block:: python |
| 434 |
|
| 435 |
class Friend: |
| 436 |
other: "Friend | None" = None |
| 437 |
|
| 438 |
@classmethod |
| 439 |
def make_pair[T: Friend](cls: type[T]) -> tuple[T, T]: |
| 440 |
a, b = cls(), cls() |
| 441 |
a.other = b |
| 442 |
b.other = a |
| 443 |
return a, b |
| 444 |
|
| 445 |
class SuperFriend(Friend): |
| 446 |
pass |
| 447 |
|
| 448 |
a, b = SuperFriend.make_pair() |
| 449 |
|
| 450 |
Here is the same example using the legacy syntax (3.11 and earlier): |
| 451 |
|
| 452 |
.. code-block:: python |
| 453 |
|
| 454 |
from typing import TypeVar |
| 455 |
|
| 456 |
T = TypeVar('T', bound='Friend') |
| 457 |
|
| 458 |
class Friend: |
| 459 |
other: "Friend | None" = None |
| 460 |
|
| 461 |
@classmethod |
| 462 |
def make_pair(cls: type[T]) -> tuple[T, T]: |
| 463 |
a, b = cls(), cls() |
| 464 |
a.other = b |
| 465 |
b.other = a |
| 466 |
return a, b |
| 467 |
|
| 468 |
class SuperFriend(Friend): |
| 469 |
pass |
| 470 |
|
| 471 |
a, b = SuperFriend.make_pair() |
| 472 |
|
| 473 |
Note that when overriding a method with generic ``self``, you must either |
| 474 |
return a generic ``self`` too, or return an instance of the current class. |
| 475 |
In the latter case, you must implement this method in all future subclasses. |
| 476 |
|
| 477 |
Note also that mypy cannot always verify that the implementation of a copy |
| 478 |
or a deserialization method returns the actual type of self. Therefore |
| 479 |
you may need to silence mypy inside these methods (but not at the call site), |
| 480 |
possibly by making use of the ``Any`` type or a ``# type: ignore`` comment. |
| 481 |
|
| 482 |
Mypy lets you use generic self types in certain unsafe ways |
| 483 |
in order to support common idioms. For example, using a generic |
| 484 |
self type in an argument type is accepted even though it's unsafe (Python 3.12 |
| 485 |
syntax): |
| 486 |
|
| 487 |
.. code-block:: python |
| 488 |
|
| 489 |
class Base: |
| 490 |
def compare[T: Base](self: T, other: T) -> bool: |
| 491 |
return False |
| 492 |
|
| 493 |
class Sub(Base): |
| 494 |
def __init__(self, x: int) -> None: |
| 495 |
self.x = x |
| 496 |
|
| 497 |
# This is unsafe (see below) but allowed because it's |
| 498 |
# a common pattern and rarely causes issues in practice. |
| 499 |
def compare(self, other: 'Sub') -> bool: |
| 500 |
return self.x > other.x |
| 501 |
|
| 502 |
b: Base = Sub(42) |
| 503 |
b.compare(Base()) # Runtime error here: 'Base' object has no attribute 'x' |
| 504 |
|
| 505 |
For some advanced uses of self types, see :ref:`additional examples <advanced_self>`. |
| 506 |
|
| 507 |
Automatic self types using typing.Self |
| 508 |
************************************** |
| 509 |
|
| 510 |
Since the patterns described above are quite common, mypy supports a |
| 511 |
simpler syntax, introduced in :pep:`673`, to make them easier to use. |
| 512 |
Instead of introducing a type parameter and using an explicit annotation |
| 513 |
for ``self``, you can import the special type ``typing.Self`` that is |
| 514 |
automatically transformed into a method-level type parameter with the |
| 515 |
current class as the upper bound, and you don't need an annotation for |
| 516 |
``self`` (or ``cls`` in class methods). The example from the previous |
| 517 |
section can be made simpler by using ``Self``: |
| 518 |
|
| 519 |
.. code-block:: python |
| 520 |
|
| 521 |
from typing import Self |
| 522 |
|
| 523 |
class Friend: |
| 524 |
other: Self | None = None |
| 525 |
|
| 526 |
@classmethod |
| 527 |
def make_pair(cls) -> tuple[Self, Self]: |
| 528 |
a, b = cls(), cls() |
| 529 |
a.other = b |
| 530 |
b.other = a |
| 531 |
return a, b |
| 532 |
|
| 533 |
class SuperFriend(Friend): |
| 534 |
pass |
| 535 |
|
| 536 |
a, b = SuperFriend.make_pair() |
| 537 |
|
| 538 |
This is more compact than using explicit type parameters. Also, you can |
| 539 |
use ``Self`` in attribute annotations in addition to methods. |
| 540 |
|
| 541 |
.. note:: |
| 542 |
|
| 543 |
To use this feature on Python versions earlier than 3.11, you will need to |
| 544 |
import ``Self`` from ``typing_extensions`` (version 4.0 or newer). |
| 545 |
|
| 546 |
.. _variance-of-generics: |
| 547 |
|
| 548 |
Variance of generic types |
| 549 |
************************* |
| 550 |
|
| 551 |
There are three main kinds of generic types with respect to subtype |
| 552 |
relations between them: invariant, covariant, and contravariant. |
| 553 |
Assuming that we have a pair of types ``A`` and ``B``, and ``B`` is |
| 554 |
a subtype of ``A``, these are defined as follows: |
| 555 |
|
| 556 |
* A generic class ``MyCovGen[T]`` is called covariant in type variable |
| 557 |
``T`` if ``MyCovGen[B]`` is always a subtype of ``MyCovGen[A]``. |
| 558 |
* A generic class ``MyContraGen[T]`` is called contravariant in type |
| 559 |
variable ``T`` if ``MyContraGen[A]`` is always a subtype of |
| 560 |
``MyContraGen[B]``. |
| 561 |
* A generic class ``MyInvGen[T]`` is called invariant in ``T`` if neither |
| 562 |
of the above is true. |
| 563 |
|
| 564 |
Let us illustrate this by few simple examples: |
| 565 |
|
| 566 |
.. code-block:: python |
| 567 |
|
| 568 |
# We'll use these classes in the examples below |
| 569 |
class Shape: ... |
| 570 |
class Triangle(Shape): ... |
| 571 |
class Square(Shape): ... |
| 572 |
|
| 573 |
* Most immutable container types, such as :py:class:`~collections.abc.Sequence` |
| 574 |
and :py:class:`~frozenset` are covariant. Union types are |
| 575 |
also covariant in all union items: ``Triangle | int`` is |
| 576 |
a subtype of ``Shape | int``. |
| 577 |
|
| 578 |
.. code-block:: python |
| 579 |
|
| 580 |
def count_lines(shapes: Sequence[Shape]) -> int: |
| 581 |
return sum(shape.num_sides for shape in shapes) |
| 582 |
|
| 583 |
triangles: Sequence[Triangle] |
| 584 |
count_lines(triangles) # OK |
| 585 |
|
| 586 |
def foo(triangle: Triangle, num: int) -> None: |
| 587 |
shape_or_number: Union[Shape, int] |
| 588 |
# a Triangle is a Shape, and a Shape is a valid Union[Shape, int] |
| 589 |
shape_or_number = triangle |
| 590 |
|
| 591 |
Covariance should feel relatively intuitive, but contravariance and invariance |
| 592 |
can be harder to reason about. |
| 593 |
|
| 594 |
* :py:class:`~collections.abc.Callable` is an example of type that behaves contravariant |
| 595 |
in types of arguments. That is, ``Callable[[Shape], int]`` is a subtype of |
| 596 |
``Callable[[Triangle], int]``, despite ``Shape`` being a supertype of |
| 597 |
``Triangle``. To understand this, consider: |
| 598 |
|
| 599 |
.. code-block:: python |
| 600 |
|
| 601 |
def cost_of_paint_required( |
| 602 |
triangle: Triangle, |
| 603 |
area_calculator: Callable[[Triangle], float] |
| 604 |
) -> float: |
| 605 |
return area_calculator(triangle) * DOLLAR_PER_SQ_FT |
| 606 |
|
| 607 |
# This straightforwardly works |
| 608 |
def area_of_triangle(triangle: Triangle) -> float: ... |
| 609 |
cost_of_paint_required(triangle, area_of_triangle) # OK |
| 610 |
|
| 611 |
# But this works as well! |
| 612 |
def area_of_any_shape(shape: Shape) -> float: ... |
| 613 |
cost_of_paint_required(triangle, area_of_any_shape) # OK |
| 614 |
|
| 615 |
``cost_of_paint_required`` needs a callable that can calculate the area of a |
| 616 |
triangle. If we give it a callable that can calculate the area of an |
| 617 |
arbitrary shape (not just triangles), everything still works. |
| 618 |
|
| 619 |
* ``list`` is an invariant generic type. Naively, one would think |
| 620 |
that it is covariant, like :py:class:`~collections.abc.Sequence` above, but consider this code: |
| 621 |
|
| 622 |
.. code-block:: python |
| 623 |
|
| 624 |
class Circle(Shape): |
| 625 |
# The rotate method is only defined on Circle, not on Shape |
| 626 |
def rotate(self): ... |
| 627 |
|
| 628 |
def add_one(things: list[Shape]) -> None: |
| 629 |
things.append(Shape()) |
| 630 |
|
| 631 |
my_circles: list[Circle] = [] |
| 632 |
add_one(my_circles) # This may appear safe, but... |
| 633 |
my_circles[0].rotate() # ...this will fail, since my_circles[0] is now a Shape, not a Circle |
| 634 |
|
| 635 |
Another example of invariant type is ``dict``. Most mutable containers |
| 636 |
are invariant. |
| 637 |
|
| 638 |
When using the Python 3.12 syntax for generics, mypy will automatically |
| 639 |
infer the most flexible variance for each class type variable. Here |
| 640 |
``Box`` will be inferred as covariant: |
| 641 |
|
| 642 |
.. code-block:: python |
| 643 |
|
| 644 |
class Box[T]: # this type is implicitly covariant |
| 645 |
def __init__(self, content: T) -> None: |
| 646 |
self._content = content |
| 647 |
|
| 648 |
def get_content(self) -> T: |
| 649 |
return self._content |
| 650 |
|
| 651 |
def look_into(box: Box[Shape]): ... |
| 652 |
|
| 653 |
my_box = Box(Square()) |
| 654 |
look_into(my_box) # OK, but mypy would complain here for an invariant type |
| 655 |
|
| 656 |
Here the underscore prefix for ``_content`` is significant. Without an |
| 657 |
underscore prefix, the class would be invariant, as the attribute would |
| 658 |
be understood as a public, mutable attribute (a single underscore prefix |
| 659 |
has no special significance for mypy in most other contexts). By declaring |
| 660 |
the attribute as ``Final``, the class could still be made covariant: |
| 661 |
|
| 662 |
.. code-block:: python |
| 663 |
|
| 664 |
from typing import Final |
| 665 |
|
| 666 |
class Box[T]: # this type is implicitly covariant |
| 667 |
def __init__(self, content: T) -> None: |
| 668 |
self.content: Final = content |
| 669 |
|
| 670 |
def get_content(self) -> T: |
| 671 |
return self.content |
| 672 |
|
| 673 |
When using the legacy syntax, mypy assumes that all user-defined generics |
| 674 |
are invariant by default. To declare a given generic class as covariant or |
| 675 |
contravariant, use type variables defined with special keyword arguments |
| 676 |
``covariant`` or ``contravariant``. For example (Python 3.11 or earlier): |
| 677 |
|
| 678 |
.. code-block:: python |
| 679 |
|
| 680 |
from typing import Generic, TypeVar |
| 681 |
|
| 682 |
T_co = TypeVar('T_co', covariant=True) |
| 683 |
|
| 684 |
class Box(Generic[T_co]): # this type is declared covariant |
| 685 |
def __init__(self, content: T_co) -> None: |
| 686 |
self._content = content |
| 687 |
|
| 688 |
def get_content(self) -> T_co: |
| 689 |
return self._content |
| 690 |
|
| 691 |
def look_into(box: Box[Shape]): ... |
| 692 |
|
| 693 |
my_box = Box(Square()) |
| 694 |
look_into(my_box) # OK, but mypy would complain here for an invariant type |
| 695 |
|
| 696 |
.. _value-constrained-type-variables: |
| 697 |
.. _type-variable-value-restriction: |
| 698 |
|
| 699 |
Value-constrained type variables |
| 700 |
********************************* |
| 701 |
|
| 702 |
By default, a type variable can be replaced with any type -- or any type that |
| 703 |
is a subtype of the upper bound, which defaults to ``object``. However, sometimes |
| 704 |
it's useful to have a type variable that can only have some specific types |
| 705 |
as its value. A typical example is a type variable that can only have values |
| 706 |
``str`` and ``bytes``. This lets us define a function that can concatenate |
| 707 |
two strings or bytes objects, but it can't be called with other argument |
| 708 |
types (Python 3.12 syntax): |
| 709 |
|
| 710 |
.. code-block:: python |
| 711 |
|
| 712 |
def concat[S: (str, bytes)](x: S, y: S) -> S: |
| 713 |
return x + y |
| 714 |
|
| 715 |
concat('a', 'b') # Okay |
| 716 |
concat(b'a', b'b') # Okay |
| 717 |
concat(1, 2) # Error! |
| 718 |
|
| 719 |
|
| 720 |
The same thing is also possibly using the legacy syntax (Python 3.11 or earlier): |
| 721 |
|
| 722 |
.. code-block:: python |
| 723 |
|
| 724 |
from typing import TypeVar |
| 725 |
|
| 726 |
AnyStr = TypeVar('AnyStr', str, bytes) |
| 727 |
|
| 728 |
def concat(x: AnyStr, y: AnyStr) -> AnyStr: |
| 729 |
return x + y |
| 730 |
|
| 731 |
No matter which syntax you use, such a type variable is called a |
| 732 |
value-constrained type variable (the allowed types are accessible at runtime |
| 733 |
via ``TypeVar.__constraints__``). Importantly, this is different from a union type, |
| 734 |
since combinations of ``str`` and ``bytes`` are not accepted: |
| 735 |
|
| 736 |
.. code-block:: python |
| 737 |
|
| 738 |
concat('string', b'bytes') # Error! |
| 739 |
|
| 740 |
In this case, this is exactly what we want, since it's not possible |
| 741 |
to concatenate a string and a bytes object! If we tried to use |
| 742 |
a union type, the type checker would complain about this possibility: |
| 743 |
|
| 744 |
.. code-block:: python |
| 745 |
|
| 746 |
def union_concat(x: str | bytes, y: str | bytes) -> str | bytes: |
| 747 |
return x + y # Error: can't concatenate str and bytes |
| 748 |
|
| 749 |
Another interesting special case is calling ``concat()`` with a |
| 750 |
subtype of ``str``: |
| 751 |
|
| 752 |
.. code-block:: python |
| 753 |
|
| 754 |
class S(str): pass |
| 755 |
|
| 756 |
ss = concat(S('foo'), S('bar')) |
| 757 |
reveal_type(ss) # Revealed type is "builtins.str" |
| 758 |
|
| 759 |
You may expect that the type of ``ss`` is ``S``, but the type is |
| 760 |
actually ``str``: a subtype gets promoted to one of the valid values |
| 761 |
for the type variable, which in this case is ``str``. |
| 762 |
|
| 763 |
This is thus subtly different from using ``str | bytes`` as an upper bound, |
| 764 |
where the return type would be ``S`` (see :ref:`type-variable-upper-bound`). |
| 765 |
Using a value constraint is correct for ``concat``, since ``concat`` |
| 766 |
actually returns a ``str`` instance in the above example: |
| 767 |
|
| 768 |
.. code-block:: python |
| 769 |
|
| 770 |
>>> print(type(ss)) |
| 771 |
<class 'str'> |
| 772 |
|
| 773 |
You can also use type variables with a restricted set of possible |
| 774 |
values when defining a generic class. For example, the type |
| 775 |
:py:class:`Pattern[S] <typing.Pattern>` is used for the return |
| 776 |
value of :py:func:`re.compile`, where ``S`` can be either ``str`` |
| 777 |
or ``bytes``. Regular expressions can be based on a string or a |
| 778 |
bytes pattern. |
| 779 |
|
| 780 |
A type variable may not have both value constraints and an upper bound. |
| 781 |
|
| 782 |
Note that you may come across :py:data:`~typing.AnyStr` imported from |
| 783 |
:py:mod:`typing`. This feature is now deprecated, but it means the same |
| 784 |
as our definition of ``AnyStr`` above. |
| 785 |
|
| 786 |
.. _declaring-decorators: |
| 787 |
|
| 788 |
Declaring decorators |
| 789 |
******************** |
| 790 |
|
| 791 |
Decorators are typically functions that take a function as an argument and |
| 792 |
return another function. Describing this behaviour in terms of types can |
| 793 |
be a little tricky; we'll show how you can use type variables and a special |
| 794 |
kind of type variable called a *parameter specification* to do so. |
| 795 |
|
| 796 |
Suppose we have the following decorator, not type annotated yet, |
| 797 |
that preserves the original function's signature and merely prints the decorated |
| 798 |
function's name: |
| 799 |
|
| 800 |
.. code-block:: python |
| 801 |
|
| 802 |
def printing_decorator(func): |
| 803 |
def wrapper(*args, **kwds): |
| 804 |
print("Calling", func) |
| 805 |
return func(*args, **kwds) |
| 806 |
return wrapper |
| 807 |
|
| 808 |
We can use it to decorate function ``add_forty_two``: |
| 809 |
|
| 810 |
.. code-block:: python |
| 811 |
|
| 812 |
# A decorated function. |
| 813 |
@printing_decorator |
| 814 |
def add_forty_two(value: int) -> int: |
| 815 |
return value + 42 |
| 816 |
|
| 817 |
a = add_forty_two(3) |
| 818 |
|
| 819 |
Since ``printing_decorator`` is not type-annotated, the following won't get type checked: |
| 820 |
|
| 821 |
.. code-block:: python |
| 822 |
|
| 823 |
reveal_type(a) # Revealed type is "Any" |
| 824 |
add_forty_two('foo') # No type checker error :( |
| 825 |
|
| 826 |
This is a sorry state of affairs! If you run with ``--strict``, mypy will |
| 827 |
even alert you to this fact: |
| 828 |
``Untyped decorator makes function "add_forty_two" untyped`` |
| 829 |
|
| 830 |
Note that class decorators are handled differently than function decorators in |
| 831 |
mypy: decorating a class does not erase its type, even if the decorator has |
| 832 |
incomplete type annotations. |
| 833 |
|
| 834 |
Here's how one could annotate the decorator (Python 3.12 syntax): |
| 835 |
|
| 836 |
.. code-block:: python |
| 837 |
|
| 838 |
from collections.abc import Callable |
| 839 |
from typing import Any, cast |
| 840 |
|
| 841 |
# A decorator that preserves the signature. |
| 842 |
def printing_decorator[F: Callable[..., Any]](func: F) -> F: |
| 843 |
def wrapper(*args, **kwds): |
| 844 |
print("Calling", func) |
| 845 |
return func(*args, **kwds) |
| 846 |
return cast(F, wrapper) |
| 847 |
|
| 848 |
@printing_decorator |
| 849 |
def add_forty_two(value: int) -> int: |
| 850 |
return value + 42 |
| 851 |
|
| 852 |
a = add_forty_two(3) |
| 853 |
reveal_type(a) # Revealed type is "builtins.int" |
| 854 |
add_forty_two('x') # Argument 1 to "add_forty_two" has incompatible type "str"; expected "int" |
| 855 |
|
| 856 |
Here is the example using the legacy syntax (Python 3.11 and earlier): |
| 857 |
|
| 858 |
.. code-block:: python |
| 859 |
|
| 860 |
from collections.abc import Callable |
| 861 |
from typing import Any, TypeVar, cast |
| 862 |
|
| 863 |
F = TypeVar('F', bound=Callable[..., Any]) |
| 864 |
|
| 865 |
# A decorator that preserves the signature. |
| 866 |
def printing_decorator(func: F) -> F: |
| 867 |
def wrapper(*args, **kwds): |
| 868 |
print("Calling", func) |
| 869 |
return func(*args, **kwds) |
| 870 |
return cast(F, wrapper) |
| 871 |
|
| 872 |
@printing_decorator |
| 873 |
def add_forty_two(value: int) -> int: |
| 874 |
return value + 42 |
| 875 |
|
| 876 |
a = add_forty_two(3) |
| 877 |
reveal_type(a) # Revealed type is "builtins.int" |
| 878 |
add_forty_two('x') # Argument 1 to "add_forty_two" has incompatible type "str"; expected "int" |
| 879 |
|
| 880 |
This still has some shortcomings. First, we need to use the unsafe |
| 881 |
:py:func:`~typing.cast` to convince mypy that ``wrapper()`` has the same |
| 882 |
signature as ``func`` (see :ref:`casts <casts>`). |
| 883 |
|
| 884 |
Second, the ``wrapper()`` function is not tightly type checked, although |
| 885 |
wrapper functions are typically small enough that this is not a big |
| 886 |
problem. This is also the reason for the :py:func:`~typing.cast` call in the |
| 887 |
``return`` statement in ``printing_decorator()``. |
| 888 |
|
| 889 |
However, we can use a parameter specification, introduced using ``**P``, |
| 890 |
for a more faithful type annotation (Python 3.12 syntax): |
| 891 |
|
| 892 |
.. code-block:: python |
| 893 |
|
| 894 |
from collections.abc import Callable |
| 895 |
|
| 896 |
def printing_decorator[**P, T](func: Callable[P, T]) -> Callable[P, T]: |
| 897 |
def wrapper(*args: P.args, **kwds: P.kwargs) -> T: |
| 898 |
print("Calling", func) |
| 899 |
return func(*args, **kwds) |
| 900 |
return wrapper |
| 901 |
|
| 902 |
The same is possible using the legacy syntax with :py:class:`~typing.ParamSpec` |
| 903 |
(Python 3.11 and earlier): |
| 904 |
|
| 905 |
.. code-block:: python |
| 906 |
|
| 907 |
from collections.abc import Callable |
| 908 |
from typing import TypeVar |
| 909 |
from typing_extensions import ParamSpec |
| 910 |
|
| 911 |
P = ParamSpec('P') |
| 912 |
T = TypeVar('T') |
| 913 |
|
| 914 |
def printing_decorator(func: Callable[P, T]) -> Callable[P, T]: |
| 915 |
def wrapper(*args: P.args, **kwds: P.kwargs) -> T: |
| 916 |
print("Calling", func) |
| 917 |
return func(*args, **kwds) |
| 918 |
return wrapper |
| 919 |
|
| 920 |
Parameter specifications also allow you to describe decorators that |
| 921 |
alter the signature of the input function (Python 3.12 syntax): |
| 922 |
|
| 923 |
.. code-block:: python |
| 924 |
|
| 925 |
from collections.abc import Callable |
| 926 |
|
| 927 |
# We reuse 'P' in the return type, but replace 'T' with 'str' |
| 928 |
def stringify[**P, T](func: Callable[P, T]) -> Callable[P, str]: |
| 929 |
def wrapper(*args: P.args, **kwds: P.kwargs) -> str: |
| 930 |
return str(func(*args, **kwds)) |
| 931 |
return wrapper |
| 932 |
|
| 933 |
@stringify |
| 934 |
def add_forty_two(value: int) -> int: |
| 935 |
return value + 42 |
| 936 |
|
| 937 |
a = add_forty_two(3) |
| 938 |
reveal_type(a) # Revealed type is "builtins.str" |
| 939 |
add_forty_two('x') # error: Argument 1 to "add_forty_two" has incompatible type "str"; expected "int" |
| 940 |
|
| 941 |
Here is the above example using the legacy syntax (Python 3.11 and earlier): |
| 942 |
|
| 943 |
.. code-block:: python |
| 944 |
|
| 945 |
from collections.abc import Callable |
| 946 |
from typing import TypeVar |
| 947 |
from typing_extensions import ParamSpec |
| 948 |
|
| 949 |
P = ParamSpec('P') |
| 950 |
T = TypeVar('T') |
| 951 |
|
| 952 |
# We reuse 'P' in the return type, but replace 'T' with 'str' |
| 953 |
def stringify(func: Callable[P, T]) -> Callable[P, str]: |
| 954 |
def wrapper(*args: P.args, **kwds: P.kwargs) -> str: |
| 955 |
return str(func(*args, **kwds)) |
| 956 |
return wrapper |
| 957 |
|
| 958 |
You can also insert an argument in a decorator (Python 3.12 syntax): |
| 959 |
|
| 960 |
.. code-block:: python |
| 961 |
|
| 962 |
from collections.abc import Callable |
| 963 |
from typing import Concatenate |
| 964 |
|
| 965 |
def printing_decorator[**P, T](func: Callable[P, T]) -> Callable[Concatenate[str, P], T]: |
| 966 |
def wrapper(msg: str, /, *args: P.args, **kwds: P.kwargs) -> T: |
| 967 |
print("Calling", func, "with", msg) |
| 968 |
return func(*args, **kwds) |
| 969 |
return wrapper |
| 970 |
|
| 971 |
@printing_decorator |
| 972 |
def add_forty_two(value: int) -> int: |
| 973 |
return value + 42 |
| 974 |
|
| 975 |
a = add_forty_two('three', 3) |
| 976 |
|
| 977 |
Here is the same function using the legacy syntax (Python 3.11 and earlier): |
| 978 |
|
| 979 |
.. code-block:: python |
| 980 |
|
| 981 |
from collections.abc import Callable |
| 982 |
from typing import TypeVar |
| 983 |
from typing_extensions import Concatenate, ParamSpec |
| 984 |
|
| 985 |
P = ParamSpec('P') |
| 986 |
T = TypeVar('T') |
| 987 |
|
| 988 |
def printing_decorator(func: Callable[P, T]) -> Callable[Concatenate[str, P], T]: |
| 989 |
def wrapper(msg: str, /, *args: P.args, **kwds: P.kwargs) -> T: |
| 990 |
print("Calling", func, "with", msg) |
| 991 |
return func(*args, **kwds) |
| 992 |
return wrapper |
| 993 |
|
| 994 |
.. _decorator-factories: |
| 995 |
|
| 996 |
Decorator factories |
| 997 |
------------------- |
| 998 |
|
| 999 |
Functions that take arguments and return a decorator (also called second-order decorators), are |
| 1000 |
similarly supported via generics (Python 3.12 syntax): |
| 1001 |
|
| 1002 |
.. code-block:: python |
| 1003 |
|
| 1004 |
from collections.abc import Callable |
| 1005 |
from typing import Any |
| 1006 |
|
| 1007 |
def route[F: Callable[..., Any]](url: str) -> Callable[[F], F]: |
| 1008 |
... |
| 1009 |
|
| 1010 |
@route(url='/') |
| 1011 |
def index(request: Any) -> str: |
| 1012 |
return 'Hello world' |
| 1013 |
|
| 1014 |
Note that mypy infers that ``F`` is used to make the ``Callable`` return value |
| 1015 |
of ``route`` generic, instead of making ``route`` itself generic, since ``F`` is |
| 1016 |
only used in the return type. Python has no explicit syntax to mark that ``F`` |
| 1017 |
is only bound in the return value. |
| 1018 |
|
| 1019 |
Here is the example using the legacy syntax (Python 3.11 and earlier): |
| 1020 |
|
| 1021 |
.. code-block:: python |
| 1022 |
|
| 1023 |
from collections.abc import Callable |
| 1024 |
from typing import Any, TypeVar |
| 1025 |
|
| 1026 |
F = TypeVar('F', bound=Callable[..., Any]) |
| 1027 |
|
| 1028 |
def route(url: str) -> Callable[[F], F]: |
| 1029 |
... |
| 1030 |
|
| 1031 |
@route(url='/') |
| 1032 |
def index(request: Any) -> str: |
| 1033 |
return 'Hello world' |
| 1034 |
|
| 1035 |
Sometimes the same decorator supports both bare calls and calls with arguments. This can be |
| 1036 |
achieved by combining with :py:func:`@overload <typing.overload>` (Python 3.12 syntax): |
| 1037 |
|
| 1038 |
.. code-block:: python |
| 1039 |
|
| 1040 |
from collections.abc import Callable |
| 1041 |
from typing import Any, overload |
| 1042 |
|
| 1043 |
# Bare decorator usage |
| 1044 |
@overload |
| 1045 |
def atomic[F: Callable[..., Any]](func: F, /) -> F: ... |
| 1046 |
# Decorator with arguments |
| 1047 |
@overload |
| 1048 |
def atomic[F: Callable[..., Any]](*, savepoint: bool = True) -> Callable[[F], F]: ... |
| 1049 |
|
| 1050 |
# Implementation |
| 1051 |
def atomic(func: Callable[..., Any] | None = None, /, *, savepoint: bool = True): |
| 1052 |
def decorator(func: Callable[..., Any]): |
| 1053 |
... # Code goes here |
| 1054 |
if __func is not None: |
| 1055 |
return decorator(__func) |
| 1056 |
else: |
| 1057 |
return decorator |
| 1058 |
|
| 1059 |
# Usage |
| 1060 |
@atomic |
| 1061 |
def func1() -> None: ... |
| 1062 |
|
| 1063 |
@atomic(savepoint=False) |
| 1064 |
def func2() -> None: ... |
| 1065 |
|
| 1066 |
Here is the decorator from the example using the legacy syntax |
| 1067 |
(Python 3.11 and earlier): |
| 1068 |
|
| 1069 |
.. code-block:: python |
| 1070 |
|
| 1071 |
from collections.abc import Callable |
| 1072 |
from typing import Any, Optional, TypeVar, overload |
| 1073 |
|
| 1074 |
F = TypeVar('F', bound=Callable[..., Any]) |
| 1075 |
|
| 1076 |
# Bare decorator usage |
| 1077 |
@overload |
| 1078 |
def atomic(func: F, /) -> F: ... |
| 1079 |
# Decorator with arguments |
| 1080 |
@overload |
| 1081 |
def atomic(*, savepoint: bool = True) -> Callable[[F], F]: ... |
| 1082 |
|
| 1083 |
# Implementation |
| 1084 |
def atomic(func: Optional[Callable[..., Any]] = None, /, *, savepoint: bool = True): |
| 1085 |
... # Same as above |
| 1086 |
|
| 1087 |
Generic protocols |
| 1088 |
***************** |
| 1089 |
|
| 1090 |
Mypy supports generic protocols (see also :ref:`protocol-types`). Several |
| 1091 |
:ref:`predefined protocols <predefined_protocols>` are generic, such as |
| 1092 |
:py:class:`Iterable[T] <collections.abc.Iterable>`, and you can define additional |
| 1093 |
generic protocols. Generic protocols mostly follow the normal rules for |
| 1094 |
generic classes. Example (Python 3.12 syntax): |
| 1095 |
|
| 1096 |
.. code-block:: python |
| 1097 |
|
| 1098 |
from typing import Protocol |
| 1099 |
|
| 1100 |
class Box[T](Protocol): |
| 1101 |
content: T |
| 1102 |
|
| 1103 |
def do_stuff(one: Box[str], other: Box[bytes]) -> None: |
| 1104 |
... |
| 1105 |
|
| 1106 |
class StringWrapper: |
| 1107 |
def __init__(self, content: str) -> None: |
| 1108 |
self.content = content |
| 1109 |
|
| 1110 |
class BytesWrapper: |
| 1111 |
def __init__(self, content: bytes) -> None: |
| 1112 |
self.content = content |
| 1113 |
|
| 1114 |
do_stuff(StringWrapper('one'), BytesWrapper(b'other')) # OK |
| 1115 |
|
| 1116 |
x: Box[float] = ... |
| 1117 |
y: Box[int] = ... |
| 1118 |
x = y # Error -- Box is invariant |
| 1119 |
|
| 1120 |
Here is the definition of ``Box`` from the above example using the legacy |
| 1121 |
syntax (Python 3.11 and earlier): |
| 1122 |
|
| 1123 |
.. code-block:: python |
| 1124 |
|
| 1125 |
from typing import Protocol, TypeVar |
| 1126 |
|
| 1127 |
T = TypeVar('T') |
| 1128 |
|
| 1129 |
class Box(Protocol[T]): |
| 1130 |
content: T |
| 1131 |
|
| 1132 |
Note that ``class ClassName(Protocol[T])`` is allowed as a shorthand for |
| 1133 |
``class ClassName(Protocol, Generic[T])`` when using the legacy syntax, |
| 1134 |
as per :pep:`PEP 544: Generic protocols <544#generic-protocols>`. |
| 1135 |
This form is only valid when using the legacy syntax. |
| 1136 |
|
| 1137 |
When using the legacy syntax, there is an important difference between |
| 1138 |
generic protocols and ordinary generic classes: mypy checks that the |
| 1139 |
declared variances of generic type variables in a protocol match how |
| 1140 |
they are used in the protocol definition. The protocol in this example |
| 1141 |
is rejected, since the type variable ``T`` is used covariantly as |
| 1142 |
a return type, but the type variable is invariant: |
| 1143 |
|
| 1144 |
.. code-block:: python |
| 1145 |
|
| 1146 |
from typing import Protocol, TypeVar |
| 1147 |
|
| 1148 |
T = TypeVar('T') |
| 1149 |
|
| 1150 |
class ReadOnlyBox(Protocol[T]): # error: Invariant type variable "T" used in protocol where covariant one is expected |
| 1151 |
def content(self) -> T: ... |
| 1152 |
|
| 1153 |
This example correctly uses a covariant type variable: |
| 1154 |
|
| 1155 |
.. code-block:: python |
| 1156 |
|
| 1157 |
from typing import Protocol, TypeVar |
| 1158 |
|
| 1159 |
T_co = TypeVar('T_co', covariant=True) |
| 1160 |
|
| 1161 |
class ReadOnlyBox(Protocol[T_co]): # OK |
| 1162 |
def content(self) -> T_co: ... |
| 1163 |
|
| 1164 |
ax: ReadOnlyBox[float] = ... |
| 1165 |
ay: ReadOnlyBox[int] = ... |
| 1166 |
ax = ay # OK -- ReadOnlyBox is covariant |
| 1167 |
|
| 1168 |
See :ref:`variance-of-generics` for more about variance. |
| 1169 |
|
| 1170 |
Generic protocols can also be recursive. Example (Python 3.12 syntax): |
| 1171 |
|
| 1172 |
.. code-block:: python |
| 1173 |
|
| 1174 |
class Linked[T](Protocol): |
| 1175 |
val: T |
| 1176 |
def next(self) -> 'Linked[T]': ... |
| 1177 |
|
| 1178 |
class L: |
| 1179 |
val: int |
| 1180 |
def next(self) -> 'L': ... |
| 1181 |
|
| 1182 |
def last(seq: Linked[T]) -> T: ... |
| 1183 |
|
| 1184 |
result = last(L()) |
| 1185 |
reveal_type(result) # Revealed type is "builtins.int" |
| 1186 |
|
| 1187 |
Here is the definition of ``Linked`` using the legacy syntax |
| 1188 |
(Python 3.11 and earlier): |
| 1189 |
|
| 1190 |
.. code-block:: python |
| 1191 |
|
| 1192 |
from typing import TypeVar |
| 1193 |
|
| 1194 |
T = TypeVar('T') |
| 1195 |
|
| 1196 |
class Linked(Protocol[T]): |
| 1197 |
val: T |
| 1198 |
def next(self) -> 'Linked[T]': ... |
| 1199 |
|
| 1200 |
.. _generic-type-aliases: |
| 1201 |
|
| 1202 |
Generic type aliases |
| 1203 |
******************** |
| 1204 |
|
| 1205 |
Type aliases can be generic. In this case they can be used in two ways. |
| 1206 |
First, subscripted aliases are equivalent to original types with substituted type |
| 1207 |
variables. Second, unsubscripted aliases are treated as original types with type |
| 1208 |
parameters replaced with ``Any``. |
| 1209 |
|
| 1210 |
The ``type`` statement introduced in Python 3.12 is used to define generic |
| 1211 |
type aliases (it also supports non-generic type aliases): |
| 1212 |
|
| 1213 |
.. code-block:: python |
| 1214 |
|
| 1215 |
from collections.abc import Callable, Iterable |
| 1216 |
|
| 1217 |
type TInt[S] = tuple[int, S] |
| 1218 |
type UInt[S] = S | int |
| 1219 |
type CBack[S] = Callable[..., S] |
| 1220 |
|
| 1221 |
def response(query: str) -> UInt[str]: # Same as str | int |
| 1222 |
... |
| 1223 |
def activate[S](cb: CBack[S]) -> S: # Same as Callable[..., S] |
| 1224 |
... |
| 1225 |
table_entry: TInt # Same as tuple[int, Any] |
| 1226 |
|
| 1227 |
type Vec[T: (int, float, complex)] = Iterable[tuple[T, T]] |
| 1228 |
|
| 1229 |
def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: |
| 1230 |
return sum(x*y for x, y in v) |
| 1231 |
|
| 1232 |
def dilate[T: (int, float, complex)](v: Vec[T], scale: T) -> Vec[T]: |
| 1233 |
return ((x * scale, y * scale) for x, y in v) |
| 1234 |
|
| 1235 |
v1: Vec[int] = [] # Same as Iterable[tuple[int, int]] |
| 1236 |
v2: Vec = [] # Same as Iterable[tuple[Any, Any]] |
| 1237 |
v3: Vec[int, int] = [] # Error: Invalid alias, too many type arguments! |
| 1238 |
|
| 1239 |
There is also a legacy syntax that relies on ``TypeVar``. |
| 1240 |
Here the number of type arguments must match the number of free type variables |
| 1241 |
in the generic type alias definition. A type variables is free if it's not |
| 1242 |
a type parameter of a surrounding class or function. Example (following |
| 1243 |
:pep:`PEP 484: Type aliases <484#type-aliases>`, Python 3.11 and earlier): |
| 1244 |
|
| 1245 |
.. code-block:: python |
| 1246 |
|
| 1247 |
from typing import TypeVar, Iterable, Union, Callable |
| 1248 |
|
| 1249 |
S = TypeVar('S') |
| 1250 |
|
| 1251 |
TInt = tuple[int, S] # 1 type parameter, since only S is free |
| 1252 |
UInt = Union[S, int] |
| 1253 |
CBack = Callable[..., S] |
| 1254 |
|
| 1255 |
def response(query: str) -> UInt[str]: # Same as Union[str, int] |
| 1256 |
... |
| 1257 |
def activate(cb: CBack[S]) -> S: # Same as Callable[..., S] |
| 1258 |
... |
| 1259 |
table_entry: TInt # Same as tuple[int, Any] |
| 1260 |
|
| 1261 |
T = TypeVar('T', int, float, complex) |
| 1262 |
|
| 1263 |
Vec = Iterable[tuple[T, T]] |
| 1264 |
|
| 1265 |
def inproduct(v: Vec[T]) -> T: |
| 1266 |
return sum(x*y for x, y in v) |
| 1267 |
|
| 1268 |
def dilate(v: Vec[T], scale: T) -> Vec[T]: |
| 1269 |
return ((x * scale, y * scale) for x, y in v) |
| 1270 |
|
| 1271 |
v1: Vec[int] = [] # Same as Iterable[tuple[int, int]] |
| 1272 |
v2: Vec = [] # Same as Iterable[tuple[Any, Any]] |
| 1273 |
v3: Vec[int, int] = [] # Error: Invalid alias, too many type arguments! |
| 1274 |
|
| 1275 |
Type aliases can be imported from modules just like other names. An |
| 1276 |
alias can also target another alias, although building complex chains |
| 1277 |
of aliases is not recommended -- this impedes code readability, thus |
| 1278 |
defeating the purpose of using aliases. Example (Python 3.12 syntax): |
| 1279 |
|
| 1280 |
.. code-block:: python |
| 1281 |
|
| 1282 |
from example1 import AliasType |
| 1283 |
from example2 import Vec |
| 1284 |
|
| 1285 |
# AliasType and Vec are type aliases (Vec as defined above) |
| 1286 |
|
| 1287 |
def fun() -> AliasType: |
| 1288 |
... |
| 1289 |
|
| 1290 |
type OIntVec = Vec[int] | None |
| 1291 |
|
| 1292 |
Type aliases defined using the ``type`` statement are not valid as |
| 1293 |
base classes, and they can't be used to construct instances: |
| 1294 |
|
| 1295 |
.. code-block:: python |
| 1296 |
|
| 1297 |
from example1 import AliasType |
| 1298 |
from example2 import Vec |
| 1299 |
|
| 1300 |
# AliasType and Vec are type aliases (Vec as defined above) |
| 1301 |
|
| 1302 |
class NewVec[T](Vec[T]): # Error: not valid as base class |
| 1303 |
... |
| 1304 |
|
| 1305 |
x = AliasType() # Error: can't be used to create instances |
| 1306 |
|
| 1307 |
Here are examples using the legacy syntax (Python 3.11 and earlier): |
| 1308 |
|
| 1309 |
.. code-block:: python |
| 1310 |
|
| 1311 |
from typing import TypeVar, Generic, Optional |
| 1312 |
from example1 import AliasType |
| 1313 |
from example2 import Vec |
| 1314 |
|
| 1315 |
# AliasType and Vec are type aliases (Vec as defined above) |
| 1316 |
|
| 1317 |
def fun() -> AliasType: |
| 1318 |
... |
| 1319 |
|
| 1320 |
OIntVec = Optional[Vec[int]] |
| 1321 |
|
| 1322 |
T = TypeVar('T') |
| 1323 |
|
| 1324 |
# Old-style type aliases can be used as base classes and you can |
| 1325 |
# construct instances using them |
| 1326 |
|
| 1327 |
class NewVec(Vec[T]): |
| 1328 |
... |
| 1329 |
|
| 1330 |
x = AliasType() |
| 1331 |
|
| 1332 |
for i, j in NewVec[int](): |
| 1333 |
... |
| 1334 |
|
| 1335 |
Using type variable bounds or value constraints in generic aliases has |
| 1336 |
the same effect as in generic classes and functions. |
| 1337 |
|
| 1338 |
|
| 1339 |
Differences between the new and old syntax |
| 1340 |
****************************************** |
| 1341 |
|
| 1342 |
There are a few notable differences between the new (Python 3.12 and later) |
| 1343 |
and the old syntax for generic classes, functions and type aliases, beyond |
| 1344 |
the obvious syntactic differences: |
| 1345 |
|
| 1346 |
* Type variables defined using the old syntax create definitions at runtime |
| 1347 |
in the surrounding namespace, whereas the type variables defined using the |
| 1348 |
new syntax are only defined within the class, function or type variable |
| 1349 |
that uses them. |
| 1350 |
* Type variable definitions can be shared when using the old syntax, but |
| 1351 |
the new syntax doesn't support this. |
| 1352 |
* When using the new syntax, the variance of class type variables is always |
| 1353 |
inferred. |
| 1354 |
* Type aliases defined using the new syntax can contain forward references |
| 1355 |
and recursive references without using string literal escaping. The |
| 1356 |
same is true for the bounds and constraints of type variables. |
| 1357 |
* The new syntax lets you define a generic alias where the definition doesn't |
| 1358 |
contain a reference to a type parameter. This is occasionally useful, at |
| 1359 |
least when conditionally defining type aliases. |
| 1360 |
* Type aliases defined using the new syntax can't be used as base classes |
| 1361 |
and can't be used to construct instances, unlike aliases defined using the |
| 1362 |
old syntax. |
| 1363 |
|
| 1364 |
|
| 1365 |
Generic class internals |
| 1366 |
*********************** |
| 1367 |
|
| 1368 |
You may wonder what happens at runtime when you index a generic class. |
| 1369 |
Indexing returns a *generic alias* to the original class that returns instances |
| 1370 |
of the original class on instantiation (Python 3.12 syntax): |
| 1371 |
|
| 1372 |
.. code-block:: python |
| 1373 |
|
| 1374 |
>>> class Stack[T]: ... |
| 1375 |
>>> Stack |
| 1376 |
__main__.Stack |
| 1377 |
>>> Stack[int] |
| 1378 |
__main__.Stack[int] |
| 1379 |
>>> instance = Stack[int]() |
| 1380 |
>>> instance.__class__ |
| 1381 |
__main__.Stack |
| 1382 |
|
| 1383 |
Here is the same example using the legacy syntax (Python 3.11 and earlier): |
| 1384 |
|
| 1385 |
.. code-block:: python |
| 1386 |
|
| 1387 |
>>> from typing import TypeVar, Generic |
| 1388 |
>>> T = TypeVar('T') |
| 1389 |
>>> class Stack(Generic[T]): ... |
| 1390 |
>>> Stack |
| 1391 |
__main__.Stack |
| 1392 |
>>> Stack[int] |
| 1393 |
__main__.Stack[int] |
| 1394 |
>>> instance = Stack[int]() |
| 1395 |
>>> instance.__class__ |
| 1396 |
__main__.Stack |
| 1397 |
|
| 1398 |
Generic aliases can be instantiated or subclassed, similar to real |
| 1399 |
classes, but the above examples illustrate that type variables are |
| 1400 |
erased at runtime. Generic ``Stack`` instances are just ordinary |
| 1401 |
Python objects, and they have no extra runtime overhead or magic due |
| 1402 |
to being generic, other than the ``Generic`` base class that overloads |
| 1403 |
the indexing operator using ``__class_getitem__``. ``typing.Generic`` |
| 1404 |
is included as an implicit base class even when using the new syntax: |
| 1405 |
|
| 1406 |
.. code-block:: python |
| 1407 |
|
| 1408 |
>>> class Stack[T]: ... |
| 1409 |
>>> Stack.mro() |
| 1410 |
[<class '__main__.Stack'>, <class 'typing.Generic'>, <class 'object'>] |
| 1411 |
|
| 1412 |
Note that in Python 3.8 and earlier, the built-in types |
| 1413 |
:py:class:`list`, :py:class:`dict` and others do not support indexing. |
| 1414 |
This is why we have the aliases :py:class:`~typing.List`, |
| 1415 |
:py:class:`~typing.Dict` and so on in the :py:mod:`typing` |
| 1416 |
module. Indexing these aliases gives you a generic alias that |
| 1417 |
resembles generic aliases constructed by directly indexing the target |
| 1418 |
class in more recent versions of Python: |
| 1419 |
|
| 1420 |
.. code-block:: python |
| 1421 |
|
| 1422 |
>>> # Prefer the 'list[int]' syntax |
| 1423 |
>>> from typing import List |
| 1424 |
>>> List[int] |
| 1425 |
typing.List[int] |
| 1426 |
|
| 1427 |
Note that the generic aliases in ``typing`` don't support constructing |
| 1428 |
instances, unlike the corresponding built-in classes: |
| 1429 |
|
| 1430 |
.. code-block:: python |
| 1431 |
|
| 1432 |
>>> list[int]() |
| 1433 |
[] |
| 1434 |
>>> from typing import List |
| 1435 |
>>> List[int]() |
| 1436 |
Traceback (most recent call last): |
| 1437 |
... |
| 1438 |
TypeError: Type List cannot be instantiated; use list() instead |