1
1
"""
2
2
The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.
3
3
4
- Any name not present in __all__ is an implementation detail
5
- that may be changed without notice. Use at your own risk!
6
-
7
4
Among other things, the module includes the following:
8
5
* Generic, Protocol, and internal machinery to support generic aliases.
9
6
All subscripted types like X[int], Union[int, str] are generic aliases.
17
14
* Special types: NewType, NamedTuple, TypedDict.
18
15
* Deprecated wrapper submodules for re and io related types.
19
16
* Deprecated aliases for builtin types and collections.abc ABCs.
17
+
18
+ Any name not present in __all__ is an implementation detail
19
+ that may be changed without notice. Use at your own risk!
20
20
"""
21
21
22
22
from abc import abstractmethod , ABCMeta
@@ -214,10 +214,12 @@ def _should_unflatten_callable_args(typ, args):
214
214
"""Internal helper for munging collections.abc.Callable's __args__.
215
215
216
216
The canonical representation for a Callable's __args__ flattens the
217
- argument types, see https://bugs. python.org/issue42195. For example::
217
+ argument types, see https://github.com/ python/cpython/issues/86361.
218
218
219
- collections.abc.Callable[[int, int], str].__args__ == (int, int, str)
220
- collections.abc.Callable[ParamSpec, str].__args__ == (ParamSpec, str)
219
+ For example::
220
+
221
+ assert collections.abc.Callable[[int, int], str].__args__ == (int, int, str)
222
+ assert collections.abc.Callable[ParamSpec, str].__args__ == (ParamSpec, str)
221
223
222
224
As a result, if we need to reconstruct the Callable from its __args__,
223
225
we need to unflatten it.
@@ -351,8 +353,9 @@ def _flatten_literal_params(parameters):
351
353
352
354
353
355
def _tp_cache (func = None , / , * , typed = False ):
354
- """Internal wrapper caching __getitem__ of generic types with a fallback to
355
- original function for non-hashable arguments.
356
+ """Internal wrapper caching __getitem__ of generic types.
357
+
358
+ For non-hashable arguments, the original function is used as a fallback.
356
359
"""
357
360
def decorator (func ):
358
361
# The callback 'inner' references the newly created lru_cache
@@ -633,10 +636,12 @@ def ClassVar(self, parameters):
633
636
634
637
An annotation wrapped in ClassVar indicates that a given
635
638
attribute is intended to be used as a class variable and
636
- should not be set on instances of that class. Usage::
639
+ should not be set on instances of that class.
640
+
641
+ Usage::
637
642
638
643
class Starship:
639
- stats: ClassVar[Dict [str, int]] = {} # class variable
644
+ stats: ClassVar[dict [str, int]] = {} # class variable
640
645
damage: int = 10 # instance variable
641
646
642
647
ClassVar accepts only types and cannot be further subscribed.
@@ -769,7 +774,9 @@ def TypeAlias(self, parameters):
769
774
770
775
Use TypeAlias to indicate that an assignment should
771
776
be recognized as a proper type alias definition by type
772
- checkers. For example::
777
+ checkers.
778
+
779
+ For example::
773
780
774
781
Predicate: TypeAlias = Callable[..., bool]
775
782
@@ -782,8 +789,8 @@ def TypeAlias(self, parameters):
782
789
def Concatenate (self , parameters ):
783
790
"""Special form for annotating higher-order functions.
784
791
785
- ``Concatenate`` can be sed in conjunction with ``ParamSpec`` and
786
- ``Callable`` to represent a higher order function which adds, removes or
792
+ ``Concatenate`` can be used in conjunction with ``ParamSpec`` and
793
+ ``Callable`` to represent a higher- order function which adds, removes or
787
794
transforms the parameters of a callable.
788
795
789
796
For example::
@@ -1599,8 +1606,9 @@ def Unpack(self, parameters):
1599
1606
"""Type unpack operator.
1600
1607
1601
1608
The type unpack operator takes the child types from some container type,
1602
- such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
1603
- example::
1609
+ such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.
1610
+
1611
+ For example::
1604
1612
1605
1613
# For some generic class `Foo`:
1606
1614
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
@@ -1625,7 +1633,7 @@ class Bar(Generic[*Ts]): ...
1625
1633
class Bar[*Ts]: ...
1626
1634
1627
1635
The operator can also be used along with a `TypedDict` to annotate
1628
- `**kwargs` in a function signature. For instance ::
1636
+ `**kwargs` in a function signature::
1629
1637
1630
1638
class Movie(TypedDict):
1631
1639
name: str
@@ -1638,7 +1646,7 @@ def foo(**kwargs: Unpack[Movie]): ...
1638
1646
Note that there is only some runtime checking of this operator. Not
1639
1647
everything the runtime allows may be accepted by static type checkers.
1640
1648
1641
- For more information, see PEP 646.
1649
+ For more information, see PEPs 646 and 692 .
1642
1650
"""
1643
1651
item = _type_check (parameters , f'{ self } accepts only single type.' )
1644
1652
return _UnpackGenericAlias (origin = self , args = (item ,))
@@ -1886,7 +1894,9 @@ def meth(self) -> int:
1886
1894
...
1887
1895
1888
1896
Such classes are primarily used with static type checkers that recognize
1889
- structural subtyping (static duck-typing), for example::
1897
+ structural subtyping (static duck-typing).
1898
+
1899
+ For example::
1890
1900
1891
1901
class C:
1892
1902
def meth(self) -> int:
@@ -2043,7 +2053,7 @@ class Annotated:
2043
2053
2044
2054
Annotated[*Ts, Ann1] # NOT valid
2045
2055
2046
- This would be equivalent to
2056
+ This would be equivalent to::
2047
2057
2048
2058
Annotated[T1, T2, T3, ..., Ann1]
2049
2059
@@ -2261,8 +2271,10 @@ def _strip_annotations(t):
2261
2271
def get_origin (tp ):
2262
2272
"""Get the unsubscripted version of a type.
2263
2273
2264
- This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
2265
- Annotated, and others. Return None for unsupported types. Examples::
2274
+ This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,
2275
+ Annotated, and others. Return None for unsupported types.
2276
+
2277
+ Examples::
2266
2278
2267
2279
assert get_origin(Literal[42]) is Literal
2268
2280
assert get_origin(int) is None
@@ -2421,7 +2433,9 @@ def overload(func):
2421
2433
"""Decorator for overloaded functions/methods.
2422
2434
2423
2435
In a stub file, place two or more stub definitions for the same
2424
- function in a row, each decorated with @overload. For example::
2436
+ function in a row, each decorated with @overload.
2437
+
2438
+ For example::
2425
2439
2426
2440
@overload
2427
2441
def utf8(value: None) -> None: ...
@@ -2432,7 +2446,7 @@ def utf8(value: str) -> bytes: ...
2432
2446
2433
2447
In a non-stub file (i.e. a regular .py file), do the same but
2434
2448
follow it with an implementation. The implementation should *not*
2435
- be decorated with @overload. For example ::
2449
+ be decorated with @overload::
2436
2450
2437
2451
@overload
2438
2452
def utf8(value: None) -> None: ...
@@ -2942,7 +2956,9 @@ class Point2D(TypedDict):
2942
2956
def Required (self , parameters ):
2943
2957
"""Special typing construct to mark a TypedDict key as required.
2944
2958
2945
- This is mainly useful for total=False TypedDicts. For example::
2959
+ This is mainly useful for total=False TypedDicts.
2960
+
2961
+ For example::
2946
2962
2947
2963
class Movie(TypedDict, total=False):
2948
2964
title: Required[str]
@@ -2984,7 +3000,9 @@ class NewType:
2984
3000
2985
3001
NewType(name, tp) is considered a subtype of tp
2986
3002
by static type checkers. At runtime, NewType(name, tp) returns
2987
- a dummy callable that simply returns its argument. Usage::
3003
+ a dummy callable that simply returns its argument.
3004
+
3005
+ Usage::
2988
3006
2989
3007
UserId = NewType('UserId', int)
2990
3008
0 commit comments