22:mod: `typing ` --- Support for type hints
33========================================
44
5+ .. testsetup :: *
6+
7+ import typing
8+ from typing import *
9+
510.. module :: typing
611 :synopsis: Support for type hints (see :pep: `484 `).
712
@@ -247,19 +252,22 @@ Callable
247252Frameworks expecting callback functions of specific signatures might be
248253type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType] ``.
249254
250- For example::
255+ For example:
256+
257+ .. testcode ::
251258
252259 from collections.abc import Callable
253260
254261 def feeder(get_next_item: Callable[[], str]) -> None:
255- # Body
262+ ... # Body
256263
257264 def async_query(on_success: Callable[[int], None],
258265 on_error: Callable[[int, Exception], None]) -> None:
259- # Body
266+ ... # Body
260267
261268 async def on_update(value: str) -> None:
262- # Body
269+ ... # Body
270+
263271 callback: Callable[[str], Awaitable[None]] = on_update
264272
265273It is possible to declare the return type of a callable without specifying
@@ -402,11 +410,14 @@ In this case ``MyDict`` has a single parameter, ``T``.
402410
403411Using a generic class without specifying type parameters assumes
404412:data: `Any ` for each position. In the following example, ``MyIterable `` is
405- not generic but implicitly inherits from ``Iterable[Any] ``::
413+ not generic but implicitly inherits from ``Iterable[Any] ``:
414+
415+ .. testcode ::
406416
407417 from collections.abc import Iterable
408418
409419 class MyIterable(Iterable): # Same as Iterable[Any]
420+ ...
410421
411422User-defined generic type aliases are also supported. Examples::
412423
@@ -654,9 +665,11 @@ These can be used as types in annotations and do not support ``[]``.
654665 A string created by composing ``LiteralString ``-typed objects
655666 is also acceptable as a ``LiteralString ``.
656667
657- Example::
668+ Example:
669+
670+ .. testcode ::
658671
659- def run_query(sql: LiteralString) -> ...
672+ def run_query(sql: LiteralString) -> None:
660673 ...
661674
662675 def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
@@ -1450,16 +1463,22 @@ for creating generic types.
14501463 def __abs__(self) -> "Array[*Shape]": ...
14511464 def get_shape(self) -> tuple[*Shape]: ...
14521465
1453- Type variable tuples can be happily combined with normal type variables::
1466+ Type variable tuples can be happily combined with normal type variables:
1467+
1468+ .. testcode ::
14541469
14551470 DType = TypeVar('DType')
1471+ Shape = TypeVarTuple('Shape')
14561472
14571473 class Array(Generic[DType, *Shape]): # This is fine
14581474 pass
14591475
14601476 class Array2(Generic[*Shape, DType]): # This would also be fine
14611477 pass
14621478
1479+ class Height: ...
1480+ class Width: ...
1481+
14631482 float_array_1d: Array[float, Height] = Array() # Totally fine
14641483 int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too
14651484
@@ -1904,6 +1923,10 @@ These are not used in annotations. They are building blocks for declaring types.
19041923
19051924 A ``TypedDict `` can be generic::
19061925
1926+ .. testcode ::
1927+
1928+ T = TypeVar("T")
1929+
19071930 class Group(TypedDict, Generic[T]):
19081931 key: T
19091932 group: list[T]
@@ -1915,7 +1938,9 @@ These are not used in annotations. They are building blocks for declaring types.
19151938 .. attribute :: __total__
19161939
19171940 ``Point2D.__total__ `` gives the value of the ``total `` argument.
1918- Example::
1941+ Example:
1942+
1943+ .. doctest ::
19191944
19201945 >>> from typing import TypedDict
19211946 >>> class Point2D (TypedDict ): pass
@@ -1945,7 +1970,9 @@ These are not used in annotations. They are building blocks for declaring types.
19451970 non-required keys in the same ``TypedDict `` . This is done by declaring a
19461971 ``TypedDict `` with one value for the ``total `` argument and then
19471972 inheriting from it in another ``TypedDict `` with a different value for
1948- ``total ``::
1973+ ``total ``:
1974+
1975+ .. doctest ::
19491976
19501977 >>> class Point2D (TypedDict , total = False ):
19511978 ... x: int
@@ -2600,7 +2627,9 @@ Functions and decorators
26002627 decorated object performs runtime "magic" that
26012628 transforms a class, giving it :func: `dataclasses.dataclass `-like behaviors.
26022629
2603- Example usage with a decorator function::
2630+ Example usage with a decorator function:
2631+
2632+ .. testcode ::
26042633
26052634 T = TypeVar("T")
26062635
@@ -2705,7 +2734,9 @@ Functions and decorators
27052734 runtime but should be ignored by a type checker. At runtime, calling
27062735 a ``@overload ``-decorated function directly will raise
27072736 :exc: `NotImplementedError `. An example of overload that gives a more
2708- precise type than can be expressed using a union or a type variable::
2737+ precise type than can be expressed using a union or a type variable:
2738+
2739+ .. testcode ::
27092740
27102741 @overload
27112742 def process(response: None) -> None:
@@ -2717,7 +2748,7 @@ Functions and decorators
27172748 def process(response: bytes) -> str:
27182749 ...
27192750 def process(response):
2720- < actual implementation>
2751+ ... # actual implementation goes here
27212752
27222753 See :pep: `484 ` for more details and comparison with other typing semantics.
27232754
@@ -2835,14 +2866,16 @@ Introspection helpers
28352866
28362867 The function recursively replaces all ``Annotated[T, ...] `` with ``T ``,
28372868 unless ``include_extras `` is set to ``True `` (see :class: `Annotated ` for
2838- more information). For example::
2869+ more information). For example:
2870+
2871+ .. testcode ::
28392872
28402873 class Student(NamedTuple):
28412874 name: Annotated[str, 'some marker']
28422875
2843- get_type_hints(Student) == {'name': str}
2844- get_type_hints(Student, include_extras=False) == {'name': str}
2845- get_type_hints(Student, include_extras=True) == {
2876+ assert get_type_hints(Student) == {'name': str}
2877+ assert get_type_hints(Student, include_extras=False) == {'name': str}
2878+ assert get_type_hints(Student, include_extras=True) == {
28462879 'name': Annotated[str, 'some marker']
28472880 }
28482881
@@ -2869,7 +2902,9 @@ Introspection helpers
28692902 If ``X `` is an instance of :class: `ParamSpecArgs ` or :class: `ParamSpecKwargs `,
28702903 return the underlying :class: `ParamSpec `.
28712904 Return ``None `` for unsupported objects.
2872- Examples::
2905+ Examples:
2906+
2907+ .. testcode ::
28732908
28742909 assert get_origin(str) is None
28752910 assert get_origin(Dict[str, int]) is dict
@@ -2888,7 +2923,9 @@ Introspection helpers
28882923 generic type, the order of ``(Y, Z, ...) `` may be different from the order
28892924 of the original arguments ``[Y, Z, ...] `` due to type caching.
28902925 Return ``() `` for unsupported objects.
2891- Examples::
2926+ Examples:
2927+
2928+ .. testcode ::
28922929
28932930 assert get_args(int) == ()
28942931 assert get_args(Dict[int, str]) == (int, str)
@@ -2900,14 +2937,20 @@ Introspection helpers
29002937
29012938 Check if a type is a :class: `TypedDict `.
29022939
2903- For example::
2940+ For example:
2941+
2942+ .. testcode ::
29042943
29052944 class Film(TypedDict):
29062945 title: str
29072946 year: int
29082947
2909- is_typeddict(Film) # => True
2910- is_typeddict(list | str) # => False
2948+ assert is_typeddict(Film)
2949+ assert not is_typeddict(list | str)
2950+
2951+ # TypedDict is a factory for creating typed dicts,
2952+ # not a typed dict itself
2953+ assert not is_typeddict(TypedDict)
29112954
29122955 .. versionadded :: 3.10
29132956
0 commit comments