2
2
:mod: `typing ` --- Support for type hints
3
3
========================================
4
4
5
+ .. testsetup :: *
6
+
7
+ import typing
8
+ from typing import *
9
+
5
10
.. module :: typing
6
11
:synopsis: Support for type hints (see :pep: `484 `).
7
12
@@ -247,19 +252,22 @@ Callable
247
252
Frameworks expecting callback functions of specific signatures might be
248
253
type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType] ``.
249
254
250
- For example::
255
+ For example:
256
+
257
+ .. testcode ::
251
258
252
259
from collections.abc import Callable
253
260
254
261
def feeder(get_next_item: Callable[[], str]) -> None:
255
- # Body
262
+ ... # Body
256
263
257
264
def async_query(on_success: Callable[[int], None],
258
265
on_error: Callable[[int, Exception], None]) -> None:
259
- # Body
266
+ ... # Body
260
267
261
268
async def on_update(value: str) -> None:
262
- # Body
269
+ ... # Body
270
+
263
271
callback: Callable[[str], Awaitable[None]] = on_update
264
272
265
273
It 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``.
402
410
403
411
Using a generic class without specifying type parameters assumes
404
412
: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 ::
406
416
407
417
from collections.abc import Iterable
408
418
409
419
class MyIterable(Iterable): # Same as Iterable[Any]
420
+ ...
410
421
411
422
User-defined generic type aliases are also supported. Examples::
412
423
@@ -654,9 +665,11 @@ These can be used as types in annotations and do not support ``[]``.
654
665
A string created by composing ``LiteralString ``-typed objects
655
666
is also acceptable as a ``LiteralString ``.
656
667
657
- Example::
668
+ Example:
669
+
670
+ .. testcode ::
658
671
659
- def run_query(sql: LiteralString) -> ...
672
+ def run_query(sql: LiteralString) -> None:
660
673
...
661
674
662
675
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
@@ -1450,16 +1463,22 @@ for creating generic types.
1450
1463
def __abs__(self) -> "Array[*Shape]": ...
1451
1464
def get_shape(self) -> tuple[*Shape]: ...
1452
1465
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 ::
1454
1469
1455
1470
DType = TypeVar('DType')
1471
+ Shape = TypeVarTuple('Shape')
1456
1472
1457
1473
class Array(Generic[DType, *Shape]): # This is fine
1458
1474
pass
1459
1475
1460
1476
class Array2(Generic[*Shape, DType]): # This would also be fine
1461
1477
pass
1462
1478
1479
+ class Height: ...
1480
+ class Width: ...
1481
+
1463
1482
float_array_1d: Array[float, Height] = Array() # Totally fine
1464
1483
int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too
1465
1484
@@ -1904,6 +1923,10 @@ These are not used in annotations. They are building blocks for declaring types.
1904
1923
1905
1924
A ``TypedDict `` can be generic::
1906
1925
1926
+ .. testcode ::
1927
+
1928
+ T = TypeVar("T")
1929
+
1907
1930
class Group(TypedDict, Generic[T]):
1908
1931
key: T
1909
1932
group: list[T]
@@ -1915,7 +1938,9 @@ These are not used in annotations. They are building blocks for declaring types.
1915
1938
.. attribute :: __total__
1916
1939
1917
1940
``Point2D.__total__ `` gives the value of the ``total `` argument.
1918
- Example::
1941
+ Example:
1942
+
1943
+ .. doctest ::
1919
1944
1920
1945
>>> from typing import TypedDict
1921
1946
>>> class Point2D (TypedDict ): pass
@@ -1945,7 +1970,9 @@ These are not used in annotations. They are building blocks for declaring types.
1945
1970
non-required keys in the same ``TypedDict `` . This is done by declaring a
1946
1971
``TypedDict `` with one value for the ``total `` argument and then
1947
1972
inheriting from it in another ``TypedDict `` with a different value for
1948
- ``total ``::
1973
+ ``total ``:
1974
+
1975
+ .. doctest ::
1949
1976
1950
1977
>>> class Point2D (TypedDict , total = False ):
1951
1978
... x: int
@@ -2600,7 +2627,9 @@ Functions and decorators
2600
2627
decorated object performs runtime "magic" that
2601
2628
transforms a class, giving it :func: `dataclasses.dataclass `-like behaviors.
2602
2629
2603
- Example usage with a decorator function::
2630
+ Example usage with a decorator function:
2631
+
2632
+ .. testcode ::
2604
2633
2605
2634
T = TypeVar("T")
2606
2635
@@ -2705,7 +2734,9 @@ Functions and decorators
2705
2734
runtime but should be ignored by a type checker. At runtime, calling
2706
2735
a ``@overload ``-decorated function directly will raise
2707
2736
: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 ::
2709
2740
2710
2741
@overload
2711
2742
def process(response: None) -> None:
@@ -2717,7 +2748,7 @@ Functions and decorators
2717
2748
def process(response: bytes) -> str:
2718
2749
...
2719
2750
def process(response):
2720
- < actual implementation>
2751
+ ... # actual implementation goes here
2721
2752
2722
2753
See :pep: `484 ` for more details and comparison with other typing semantics.
2723
2754
@@ -2835,14 +2866,16 @@ Introspection helpers
2835
2866
2836
2867
The function recursively replaces all ``Annotated[T, ...] `` with ``T ``,
2837
2868
unless ``include_extras `` is set to ``True `` (see :class: `Annotated ` for
2838
- more information). For example::
2869
+ more information). For example:
2870
+
2871
+ .. testcode ::
2839
2872
2840
2873
class Student(NamedTuple):
2841
2874
name: Annotated[str, 'some marker']
2842
2875
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) == {
2846
2879
'name': Annotated[str, 'some marker']
2847
2880
}
2848
2881
@@ -2869,7 +2902,9 @@ Introspection helpers
2869
2902
If ``X `` is an instance of :class: `ParamSpecArgs ` or :class: `ParamSpecKwargs `,
2870
2903
return the underlying :class: `ParamSpec `.
2871
2904
Return ``None `` for unsupported objects.
2872
- Examples::
2905
+ Examples:
2906
+
2907
+ .. testcode ::
2873
2908
2874
2909
assert get_origin(str) is None
2875
2910
assert get_origin(Dict[str, int]) is dict
@@ -2888,7 +2923,9 @@ Introspection helpers
2888
2923
generic type, the order of ``(Y, Z, ...) `` may be different from the order
2889
2924
of the original arguments ``[Y, Z, ...] `` due to type caching.
2890
2925
Return ``() `` for unsupported objects.
2891
- Examples::
2926
+ Examples:
2927
+
2928
+ .. testcode ::
2892
2929
2893
2930
assert get_args(int) == ()
2894
2931
assert get_args(Dict[int, str]) == (int, str)
@@ -2900,14 +2937,20 @@ Introspection helpers
2900
2937
2901
2938
Check if a type is a :class: `TypedDict `.
2902
2939
2903
- For example::
2940
+ For example:
2941
+
2942
+ .. testcode ::
2904
2943
2905
2944
class Film(TypedDict):
2906
2945
title: str
2907
2946
year: int
2908
2947
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)
2911
2954
2912
2955
.. versionadded :: 3.10
2913
2956
0 commit comments