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
@@ -261,19 +266,22 @@ Callable
261
266
Frameworks expecting callback functions of specific signatures might be
262
267
type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType] ``.
263
268
264
- For example::
269
+ For example:
270
+
271
+ .. testcode ::
265
272
266
273
from collections.abc import Callable
267
274
268
275
def feeder(get_next_item: Callable[[], str]) -> None:
269
- # Body
276
+ ... # Body
270
277
271
278
def async_query(on_success: Callable[[int], None],
272
279
on_error: Callable[[int, Exception], None]) -> None:
273
- # Body
280
+ ... # Body
274
281
275
282
async def on_update(value: str) -> None:
276
- # Body
283
+ ... # Body
284
+
277
285
callback: Callable[[str], Awaitable[None]] = on_update
278
286
279
287
It is possible to declare the return type of a callable without specifying
@@ -431,11 +439,14 @@ In this case ``MyDict`` has a single parameter, ``T``.
431
439
432
440
Using a generic class without specifying type parameters assumes
433
441
:data: `Any ` for each position. In the following example, ``MyIterable `` is
434
- not generic but implicitly inherits from ``Iterable[Any] ``::
442
+ not generic but implicitly inherits from ``Iterable[Any] ``:
443
+
444
+ .. testcode ::
435
445
436
446
from collections.abc import Iterable
437
447
438
448
class MyIterable(Iterable): # Same as Iterable[Any]
449
+ ...
439
450
440
451
User-defined generic type aliases are also supported. Examples::
441
452
@@ -701,9 +712,11 @@ These can be used as types in annotations and do not support ``[]``.
701
712
A string created by composing ``LiteralString ``-typed objects
702
713
is also acceptable as a ``LiteralString ``.
703
714
704
- Example::
715
+ Example:
716
+
717
+ .. testcode ::
705
718
706
- def run_query(sql: LiteralString) -> ...
719
+ def run_query(sql: LiteralString) -> None:
707
720
...
708
721
709
722
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
@@ -1596,16 +1609,19 @@ without the dedicated syntax, as documented below.
1596
1609
def __abs__(self) -> "Array[*Shape]": ...
1597
1610
def get_shape(self) -> tuple[*Shape]: ...
1598
1611
1599
- Type variable tuples can be happily combined with normal type variables::
1612
+ Type variable tuples can be happily combined with normal type variables:
1600
1613
1601
- DType = TypeVar('DType')
1614
+ .. testcode ::
1602
1615
1603
1616
class Array[DType, *Shape]: # This is fine
1604
1617
pass
1605
1618
1606
1619
class Array2[*Shape, DType]: # This would also be fine
1607
1620
pass
1608
1621
1622
+ class Height: ...
1623
+ class Width: ...
1624
+
1609
1625
float_array_1d: Array[float, Height] = Array() # Totally fine
1610
1626
int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too
1611
1627
@@ -1759,7 +1775,9 @@ without the dedicated syntax, as documented below.
1759
1775
1760
1776
The type of type aliases created through the :keyword: `type ` statement.
1761
1777
1762
- Example::
1778
+ Example:
1779
+
1780
+ .. doctest ::
1763
1781
1764
1782
>>> type Alias = int
1765
1783
>>> type (Alias)
@@ -1769,7 +1787,9 @@ without the dedicated syntax, as documented below.
1769
1787
1770
1788
.. attribute :: __name__
1771
1789
1772
- The name of the type alias::
1790
+ The name of the type alias:
1791
+
1792
+ .. doctest ::
1773
1793
1774
1794
>>> type Alias = int
1775
1795
>>> Alias.__name__
@@ -2147,7 +2167,11 @@ These are not used in annotations. They are building blocks for declaring types.
2147
2167
group: list[T]
2148
2168
2149
2169
To create a generic ``TypedDict `` that is compatible with Python 3.11
2150
- or lower, inherit from :class: `Generic ` explicitly::
2170
+ or lower, inherit from :class: `Generic ` explicitly:
2171
+
2172
+ .. testcode ::
2173
+
2174
+ T = TypeVar("T")
2151
2175
2152
2176
class Group(TypedDict, Generic[T]):
2153
2177
key: T
@@ -2160,7 +2184,9 @@ These are not used in annotations. They are building blocks for declaring types.
2160
2184
.. attribute :: __total__
2161
2185
2162
2186
``Point2D.__total__ `` gives the value of the ``total `` argument.
2163
- Example::
2187
+ Example:
2188
+
2189
+ .. doctest ::
2164
2190
2165
2191
>>> from typing import TypedDict
2166
2192
>>> class Point2D (TypedDict ): pass
@@ -2190,7 +2216,9 @@ These are not used in annotations. They are building blocks for declaring types.
2190
2216
non-required keys in the same ``TypedDict `` . This is done by declaring a
2191
2217
``TypedDict `` with one value for the ``total `` argument and then
2192
2218
inheriting from it in another ``TypedDict `` with a different value for
2193
- ``total ``::
2219
+ ``total ``:
2220
+
2221
+ .. doctest ::
2194
2222
2195
2223
>>> class Point2D (TypedDict , total = False ):
2196
2224
... x: int
@@ -2844,12 +2872,12 @@ Functions and decorators
2844
2872
decorated object performs runtime "magic" that
2845
2873
transforms a class, giving it :func: `dataclasses.dataclass `-like behaviors.
2846
2874
2847
- Example usage with a decorator function::
2875
+ Example usage with a decorator function:
2848
2876
2849
- T = TypeVar("T")
2877
+ .. testcode ::
2850
2878
2851
2879
@dataclass_transform()
2852
- def create_model(cls: type[T]) -> type[T]:
2880
+ def create_model[T] (cls: type[T]) -> type[T]:
2853
2881
...
2854
2882
return cls
2855
2883
@@ -2953,7 +2981,9 @@ Functions and decorators
2953
2981
runtime but should be ignored by a type checker. At runtime, calling
2954
2982
a ``@overload ``-decorated function directly will raise
2955
2983
:exc: `NotImplementedError `. An example of overload that gives a more
2956
- precise type than can be expressed using a union or a type variable::
2984
+ precise type than can be expressed using a union or a type variable:
2985
+
2986
+ .. testcode ::
2957
2987
2958
2988
@overload
2959
2989
def process(response: None) -> None:
@@ -2965,7 +2995,7 @@ Functions and decorators
2965
2995
def process(response: bytes) -> str:
2966
2996
...
2967
2997
def process(response):
2968
- < actual implementation>
2998
+ ... # actual implementation goes here
2969
2999
2970
3000
See :pep: `484 ` for more details and comparison with other typing semantics.
2971
3001
@@ -3057,10 +3087,13 @@ Functions and decorators
3057
3087
This helps prevent bugs that may occur when a base class is changed without
3058
3088
an equivalent change to a child class.
3059
3089
3060
- For example::
3090
+ For example:
3091
+
3092
+ .. testcode ::
3061
3093
3062
3094
class Base:
3063
- def log_status(self)
3095
+ def log_status(self) -> None:
3096
+ ...
3064
3097
3065
3098
class Sub(Base):
3066
3099
@override
@@ -3119,14 +3152,16 @@ Introspection helpers
3119
3152
3120
3153
The function recursively replaces all ``Annotated[T, ...] `` with ``T ``,
3121
3154
unless ``include_extras `` is set to ``True `` (see :class: `Annotated ` for
3122
- more information). For example::
3155
+ more information). For example:
3156
+
3157
+ .. testcode ::
3123
3158
3124
3159
class Student(NamedTuple):
3125
3160
name: Annotated[str, 'some marker']
3126
3161
3127
- get_type_hints(Student) == {'name': str}
3128
- get_type_hints(Student, include_extras=False) == {'name': str}
3129
- get_type_hints(Student, include_extras=True) == {
3162
+ assert get_type_hints(Student) == {'name': str}
3163
+ assert get_type_hints(Student, include_extras=False) == {'name': str}
3164
+ assert get_type_hints(Student, include_extras=True) == {
3130
3165
'name': Annotated[str, 'some marker']
3131
3166
}
3132
3167
@@ -3153,7 +3188,9 @@ Introspection helpers
3153
3188
If ``X `` is an instance of :class: `ParamSpecArgs ` or :class: `ParamSpecKwargs `,
3154
3189
return the underlying :class: `ParamSpec `.
3155
3190
Return ``None `` for unsupported objects.
3156
- Examples::
3191
+ Examples:
3192
+
3193
+ .. testcode ::
3157
3194
3158
3195
assert get_origin(str) is None
3159
3196
assert get_origin(Dict[str, int]) is dict
@@ -3172,7 +3209,9 @@ Introspection helpers
3172
3209
generic type, the order of ``(Y, Z, ...) `` may be different from the order
3173
3210
of the original arguments ``[Y, Z, ...] `` due to type caching.
3174
3211
Return ``() `` for unsupported objects.
3175
- Examples::
3212
+ Examples:
3213
+
3214
+ .. testcode ::
3176
3215
3177
3216
assert get_args(int) == ()
3178
3217
assert get_args(Dict[int, str]) == (int, str)
@@ -3184,14 +3223,20 @@ Introspection helpers
3184
3223
3185
3224
Check if a type is a :class: `TypedDict `.
3186
3225
3187
- For example::
3226
+ For example:
3227
+
3228
+ .. testcode ::
3188
3229
3189
3230
class Film(TypedDict):
3190
3231
title: str
3191
3232
year: int
3192
3233
3193
- is_typeddict(Film) # => True
3194
- is_typeddict(list | str) # => False
3234
+ assert is_typeddict(Film)
3235
+ assert not is_typeddict(list | str)
3236
+
3237
+ # TypedDict is a factory for creating typed dicts,
3238
+ # not a typed dict itself
3239
+ assert not is_typeddict(TypedDict)
3195
3240
3196
3241
.. versionadded :: 3.10
3197
3242
0 commit comments