1:mod:`typing` --- Support for type hints 2======================================== 3 4.. module:: typing 5 :synopsis: Support for type hints (see PEP 484). 6 7.. versionadded:: 3.5 8 9**Source code:** :source:`Lib/typing.py` 10 11.. note:: 12 13 The typing module has been included in the standard library on a 14 :term:`provisional basis <provisional api>`. New features might 15 be added and API may change even between minor releases if deemed 16 necessary by the core developers. 17 18-------------- 19 20This module supports type hints as specified by :pep:`484` and :pep:`526`. 21The most fundamental support consists of the types :data:`Any`, :data:`Union`, 22:data:`Tuple`, :data:`Callable`, :class:`TypeVar`, and 23:class:`Generic`. For full specification please see :pep:`484`. For 24a simplified introduction to type hints see :pep:`483`. 25 26 27The function below takes and returns a string and is annotated as follows:: 28 29 def greeting(name: str) -> str: 30 return 'Hello ' + name 31 32In the function ``greeting``, the argument ``name`` is expected to be of type 33:class:`str` and the return type :class:`str`. Subtypes are accepted as 34arguments. 35 36Type aliases 37------------ 38 39A type alias is defined by assigning the type to the alias. In this example, 40``Vector`` and ``List[float]`` will be treated as interchangeable synonyms:: 41 42 from typing import List 43 Vector = List[float] 44 45 def scale(scalar: float, vector: Vector) -> Vector: 46 return [scalar * num for num in vector] 47 48 # typechecks; a list of floats qualifies as a Vector. 49 new_vector = scale(2.0, [1.0, -4.2, 5.4]) 50 51Type aliases are useful for simplifying complex type signatures. For example:: 52 53 from typing import Dict, Tuple, Sequence 54 55 ConnectionOptions = Dict[str, str] 56 Address = Tuple[str, int] 57 Server = Tuple[Address, ConnectionOptions] 58 59 def broadcast_message(message: str, servers: Sequence[Server]) -> None: 60 ... 61 62 # The static type checker will treat the previous type signature as 63 # being exactly equivalent to this one. 64 def broadcast_message( 65 message: str, 66 servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None: 67 ... 68 69Note that ``None`` as a type hint is a special case and is replaced by 70``type(None)``. 71 72.. _distinct: 73 74NewType 75------- 76 77Use the :func:`NewType` helper function to create distinct types:: 78 79 from typing import NewType 80 81 UserId = NewType('UserId', int) 82 some_id = UserId(524313) 83 84The static type checker will treat the new type as if it were a subclass 85of the original type. This is useful in helping catch logical errors:: 86 87 def get_user_name(user_id: UserId) -> str: 88 ... 89 90 # typechecks 91 user_a = get_user_name(UserId(42351)) 92 93 # does not typecheck; an int is not a UserId 94 user_b = get_user_name(-1) 95 96You may still perform all ``int`` operations on a variable of type ``UserId``, 97but the result will always be of type ``int``. This lets you pass in a 98``UserId`` wherever an ``int`` might be expected, but will prevent you from 99accidentally creating a ``UserId`` in an invalid way:: 100 101 # 'output' is of type 'int', not 'UserId' 102 output = UserId(23413) + UserId(54341) 103 104Note that these checks are enforced only by the static type checker. At runtime 105the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a 106function that immediately returns whatever parameter you pass it. That means 107the expression ``Derived(some_value)`` does not create a new class or introduce 108any overhead beyond that of a regular function call. 109 110More precisely, the expression ``some_value is Derived(some_value)`` is always 111true at runtime. 112 113This also means that it is not possible to create a subtype of ``Derived`` 114since it is an identity function at runtime, not an actual type:: 115 116 from typing import NewType 117 118 UserId = NewType('UserId', int) 119 120 # Fails at runtime and does not typecheck 121 class AdminUserId(UserId): pass 122 123However, it is possible to create a :func:`NewType` based on a 'derived' ``NewType``:: 124 125 from typing import NewType 126 127 UserId = NewType('UserId', int) 128 129 ProUserId = NewType('ProUserId', UserId) 130 131and typechecking for ``ProUserId`` will work as expected. 132 133See :pep:`484` for more details. 134 135.. note:: 136 137 Recall that the use of a type alias declares two types to be *equivalent* to 138 one another. Doing ``Alias = Original`` will make the static type checker 139 treat ``Alias`` as being *exactly equivalent* to ``Original`` in all cases. 140 This is useful when you want to simplify complex type signatures. 141 142 In contrast, ``NewType`` declares one type to be a *subtype* of another. 143 Doing ``Derived = NewType('Derived', Original)`` will make the static type 144 checker treat ``Derived`` as a *subclass* of ``Original``, which means a 145 value of type ``Original`` cannot be used in places where a value of type 146 ``Derived`` is expected. This is useful when you want to prevent logic 147 errors with minimal runtime cost. 148 149.. versionadded:: 3.5.2 150 151Callable 152-------- 153 154Frameworks expecting callback functions of specific signatures might be 155type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType]``. 156 157For example:: 158 159 from typing import Callable 160 161 def feeder(get_next_item: Callable[[], str]) -> None: 162 # Body 163 164 def async_query(on_success: Callable[[int], None], 165 on_error: Callable[[int, Exception], None]) -> None: 166 # Body 167 168It is possible to declare the return type of a callable without specifying 169the call signature by substituting a literal ellipsis 170for the list of arguments in the type hint: ``Callable[..., ReturnType]``. 171 172.. _generics: 173 174Generics 175-------- 176 177Since type information about objects kept in containers cannot be statically 178inferred in a generic way, abstract base classes have been extended to support 179subscription to denote expected types for container elements. 180 181:: 182 183 from typing import Mapping, Sequence 184 185 def notify_by_email(employees: Sequence[Employee], 186 overrides: Mapping[str, str]) -> None: ... 187 188Generics can be parameterized by using a new factory available in typing 189called :class:`TypeVar`. 190 191:: 192 193 from typing import Sequence, TypeVar 194 195 T = TypeVar('T') # Declare type variable 196 197 def first(l: Sequence[T]) -> T: # Generic function 198 return l[0] 199 200 201User-defined generic types 202-------------------------- 203 204A user-defined class can be defined as a generic class. 205 206:: 207 208 from typing import TypeVar, Generic 209 from logging import Logger 210 211 T = TypeVar('T') 212 213 class LoggedVar(Generic[T]): 214 def __init__(self, value: T, name: str, logger: Logger) -> None: 215 self.name = name 216 self.logger = logger 217 self.value = value 218 219 def set(self, new: T) -> None: 220 self.log('Set ' + repr(self.value)) 221 self.value = new 222 223 def get(self) -> T: 224 self.log('Get ' + repr(self.value)) 225 return self.value 226 227 def log(self, message: str) -> None: 228 self.logger.info('%s: %s', self.name, message) 229 230``Generic[T]`` as a base class defines that the class ``LoggedVar`` takes a 231single type parameter ``T`` . This also makes ``T`` valid as a type within the 232class body. 233 234The :class:`Generic` base class uses a metaclass that defines 235:meth:`__getitem__` so that ``LoggedVar[t]`` is valid as a type:: 236 237 from typing import Iterable 238 239 def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None: 240 for var in vars: 241 var.set(0) 242 243A generic type can have any number of type variables, and type variables may 244be constrained:: 245 246 from typing import TypeVar, Generic 247 ... 248 249 T = TypeVar('T') 250 S = TypeVar('S', int, str) 251 252 class StrangePair(Generic[T, S]): 253 ... 254 255Each type variable argument to :class:`Generic` must be distinct. 256This is thus invalid:: 257 258 from typing import TypeVar, Generic 259 ... 260 261 T = TypeVar('T') 262 263 class Pair(Generic[T, T]): # INVALID 264 ... 265 266You can use multiple inheritance with :class:`Generic`:: 267 268 from typing import TypeVar, Generic, Sized 269 270 T = TypeVar('T') 271 272 class LinkedList(Sized, Generic[T]): 273 ... 274 275When inheriting from generic classes, some type variables could be fixed:: 276 277 from typing import TypeVar, Mapping 278 279 T = TypeVar('T') 280 281 class MyDict(Mapping[str, T]): 282 ... 283 284In this case ``MyDict`` has a single parameter, ``T``. 285 286Using a generic class without specifying type parameters assumes 287:data:`Any` for each position. In the following example, ``MyIterable`` is 288not generic but implicitly inherits from ``Iterable[Any]``:: 289 290 from typing import Iterable 291 292 class MyIterable(Iterable): # Same as Iterable[Any] 293 294User defined generic type aliases are also supported. Examples:: 295 296 from typing import TypeVar, Iterable, Tuple, Union 297 S = TypeVar('S') 298 Response = Union[Iterable[S], int] 299 300 # Return type here is same as Union[Iterable[str], int] 301 def response(query: str) -> Response[str]: 302 ... 303 304 T = TypeVar('T', int, float, complex) 305 Vec = Iterable[Tuple[T, T]] 306 307 def inproduct(v: Vec[T]) -> T: # Same as Iterable[Tuple[T, T]] 308 return sum(x*y for x, y in v) 309 310The metaclass used by :class:`Generic` is a subclass of :class:`abc.ABCMeta`. 311A generic class can be an ABC by including abstract methods or properties, 312and generic classes can also have ABCs as base classes without a metaclass 313conflict. Generic metaclasses are not supported. The outcome of parameterizing 314generics is cached, and most types in the typing module are hashable and 315comparable for equality. 316 317 318The :data:`Any` type 319-------------------- 320 321A special kind of type is :data:`Any`. A static type checker will treat 322every type as being compatible with :data:`Any` and :data:`Any` as being 323compatible with every type. 324 325This means that it is possible to perform any operation or method call on a 326value of type on :data:`Any` and assign it to any variable:: 327 328 from typing import Any 329 330 a = None # type: Any 331 a = [] # OK 332 a = 2 # OK 333 334 s = '' # type: str 335 s = a # OK 336 337 def foo(item: Any) -> int: 338 # Typechecks; 'item' could be any type, 339 # and that type might have a 'bar' method 340 item.bar() 341 ... 342 343Notice that no typechecking is performed when assigning a value of type 344:data:`Any` to a more precise type. For example, the static type checker did 345not report an error when assigning ``a`` to ``s`` even though ``s`` was 346declared to be of type :class:`str` and receives an :class:`int` value at 347runtime! 348 349Furthermore, all functions without a return type or parameter types will 350implicitly default to using :data:`Any`:: 351 352 def legacy_parser(text): 353 ... 354 return data 355 356 # A static type checker will treat the above 357 # as having the same signature as: 358 def legacy_parser(text: Any) -> Any: 359 ... 360 return data 361 362This behavior allows :data:`Any` to be used as an *escape hatch* when you 363need to mix dynamically and statically typed code. 364 365Contrast the behavior of :data:`Any` with the behavior of :class:`object`. 366Similar to :data:`Any`, every type is a subtype of :class:`object`. However, 367unlike :data:`Any`, the reverse is not true: :class:`object` is *not* a 368subtype of every other type. 369 370That means when the type of a value is :class:`object`, a type checker will 371reject almost all operations on it, and assigning it to a variable (or using 372it as a return value) of a more specialized type is a type error. For example:: 373 374 def hash_a(item: object) -> int: 375 # Fails; an object does not have a 'magic' method. 376 item.magic() 377 ... 378 379 def hash_b(item: Any) -> int: 380 # Typechecks 381 item.magic() 382 ... 383 384 # Typechecks, since ints and strs are subclasses of object 385 hash_a(42) 386 hash_a("foo") 387 388 # Typechecks, since Any is compatible with all types 389 hash_b(42) 390 hash_b("foo") 391 392Use :class:`object` to indicate that a value could be any type in a typesafe 393manner. Use :data:`Any` to indicate that a value is dynamically typed. 394 395Classes, functions, and decorators 396---------------------------------- 397 398The module defines the following classes, functions and decorators: 399 400.. class:: TypeVar 401 402 Type variable. 403 404 Usage:: 405 406 T = TypeVar('T') # Can be anything 407 A = TypeVar('A', str, bytes) # Must be str or bytes 408 409 Type variables exist primarily for the benefit of static type 410 checkers. They serve as the parameters for generic types as well 411 as for generic function definitions. See class Generic for more 412 information on generic types. Generic functions work as follows:: 413 414 def repeat(x: T, n: int) -> Sequence[T]: 415 """Return a list containing n references to x.""" 416 return [x]*n 417 418 def longest(x: A, y: A) -> A: 419 """Return the longest of two strings.""" 420 return x if len(x) >= len(y) else y 421 422 The latter example's signature is essentially the overloading 423 of ``(str, str) -> str`` and ``(bytes, bytes) -> bytes``. Also note 424 that if the arguments are instances of some subclass of :class:`str`, 425 the return type is still plain :class:`str`. 426 427 At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`. In general, 428 :func:`isinstance` and :func:`issubclass` should not be used with types. 429 430 Type variables may be marked covariant or contravariant by passing 431 ``covariant=True`` or ``contravariant=True``. See :pep:`484` for more 432 details. By default type variables are invariant. Alternatively, 433 a type variable may specify an upper bound using ``bound=<type>``. 434 This means that an actual type substituted (explicitly or implicitly) 435 for the type variable must be a subclass of the boundary type, 436 see :pep:`484`. 437 438.. class:: Generic 439 440 Abstract base class for generic types. 441 442 A generic type is typically declared by inheriting from an 443 instantiation of this class with one or more type variables. 444 For example, a generic mapping type might be defined as:: 445 446 class Mapping(Generic[KT, VT]): 447 def __getitem__(self, key: KT) -> VT: 448 ... 449 # Etc. 450 451 This class can then be used as follows:: 452 453 X = TypeVar('X') 454 Y = TypeVar('Y') 455 456 def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y: 457 try: 458 return mapping[key] 459 except KeyError: 460 return default 461 462.. class:: Type(Generic[CT_co]) 463 464 A variable annotated with ``C`` may accept a value of type ``C``. In 465 contrast, a variable annotated with ``Type[C]`` may accept values that are 466 classes themselves -- specifically, it will accept the *class object* of 467 ``C``. For example:: 468 469 a = 3 # Has type 'int' 470 b = int # Has type 'Type[int]' 471 c = type(a) # Also has type 'Type[int]' 472 473 Note that ``Type[C]`` is covariant:: 474 475 class User: ... 476 class BasicUser(User): ... 477 class ProUser(User): ... 478 class TeamUser(User): ... 479 480 # Accepts User, BasicUser, ProUser, TeamUser, ... 481 def make_new_user(user_class: Type[User]) -> User: 482 # ... 483 return user_class() 484 485 The fact that ``Type[C]`` is covariant implies that all subclasses of 486 ``C`` should implement the same constructor signature and class method 487 signatures as ``C``. The type checker should flag violations of this, 488 but should also allow constructor calls in subclasses that match the 489 constructor calls in the indicated base class. How the type checker is 490 required to handle this particular case may change in future revisions of 491 :pep:`484`. 492 493 The only legal parameters for :class:`Type` are classes, :data:`Any`, 494 :ref:`type variables <generics>`, and unions of any of these types. 495 For example:: 496 497 def new_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ... 498 499 ``Type[Any]`` is equivalent to ``Type`` which in turn is equivalent 500 to ``type``, which is the root of Python's metaclass hierarchy. 501 502 .. versionadded:: 3.5.2 503 504.. class:: Iterable(Generic[T_co]) 505 506 A generic version of :class:`collections.abc.Iterable`. 507 508.. class:: Iterator(Iterable[T_co]) 509 510 A generic version of :class:`collections.abc.Iterator`. 511 512.. class:: Reversible(Iterable[T_co]) 513 514 A generic version of :class:`collections.abc.Reversible`. 515 516.. class:: SupportsInt 517 518 An ABC with one abstract method ``__int__``. 519 520.. class:: SupportsFloat 521 522 An ABC with one abstract method ``__float__``. 523 524.. class:: SupportsComplex 525 526 An ABC with one abstract method ``__complex__``. 527 528.. class:: SupportsBytes 529 530 An ABC with one abstract method ``__bytes__``. 531 532.. class:: SupportsAbs 533 534 An ABC with one abstract method ``__abs__`` that is covariant 535 in its return type. 536 537.. class:: SupportsRound 538 539 An ABC with one abstract method ``__round__`` 540 that is covariant in its return type. 541 542.. class:: Container(Generic[T_co]) 543 544 A generic version of :class:`collections.abc.Container`. 545 546.. class:: Hashable 547 548 An alias to :class:`collections.abc.Hashable` 549 550.. class:: Sized 551 552 An alias to :class:`collections.abc.Sized` 553 554.. class:: Collection(Sized, Iterable[T_co], Container[T_co]) 555 556 A generic version of :class:`collections.abc.Collection` 557 558 .. versionadded:: 3.6 559 560.. class:: AbstractSet(Sized, Collection[T_co]) 561 562 A generic version of :class:`collections.abc.Set`. 563 564.. class:: MutableSet(AbstractSet[T]) 565 566 A generic version of :class:`collections.abc.MutableSet`. 567 568.. class:: Mapping(Sized, Collection[KT], Generic[VT_co]) 569 570 A generic version of :class:`collections.abc.Mapping`. 571 This type can be used as follows:: 572 573 def get_position_in_index(word_list: Mapping[str, int], word: str) -> int: 574 return word_list[word] 575 576.. class:: MutableMapping(Mapping[KT, VT]) 577 578 A generic version of :class:`collections.abc.MutableMapping`. 579 580.. class:: Sequence(Reversible[T_co], Collection[T_co]) 581 582 A generic version of :class:`collections.abc.Sequence`. 583 584.. class:: MutableSequence(Sequence[T]) 585 586 A generic version of :class:`collections.abc.MutableSequence`. 587 588.. class:: ByteString(Sequence[int]) 589 590 A generic version of :class:`collections.abc.ByteString`. 591 592 This type represents the types :class:`bytes`, :class:`bytearray`, 593 and :class:`memoryview`. 594 595 As a shorthand for this type, :class:`bytes` can be used to 596 annotate arguments of any of the types mentioned above. 597 598.. class:: Deque(deque, MutableSequence[T]) 599 600 A generic version of :class:`collections.deque`. 601 602 .. versionadded:: 3.6.1 603 604.. class:: List(list, MutableSequence[T]) 605 606 Generic version of :class:`list`. 607 Useful for annotating return types. To annotate arguments it is preferred 608 to use an abstract collection type such as :class:`Sequence` or 609 :class:`Iterable`. 610 611 This type may be used as follows:: 612 613 T = TypeVar('T', int, float) 614 615 def vec2(x: T, y: T) -> List[T]: 616 return [x, y] 617 618 def keep_positives(vector: Sequence[T]) -> List[T]: 619 return [item for item in vector if item > 0] 620 621.. class:: Set(set, MutableSet[T]) 622 623 A generic version of :class:`builtins.set <set>`. 624 Useful for annotating return types. To annotate arguments it is preferred 625 to use an abstract collection type such as :class:`AbstractSet`. 626 627.. class:: FrozenSet(frozenset, AbstractSet[T_co]) 628 629 A generic version of :class:`builtins.frozenset <frozenset>`. 630 631.. class:: MappingView(Sized, Iterable[T_co]) 632 633 A generic version of :class:`collections.abc.MappingView`. 634 635.. class:: KeysView(MappingView[KT_co], AbstractSet[KT_co]) 636 637 A generic version of :class:`collections.abc.KeysView`. 638 639.. class:: ItemsView(MappingView, Generic[KT_co, VT_co]) 640 641 A generic version of :class:`collections.abc.ItemsView`. 642 643.. class:: ValuesView(MappingView[VT_co]) 644 645 A generic version of :class:`collections.abc.ValuesView`. 646 647.. class:: Awaitable(Generic[T_co]) 648 649 A generic version of :class:`collections.abc.Awaitable`. 650 651.. class:: Coroutine(Awaitable[V_co], Generic[T_co T_contra, V_co]) 652 653 A generic version of :class:`collections.abc.Coroutine`. 654 The variance and order of type variables 655 correspond to those of :class:`Generator`, for example:: 656 657 from typing import List, Coroutine 658 c = None # type: Coroutine[List[str], str, int] 659 ... 660 x = c.send('hi') # type: List[str] 661 async def bar() -> None: 662 x = await c # type: int 663 664.. class:: AsyncIterable(Generic[T_co]) 665 666 A generic version of :class:`collections.abc.AsyncIterable`. 667 668.. class:: AsyncIterator(AsyncIterable[T_co]) 669 670 A generic version of :class:`collections.abc.AsyncIterator`. 671 672.. class:: ContextManager(Generic[T_co]) 673 674 A generic version of :class:`contextlib.AbstractContextManager`. 675 676 .. versionadded:: 3.6 677 678.. class:: AsyncContextManager(Generic[T_co]) 679 680 A generic version of :class:`contextlib.AbstractAsyncContextManager`. 681 682 .. versionadded:: 3.6 683 684.. class:: Dict(dict, MutableMapping[KT, VT]) 685 686 A generic version of :class:`dict`. 687 Useful for annotating return types. To annotate arguments it is preferred 688 to use an abstract collection type such as :class:`Mapping`. 689 690 This type can be used as follows:: 691 692 def count_words(text: str) -> Dict[str, int]: 693 ... 694 695.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT]) 696 697 A generic version of :class:`collections.defaultdict`. 698 699 .. versionadded:: 3.5.2 700 701.. class:: OrderedDict(collections.OrderedDict, MutableMapping[KT, VT]) 702 703 A generic version of :class:`collections.OrderedDict`. 704 705 .. versionadded:: 3.7.2 706 707.. class:: Counter(collections.Counter, Dict[T, int]) 708 709 A generic version of :class:`collections.Counter`. 710 711 .. versionadded:: 3.6.1 712 713.. class:: ChainMap(collections.ChainMap, MutableMapping[KT, VT]) 714 715 A generic version of :class:`collections.ChainMap`. 716 717 .. versionadded:: 3.6.1 718 719.. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]) 720 721 A generator can be annotated by the generic type 722 ``Generator[YieldType, SendType, ReturnType]``. For example:: 723 724 def echo_round() -> Generator[int, float, str]: 725 sent = yield 0 726 while sent >= 0: 727 sent = yield round(sent) 728 return 'Done' 729 730 Note that unlike many other generics in the typing module, the ``SendType`` 731 of :class:`Generator` behaves contravariantly, not covariantly or 732 invariantly. 733 734 If your generator will only yield values, set the ``SendType`` and 735 ``ReturnType`` to ``None``:: 736 737 def infinite_stream(start: int) -> Generator[int, None, None]: 738 while True: 739 yield start 740 start += 1 741 742 Alternatively, annotate your generator as having a return type of 743 either ``Iterable[YieldType]`` or ``Iterator[YieldType]``:: 744 745 def infinite_stream(start: int) -> Iterator[int]: 746 while True: 747 yield start 748 start += 1 749 750.. class:: AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra]) 751 752 An async generator can be annotated by the generic type 753 ``AsyncGenerator[YieldType, SendType]``. For example:: 754 755 async def echo_round() -> AsyncGenerator[int, float]: 756 sent = yield 0 757 while sent >= 0.0: 758 rounded = await round(sent) 759 sent = yield rounded 760 761 Unlike normal generators, async generators cannot return a value, so there 762 is no ``ReturnType`` type parameter. As with :class:`Generator`, the 763 ``SendType`` behaves contravariantly. 764 765 If your generator will only yield values, set the ``SendType`` to 766 ``None``:: 767 768 async def infinite_stream(start: int) -> AsyncGenerator[int, None]: 769 while True: 770 yield start 771 start = await increment(start) 772 773 Alternatively, annotate your generator as having a return type of 774 either ``AsyncIterable[YieldType]`` or ``AsyncIterator[YieldType]``:: 775 776 async def infinite_stream(start: int) -> AsyncIterator[int]: 777 while True: 778 yield start 779 start = await increment(start) 780 781 .. versionadded:: 3.5.4 782 783.. class:: Text 784 785 ``Text`` is an alias for ``str``. It is provided to supply a forward 786 compatible path for Python 2 code: in Python 2, ``Text`` is an alias for 787 ``unicode``. 788 789 Use ``Text`` to indicate that a value must contain a unicode string in 790 a manner that is compatible with both Python 2 and Python 3:: 791 792 def add_unicode_checkmark(text: Text) -> Text: 793 return text + u' \u2713' 794 795 .. versionadded:: 3.5.2 796 797.. class:: IO 798 TextIO 799 BinaryIO 800 801 Generic type ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])`` 802 and ``BinaryIO(IO[bytes])`` 803 represent the types of I/O streams such as returned by 804 :func:`open`. 805 806.. class:: Pattern 807 Match 808 809 These type aliases 810 correspond to the return types from :func:`re.compile` and 811 :func:`re.match`. These types (and the corresponding functions) 812 are generic in ``AnyStr`` and can be made specific by writing 813 ``Pattern[str]``, ``Pattern[bytes]``, ``Match[str]``, or 814 ``Match[bytes]``. 815 816.. class:: NamedTuple 817 818 Typed version of namedtuple. 819 820 Usage:: 821 822 class Employee(NamedTuple): 823 name: str 824 id: int 825 826 This is equivalent to:: 827 828 Employee = collections.namedtuple('Employee', ['name', 'id']) 829 830 To give a field a default value, you can assign to it in the class body:: 831 832 class Employee(NamedTuple): 833 name: str 834 id: int = 3 835 836 employee = Employee('Guido') 837 assert employee.id == 3 838 839 Fields with a default value must come after any fields without a default. 840 841 The resulting class has two extra attributes: ``_field_types``, 842 giving a dict mapping field names to types, and ``_field_defaults``, a dict 843 mapping field names to default values. (The field names are in the 844 ``_fields`` attribute, which is part of the namedtuple API.) 845 846 ``NamedTuple`` subclasses can also have docstrings and methods:: 847 848 class Employee(NamedTuple): 849 """Represents an employee.""" 850 name: str 851 id: int = 3 852 853 def __repr__(self) -> str: 854 return f'<Employee {self.name}, id={self.id}>' 855 856 Backward-compatible usage:: 857 858 Employee = NamedTuple('Employee', [('name', str), ('id', int)]) 859 860 .. versionchanged:: 3.6 861 Added support for :pep:`526` variable annotation syntax. 862 863 .. versionchanged:: 3.6.1 864 Added support for default values, methods, and docstrings. 865 866.. function:: NewType(typ) 867 868 A helper function to indicate a distinct types to a typechecker, 869 see :ref:`distinct`. At runtime it returns a function that returns 870 its argument. Usage:: 871 872 UserId = NewType('UserId', int) 873 first_user = UserId(1) 874 875 .. versionadded:: 3.5.2 876 877.. function:: cast(typ, val) 878 879 Cast a value to a type. 880 881 This returns the value unchanged. To the type checker this 882 signals that the return value has the designated type, but at 883 runtime we intentionally don't check anything (we want this 884 to be as fast as possible). 885 886.. function:: get_type_hints(obj[, globals[, locals]]) 887 888 Return a dictionary containing type hints for a function, method, module 889 or class object. 890 891 This is often the same as ``obj.__annotations__``. In addition, 892 forward references encoded as string literals are handled by evaluating 893 them in ``globals`` and ``locals`` namespaces. If necessary, 894 ``Optional[t]`` is added for function and method annotations if a default 895 value equal to ``None`` is set. For a class ``C``, return 896 a dictionary constructed by merging all the ``__annotations__`` along 897 ``C.__mro__`` in reverse order. 898 899.. decorator:: overload 900 901 The ``@overload`` decorator allows describing functions and methods 902 that support multiple different combinations of argument types. A series 903 of ``@overload``-decorated definitions must be followed by exactly one 904 non-``@overload``-decorated definition (for the same function/method). 905 The ``@overload``-decorated definitions are for the benefit of the 906 type checker only, since they will be overwritten by the 907 non-``@overload``-decorated definition, while the latter is used at 908 runtime but should be ignored by a type checker. At runtime, calling 909 a ``@overload``-decorated function directly will raise 910 :exc:`NotImplementedError`. An example of overload that gives a more 911 precise type than can be expressed using a union or a type variable:: 912 913 @overload 914 def process(response: None) -> None: 915 ... 916 @overload 917 def process(response: int) -> Tuple[int, str]: 918 ... 919 @overload 920 def process(response: bytes) -> str: 921 ... 922 def process(response): 923 <actual implementation> 924 925 See :pep:`484` for details and comparison with other typing semantics. 926 927.. decorator:: no_type_check 928 929 Decorator to indicate that annotations are not type hints. 930 931 This works as class or function :term:`decorator`. With a class, it 932 applies recursively to all methods defined in that class (but not 933 to methods defined in its superclasses or subclasses). 934 935 This mutates the function(s) in place. 936 937.. decorator:: no_type_check_decorator 938 939 Decorator to give another decorator the :func:`no_type_check` effect. 940 941 This wraps the decorator with something that wraps the decorated 942 function in :func:`no_type_check`. 943 944.. data:: Any 945 946 Special type indicating an unconstrained type. 947 948 * Every type is compatible with :data:`Any`. 949 * :data:`Any` is compatible with every type. 950 951.. data:: NoReturn 952 953 Special type indicating that a function never returns. 954 For example:: 955 956 from typing import NoReturn 957 958 def stop() -> NoReturn: 959 raise RuntimeError('no way') 960 961 .. versionadded:: 3.5.4 962 963.. data:: Union 964 965 Union type; ``Union[X, Y]`` means either X or Y. 966 967 To define a union, use e.g. ``Union[int, str]``. Details: 968 969 * The arguments must be types and there must be at least one. 970 971 * Unions of unions are flattened, e.g.:: 972 973 Union[Union[int, str], float] == Union[int, str, float] 974 975 * Unions of a single argument vanish, e.g.:: 976 977 Union[int] == int # The constructor actually returns int 978 979 * Redundant arguments are skipped, e.g.:: 980 981 Union[int, str, int] == Union[int, str] 982 983 * When comparing unions, the argument order is ignored, e.g.:: 984 985 Union[int, str] == Union[str, int] 986 987 * You cannot subclass or instantiate a union. 988 989 * You cannot write ``Union[X][Y]``. 990 991 * You can use ``Optional[X]`` as a shorthand for ``Union[X, None]``. 992 993 .. versionchanged:: 3.7 994 Don't remove explicit subclasses from unions at runtime. 995 996.. data:: Optional 997 998 Optional type. 999 1000 ``Optional[X]`` is equivalent to ``Union[X, None]``. 1001 1002 Note that this is not the same concept as an optional argument, 1003 which is one that has a default. An optional argument with a 1004 default does not require the ``Optional`` qualifier on its type 1005 annotation just because it is optional. For example:: 1006 1007 def foo(arg: int = 0) -> None: 1008 ... 1009 1010 On the other hand, if an explicit value of ``None`` is allowed, the 1011 use of ``Optional`` is appropriate, whether the argument is optional 1012 or not. For example:: 1013 1014 def foo(arg: Optional[int] = None) -> None: 1015 ... 1016 1017.. data:: Tuple 1018 1019 Tuple type; ``Tuple[X, Y]`` is the type of a tuple of two items 1020 with the first item of type X and the second of type Y. 1021 1022 Example: ``Tuple[T1, T2]`` is a tuple of two elements corresponding 1023 to type variables T1 and T2. ``Tuple[int, float, str]`` is a tuple 1024 of an int, a float and a string. 1025 1026 To specify a variable-length tuple of homogeneous type, 1027 use literal ellipsis, e.g. ``Tuple[int, ...]``. A plain :data:`Tuple` 1028 is equivalent to ``Tuple[Any, ...]``, and in turn to :class:`tuple`. 1029 1030.. data:: Callable 1031 1032 Callable type; ``Callable[[int], str]`` is a function of (int) -> str. 1033 1034 The subscription syntax must always be used with exactly two 1035 values: the argument list and the return type. The argument list 1036 must be a list of types or an ellipsis; the return type must be 1037 a single type. 1038 1039 There is no syntax to indicate optional or keyword arguments; 1040 such function types are rarely used as callback types. 1041 ``Callable[..., ReturnType]`` (literal ellipsis) can be used to 1042 type hint a callable taking any number of arguments and returning 1043 ``ReturnType``. A plain :data:`Callable` is equivalent to 1044 ``Callable[..., Any]``, and in turn to 1045 :class:`collections.abc.Callable`. 1046 1047.. data:: ClassVar 1048 1049 Special type construct to mark class variables. 1050 1051 As introduced in :pep:`526`, a variable annotation wrapped in ClassVar 1052 indicates that a given attribute is intended to be used as a class variable 1053 and should not be set on instances of that class. Usage:: 1054 1055 class Starship: 1056 stats: ClassVar[Dict[str, int]] = {} # class variable 1057 damage: int = 10 # instance variable 1058 1059 :data:`ClassVar` accepts only types and cannot be further subscribed. 1060 1061 :data:`ClassVar` is not a class itself, and should not 1062 be used with :func:`isinstance` or :func:`issubclass`. 1063 :data:`ClassVar` does not change Python runtime behavior, but 1064 it can be used by third-party type checkers. For example, a type checker 1065 might flag the following code as an error:: 1066 1067 enterprise_d = Starship(3000) 1068 enterprise_d.stats = {} # Error, setting class variable on instance 1069 Starship.stats = {} # This is OK 1070 1071 .. versionadded:: 3.5.3 1072 1073.. data:: AnyStr 1074 1075 ``AnyStr`` is a type variable defined as 1076 ``AnyStr = TypeVar('AnyStr', str, bytes)``. 1077 1078 It is meant to be used for functions that may accept any kind of string 1079 without allowing different kinds of strings to mix. For example:: 1080 1081 def concat(a: AnyStr, b: AnyStr) -> AnyStr: 1082 return a + b 1083 1084 concat(u"foo", u"bar") # Ok, output has type 'unicode' 1085 concat(b"foo", b"bar") # Ok, output has type 'bytes' 1086 concat(u"foo", b"bar") # Error, cannot mix unicode and bytes 1087 1088.. data:: TYPE_CHECKING 1089 1090 A special constant that is assumed to be ``True`` by 3rd party static 1091 type checkers. It is ``False`` at runtime. Usage:: 1092 1093 if TYPE_CHECKING: 1094 import expensive_mod 1095 1096 def fun(arg: 'expensive_mod.SomeType') -> None: 1097 local_var: expensive_mod.AnotherType = other_fun() 1098 1099 Note that the first type annotation must be enclosed in quotes, making it a 1100 "forward reference", to hide the ``expensive_mod`` reference from the 1101 interpreter runtime. Type annotations for local variables are not 1102 evaluated, so the second annotation does not need to be enclosed in quotes. 1103 1104 .. versionadded:: 3.5.2 1105