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__
@@ -2158,7 +2178,11 @@ These are not used in annotations. They are building blocks for declaring types.
2158
2178
group: list[T]
2159
2179
2160
2180
To create a generic ``TypedDict `` that is compatible with Python 3.11
2161
- or lower, inherit from :class: `Generic ` explicitly::
2181
+ or lower, inherit from :class: `Generic ` explicitly:
2182
+
2183
+ .. testcode ::
2184
+
2185
+ T = TypeVar("T")
2162
2186
2163
2187
class Group(TypedDict, Generic[T]):
2164
2188
key: T
@@ -2171,7 +2195,9 @@ These are not used in annotations. They are building blocks for declaring types.
2171
2195
.. attribute :: __total__
2172
2196
2173
2197
``Point2D.__total__ `` gives the value of the ``total `` argument.
2174
- Example::
2198
+ Example:
2199
+
2200
+ .. doctest ::
2175
2201
2176
2202
>>> from typing import TypedDict
2177
2203
>>> class Point2D (TypedDict ): pass
@@ -2201,7 +2227,9 @@ These are not used in annotations. They are building blocks for declaring types.
2201
2227
non-required keys in the same ``TypedDict `` . This is done by declaring a
2202
2228
``TypedDict `` with one value for the ``total `` argument and then
2203
2229
inheriting from it in another ``TypedDict `` with a different value for
2204
- ``total ``::
2230
+ ``total ``:
2231
+
2232
+ .. doctest ::
2205
2233
2206
2234
>>> class Point2D (TypedDict , total = False ):
2207
2235
... x: int
@@ -2860,12 +2888,12 @@ Functions and decorators
2860
2888
decorated object performs runtime "magic" that
2861
2889
transforms a class, giving it :func: `dataclasses.dataclass `-like behaviors.
2862
2890
2863
- Example usage with a decorator function::
2891
+ Example usage with a decorator function:
2864
2892
2865
- T = TypeVar("T")
2893
+ .. testcode ::
2866
2894
2867
2895
@dataclass_transform()
2868
- def create_model(cls: type[T]) -> type[T]:
2896
+ def create_model[T] (cls: type[T]) -> type[T]:
2869
2897
...
2870
2898
return cls
2871
2899
@@ -2969,7 +2997,9 @@ Functions and decorators
2969
2997
runtime but should be ignored by a type checker. At runtime, calling
2970
2998
a ``@overload ``-decorated function directly will raise
2971
2999
:exc: `NotImplementedError `. An example of overload that gives a more
2972
- precise type than can be expressed using a union or a type variable::
3000
+ precise type than can be expressed using a union or a type variable:
3001
+
3002
+ .. testcode ::
2973
3003
2974
3004
@overload
2975
3005
def process(response: None) -> None:
@@ -2981,7 +3011,7 @@ Functions and decorators
2981
3011
def process(response: bytes) -> str:
2982
3012
...
2983
3013
def process(response):
2984
- < actual implementation>
3014
+ ... # actual implementation goes here
2985
3015
2986
3016
See :pep: `484 ` for more details and comparison with other typing semantics.
2987
3017
@@ -3073,10 +3103,13 @@ Functions and decorators
3073
3103
This helps prevent bugs that may occur when a base class is changed without
3074
3104
an equivalent change to a child class.
3075
3105
3076
- For example::
3106
+ For example:
3107
+
3108
+ .. testcode ::
3077
3109
3078
3110
class Base:
3079
- def log_status(self)
3111
+ def log_status(self) -> None:
3112
+ ...
3080
3113
3081
3114
class Sub(Base):
3082
3115
@override
@@ -3135,14 +3168,16 @@ Introspection helpers
3135
3168
3136
3169
The function recursively replaces all ``Annotated[T, ...] `` with ``T ``,
3137
3170
unless ``include_extras `` is set to ``True `` (see :class: `Annotated ` for
3138
- more information). For example::
3171
+ more information). For example:
3172
+
3173
+ .. testcode ::
3139
3174
3140
3175
class Student(NamedTuple):
3141
3176
name: Annotated[str, 'some marker']
3142
3177
3143
- get_type_hints(Student) == {'name': str}
3144
- get_type_hints(Student, include_extras=False) == {'name': str}
3145
- get_type_hints(Student, include_extras=True) == {
3178
+ assert get_type_hints(Student) == {'name': str}
3179
+ assert get_type_hints(Student, include_extras=False) == {'name': str}
3180
+ assert get_type_hints(Student, include_extras=True) == {
3146
3181
'name': Annotated[str, 'some marker']
3147
3182
}
3148
3183
@@ -3169,7 +3204,9 @@ Introspection helpers
3169
3204
If ``X `` is an instance of :class: `ParamSpecArgs ` or :class: `ParamSpecKwargs `,
3170
3205
return the underlying :class: `ParamSpec `.
3171
3206
Return ``None `` for unsupported objects.
3172
- Examples::
3207
+ Examples:
3208
+
3209
+ .. testcode ::
3173
3210
3174
3211
assert get_origin(str) is None
3175
3212
assert get_origin(Dict[str, int]) is dict
@@ -3188,7 +3225,9 @@ Introspection helpers
3188
3225
generic type, the order of ``(Y, Z, ...) `` may be different from the order
3189
3226
of the original arguments ``[Y, Z, ...] `` due to type caching.
3190
3227
Return ``() `` for unsupported objects.
3191
- Examples::
3228
+ Examples:
3229
+
3230
+ .. testcode ::
3192
3231
3193
3232
assert get_args(int) == ()
3194
3233
assert get_args(Dict[int, str]) == (int, str)
@@ -3200,14 +3239,20 @@ Introspection helpers
3200
3239
3201
3240
Check if a type is a :class: `TypedDict `.
3202
3241
3203
- For example::
3242
+ For example:
3243
+
3244
+ .. testcode ::
3204
3245
3205
3246
class Film(TypedDict):
3206
3247
title: str
3207
3248
year: int
3208
3249
3209
- is_typeddict(Film) # => True
3210
- is_typeddict(list | str) # => False
3250
+ assert is_typeddict(Film)
3251
+ assert not is_typeddict(list | str)
3252
+
3253
+ # TypedDict is a factory for creating typed dicts,
3254
+ # not a typed dict itself
3255
+ assert not is_typeddict(TypedDict)
3211
3256
3212
3257
.. versionadded :: 3.10
3213
3258
0 commit comments