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