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
@@ -251,19 +256,22 @@ Callable
251
256
Frameworks expecting callback functions of specific signatures might be
252
257
type hinted using ``Callable[[Arg1Type, Arg2Type], ReturnType] ``.
253
258
254
- For example::
259
+ For example:
260
+
261
+ .. testcode ::
255
262
256
263
from collections.abc import Callable
257
264
258
265
def feeder(get_next_item: Callable[[], str]) -> None:
259
- # Body
266
+ ... # Body
260
267
261
268
def async_query(on_success: Callable[[int], None],
262
269
on_error: Callable[[int, Exception], None]) -> None:
263
- # Body
270
+ ... # Body
264
271
265
272
async def on_update(value: str) -> None:
266
- # Body
273
+ ... # Body
274
+
267
275
callback: Callable[[str], Awaitable[None]] = on_update
268
276
269
277
It is possible to declare the return type of a callable without specifying
@@ -421,11 +429,14 @@ In this case ``MyDict`` has a single parameter, ``T``.
421
429
422
430
Using a generic class without specifying type parameters assumes
423
431
:data: `Any ` for each position. In the following example, ``MyIterable `` is
424
- not generic but implicitly inherits from ``Iterable[Any] ``::
432
+ not generic but implicitly inherits from ``Iterable[Any] ``:
433
+
434
+ .. testcode ::
425
435
426
436
from collections.abc import Iterable
427
437
428
438
class MyIterable(Iterable): # Same as Iterable[Any]
439
+ ...
429
440
430
441
User-defined generic type aliases are also supported. Examples::
431
442
@@ -691,9 +702,11 @@ These can be used as types in annotations and do not support ``[]``.
691
702
A string created by composing ``LiteralString ``-typed objects
692
703
is also acceptable as a ``LiteralString ``.
693
704
694
- Example::
705
+ Example:
706
+
707
+ .. testcode ::
695
708
696
- def run_query(sql: LiteralString) -> ...
709
+ def run_query(sql: LiteralString) -> None:
697
710
...
698
711
699
712
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
@@ -1586,16 +1599,19 @@ without the dedicated syntax, as documented below.
1586
1599
def __abs__(self) -> "Array[*Shape]": ...
1587
1600
def get_shape(self) -> tuple[*Shape]: ...
1588
1601
1589
- Type variable tuples can be happily combined with normal type variables::
1602
+ Type variable tuples can be happily combined with normal type variables:
1590
1603
1591
- DType = TypeVar('DType')
1604
+ .. testcode ::
1592
1605
1593
1606
class Array[DType, *Shape]: # This is fine
1594
1607
pass
1595
1608
1596
1609
class Array2[*Shape, DType]: # This would also be fine
1597
1610
pass
1598
1611
1612
+ class Height: ...
1613
+ class Width: ...
1614
+
1599
1615
float_array_1d: Array[float, Height] = Array() # Totally fine
1600
1616
int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too
1601
1617
@@ -1749,7 +1765,9 @@ without the dedicated syntax, as documented below.
1749
1765
1750
1766
The type of type aliases created through the :keyword: `type ` statement.
1751
1767
1752
- Example::
1768
+ Example:
1769
+
1770
+ .. doctest ::
1753
1771
1754
1772
>>> type Alias = int
1755
1773
>>> type (Alias)
@@ -1759,7 +1777,9 @@ without the dedicated syntax, as documented below.
1759
1777
1760
1778
.. attribute :: __name__
1761
1779
1762
- The name of the type alias::
1780
+ The name of the type alias:
1781
+
1782
+ .. doctest ::
1763
1783
1764
1784
>>> type Alias = int
1765
1785
>>> Alias.__name__
@@ -2148,7 +2168,11 @@ These are not used in annotations. They are building blocks for declaring types.
2148
2168
group: list[T]
2149
2169
2150
2170
To create a generic ``TypedDict `` that is compatible with Python 3.11
2151
- or lower, inherit from :class: `Generic ` explicitly::
2171
+ or lower, inherit from :class: `Generic ` explicitly:
2172
+
2173
+ .. testcode ::
2174
+
2175
+ T = TypeVar("T")
2152
2176
2153
2177
class Group(TypedDict, Generic[T]):
2154
2178
key: T
@@ -2161,7 +2185,9 @@ These are not used in annotations. They are building blocks for declaring types.
2161
2185
.. attribute :: __total__
2162
2186
2163
2187
``Point2D.__total__ `` gives the value of the ``total `` argument.
2164
- Example::
2188
+ Example:
2189
+
2190
+ .. doctest ::
2165
2191
2166
2192
>>> from typing import TypedDict
2167
2193
>>> class Point2D (TypedDict ): pass
@@ -2191,7 +2217,9 @@ These are not used in annotations. They are building blocks for declaring types.
2191
2217
non-required keys in the same ``TypedDict `` . This is done by declaring a
2192
2218
``TypedDict `` with one value for the ``total `` argument and then
2193
2219
inheriting from it in another ``TypedDict `` with a different value for
2194
- ``total ``::
2220
+ ``total ``:
2221
+
2222
+ .. doctest ::
2195
2223
2196
2224
>>> class Point2D (TypedDict , total = False ):
2197
2225
... x: int
@@ -2850,12 +2878,12 @@ Functions and decorators
2850
2878
decorated object performs runtime "magic" that
2851
2879
transforms a class, giving it :func: `dataclasses.dataclass `-like behaviors.
2852
2880
2853
- Example usage with a decorator function::
2881
+ Example usage with a decorator function:
2854
2882
2855
- T = TypeVar("T")
2883
+ .. testcode ::
2856
2884
2857
2885
@dataclass_transform()
2858
- def create_model(cls: type[T]) -> type[T]:
2886
+ def create_model[T] (cls: type[T]) -> type[T]:
2859
2887
...
2860
2888
return cls
2861
2889
@@ -2959,7 +2987,9 @@ Functions and decorators
2959
2987
runtime but should be ignored by a type checker. At runtime, calling
2960
2988
a ``@overload ``-decorated function directly will raise
2961
2989
:exc: `NotImplementedError `. An example of overload that gives a more
2962
- precise type than can be expressed using a union or a type variable::
2990
+ precise type than can be expressed using a union or a type variable:
2991
+
2992
+ .. testcode ::
2963
2993
2964
2994
@overload
2965
2995
def process(response: None) -> None:
@@ -2971,7 +3001,7 @@ Functions and decorators
2971
3001
def process(response: bytes) -> str:
2972
3002
...
2973
3003
def process(response):
2974
- < actual implementation>
3004
+ ... # actual implementation goes here
2975
3005
2976
3006
See :pep: `484 ` for more details and comparison with other typing semantics.
2977
3007
@@ -3063,10 +3093,13 @@ Functions and decorators
3063
3093
This helps prevent bugs that may occur when a base class is changed without
3064
3094
an equivalent change to a child class.
3065
3095
3066
- For example::
3096
+ For example:
3097
+
3098
+ .. testcode ::
3067
3099
3068
3100
class Base:
3069
- def log_status(self)
3101
+ def log_status(self) -> None:
3102
+ ...
3070
3103
3071
3104
class Sub(Base):
3072
3105
@override
@@ -3125,14 +3158,16 @@ Introspection helpers
3125
3158
3126
3159
The function recursively replaces all ``Annotated[T, ...] `` with ``T ``,
3127
3160
unless ``include_extras `` is set to ``True `` (see :class: `Annotated ` for
3128
- more information). For example::
3161
+ more information). For example:
3162
+
3163
+ .. testcode ::
3129
3164
3130
3165
class Student(NamedTuple):
3131
3166
name: Annotated[str, 'some marker']
3132
3167
3133
- get_type_hints(Student) == {'name': str}
3134
- get_type_hints(Student, include_extras=False) == {'name': str}
3135
- get_type_hints(Student, include_extras=True) == {
3168
+ assert get_type_hints(Student) == {'name': str}
3169
+ assert get_type_hints(Student, include_extras=False) == {'name': str}
3170
+ assert get_type_hints(Student, include_extras=True) == {
3136
3171
'name': Annotated[str, 'some marker']
3137
3172
}
3138
3173
@@ -3159,7 +3194,9 @@ Introspection helpers
3159
3194
If ``X `` is an instance of :class: `ParamSpecArgs ` or :class: `ParamSpecKwargs `,
3160
3195
return the underlying :class: `ParamSpec `.
3161
3196
Return ``None `` for unsupported objects.
3162
- Examples::
3197
+ Examples:
3198
+
3199
+ .. testcode ::
3163
3200
3164
3201
assert get_origin(str) is None
3165
3202
assert get_origin(Dict[str, int]) is dict
@@ -3178,7 +3215,9 @@ Introspection helpers
3178
3215
generic type, the order of ``(Y, Z, ...) `` may be different from the order
3179
3216
of the original arguments ``[Y, Z, ...] `` due to type caching.
3180
3217
Return ``() `` for unsupported objects.
3181
- Examples::
3218
+ Examples:
3219
+
3220
+ .. testcode ::
3182
3221
3183
3222
assert get_args(int) == ()
3184
3223
assert get_args(Dict[int, str]) == (int, str)
@@ -3190,14 +3229,20 @@ Introspection helpers
3190
3229
3191
3230
Check if a type is a :class: `TypedDict `.
3192
3231
3193
- For example::
3232
+ For example:
3233
+
3234
+ .. testcode ::
3194
3235
3195
3236
class Film(TypedDict):
3196
3237
title: str
3197
3238
year: int
3198
3239
3199
- is_typeddict(Film) # => True
3200
- is_typeddict(list | str) # => False
3240
+ assert is_typeddict(Film)
3241
+ assert not is_typeddict(list | str)
3242
+
3243
+ # TypedDict is a factory for creating typed dicts,
3244
+ # not a typed dict itself
3245
+ assert not is_typeddict(TypedDict)
3201
3246
3202
3247
.. versionadded :: 3.10
3203
3248
0 commit comments