metaflow 2.15.4__py2.py3-none-any.whl → 2.15.6__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- metaflow/_vendor/typeguard/_checkers.py +259 -95
- metaflow/_vendor/typeguard/_config.py +4 -4
- metaflow/_vendor/typeguard/_decorators.py +8 -12
- metaflow/_vendor/typeguard/_functions.py +33 -32
- metaflow/_vendor/typeguard/_pytest_plugin.py +40 -13
- metaflow/_vendor/typeguard/_suppression.py +3 -5
- metaflow/_vendor/typeguard/_transformer.py +84 -48
- metaflow/_vendor/typeguard/_union_transformer.py +1 -0
- metaflow/_vendor/typeguard/_utils.py +13 -9
- metaflow/_vendor/typing_extensions.py +1088 -500
- metaflow/_vendor/v3_7/__init__.py +1 -0
- metaflow/_vendor/v3_7/importlib_metadata/__init__.py +1063 -0
- metaflow/_vendor/v3_7/importlib_metadata/_adapters.py +68 -0
- metaflow/_vendor/v3_7/importlib_metadata/_collections.py +30 -0
- metaflow/_vendor/v3_7/importlib_metadata/_compat.py +71 -0
- metaflow/_vendor/v3_7/importlib_metadata/_functools.py +104 -0
- metaflow/_vendor/v3_7/importlib_metadata/_itertools.py +73 -0
- metaflow/_vendor/v3_7/importlib_metadata/_meta.py +48 -0
- metaflow/_vendor/v3_7/importlib_metadata/_text.py +99 -0
- metaflow/_vendor/v3_7/importlib_metadata/py.typed +0 -0
- metaflow/_vendor/v3_7/typeguard/__init__.py +48 -0
- metaflow/_vendor/v3_7/typeguard/_checkers.py +906 -0
- metaflow/_vendor/v3_7/typeguard/_config.py +108 -0
- metaflow/_vendor/v3_7/typeguard/_decorators.py +237 -0
- metaflow/_vendor/v3_7/typeguard/_exceptions.py +42 -0
- metaflow/_vendor/v3_7/typeguard/_functions.py +310 -0
- metaflow/_vendor/v3_7/typeguard/_importhook.py +213 -0
- metaflow/_vendor/v3_7/typeguard/_memo.py +48 -0
- metaflow/_vendor/v3_7/typeguard/_pytest_plugin.py +100 -0
- metaflow/_vendor/v3_7/typeguard/_suppression.py +88 -0
- metaflow/_vendor/v3_7/typeguard/_transformer.py +1207 -0
- metaflow/_vendor/v3_7/typeguard/_union_transformer.py +54 -0
- metaflow/_vendor/v3_7/typeguard/_utils.py +169 -0
- metaflow/_vendor/v3_7/typeguard/py.typed +0 -0
- metaflow/_vendor/v3_7/typing_extensions.py +3072 -0
- metaflow/_vendor/v3_7/zipp.py +329 -0
- metaflow/cmd/develop/stubs.py +1 -1
- metaflow/extension_support/__init__.py +1 -1
- metaflow/plugins/argo/argo_client.py +9 -2
- metaflow/plugins/argo/argo_workflows.py +79 -28
- metaflow/plugins/argo/argo_workflows_cli.py +16 -25
- metaflow/plugins/argo/argo_workflows_deployer_objects.py +5 -2
- metaflow/plugins/cards/card_modules/main.js +52 -50
- metaflow/plugins/metadata_providers/service.py +16 -7
- metaflow/plugins/pypi/utils.py +4 -0
- metaflow/runner/click_api.py +7 -2
- metaflow/runner/deployer.py +3 -2
- metaflow/vendor.py +1 -0
- metaflow/version.py +1 -1
- {metaflow-2.15.4.data → metaflow-2.15.6.data}/data/share/metaflow/devtools/Tiltfile +4 -4
- metaflow-2.15.6.dist-info/METADATA +103 -0
- {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/RECORD +58 -32
- {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/WHEEL +1 -1
- metaflow-2.15.4.dist-info/METADATA +0 -110
- {metaflow-2.15.4.data → metaflow-2.15.6.data}/data/share/metaflow/devtools/Makefile +0 -0
- {metaflow-2.15.4.data → metaflow-2.15.6.data}/data/share/metaflow/devtools/pick_services.sh +0 -0
- {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/LICENSE +0 -0
- {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/entry_points.txt +0 -0
- {metaflow-2.15.4.dist-info → metaflow-2.15.6.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,3072 @@
|
|
1
|
+
import abc
|
2
|
+
import collections
|
3
|
+
import collections.abc
|
4
|
+
import functools
|
5
|
+
import inspect
|
6
|
+
import operator
|
7
|
+
import sys
|
8
|
+
import types as _types
|
9
|
+
import typing
|
10
|
+
import warnings
|
11
|
+
|
12
|
+
__all__ = [
|
13
|
+
# Super-special typing primitives.
|
14
|
+
'Any',
|
15
|
+
'ClassVar',
|
16
|
+
'Concatenate',
|
17
|
+
'Final',
|
18
|
+
'LiteralString',
|
19
|
+
'ParamSpec',
|
20
|
+
'ParamSpecArgs',
|
21
|
+
'ParamSpecKwargs',
|
22
|
+
'Self',
|
23
|
+
'Type',
|
24
|
+
'TypeVar',
|
25
|
+
'TypeVarTuple',
|
26
|
+
'Unpack',
|
27
|
+
|
28
|
+
# ABCs (from collections.abc).
|
29
|
+
'Awaitable',
|
30
|
+
'AsyncIterator',
|
31
|
+
'AsyncIterable',
|
32
|
+
'Coroutine',
|
33
|
+
'AsyncGenerator',
|
34
|
+
'AsyncContextManager',
|
35
|
+
'Buffer',
|
36
|
+
'ChainMap',
|
37
|
+
|
38
|
+
# Concrete collection types.
|
39
|
+
'ContextManager',
|
40
|
+
'Counter',
|
41
|
+
'Deque',
|
42
|
+
'DefaultDict',
|
43
|
+
'NamedTuple',
|
44
|
+
'OrderedDict',
|
45
|
+
'TypedDict',
|
46
|
+
|
47
|
+
# Structural checks, a.k.a. protocols.
|
48
|
+
'SupportsAbs',
|
49
|
+
'SupportsBytes',
|
50
|
+
'SupportsComplex',
|
51
|
+
'SupportsFloat',
|
52
|
+
'SupportsIndex',
|
53
|
+
'SupportsInt',
|
54
|
+
'SupportsRound',
|
55
|
+
|
56
|
+
# One-off things.
|
57
|
+
'Annotated',
|
58
|
+
'assert_never',
|
59
|
+
'assert_type',
|
60
|
+
'clear_overloads',
|
61
|
+
'dataclass_transform',
|
62
|
+
'deprecated',
|
63
|
+
'get_overloads',
|
64
|
+
'final',
|
65
|
+
'get_args',
|
66
|
+
'get_origin',
|
67
|
+
'get_original_bases',
|
68
|
+
'get_protocol_members',
|
69
|
+
'get_type_hints',
|
70
|
+
'IntVar',
|
71
|
+
'is_protocol',
|
72
|
+
'is_typeddict',
|
73
|
+
'Literal',
|
74
|
+
'NewType',
|
75
|
+
'overload',
|
76
|
+
'override',
|
77
|
+
'Protocol',
|
78
|
+
'reveal_type',
|
79
|
+
'runtime',
|
80
|
+
'runtime_checkable',
|
81
|
+
'Text',
|
82
|
+
'TypeAlias',
|
83
|
+
'TypeAliasType',
|
84
|
+
'TypeGuard',
|
85
|
+
'TYPE_CHECKING',
|
86
|
+
'Never',
|
87
|
+
'NoReturn',
|
88
|
+
'Required',
|
89
|
+
'NotRequired',
|
90
|
+
|
91
|
+
# Pure aliases, have always been in typing
|
92
|
+
'AbstractSet',
|
93
|
+
'AnyStr',
|
94
|
+
'BinaryIO',
|
95
|
+
'Callable',
|
96
|
+
'Collection',
|
97
|
+
'Container',
|
98
|
+
'Dict',
|
99
|
+
'ForwardRef',
|
100
|
+
'FrozenSet',
|
101
|
+
'Generator',
|
102
|
+
'Generic',
|
103
|
+
'Hashable',
|
104
|
+
'IO',
|
105
|
+
'ItemsView',
|
106
|
+
'Iterable',
|
107
|
+
'Iterator',
|
108
|
+
'KeysView',
|
109
|
+
'List',
|
110
|
+
'Mapping',
|
111
|
+
'MappingView',
|
112
|
+
'Match',
|
113
|
+
'MutableMapping',
|
114
|
+
'MutableSequence',
|
115
|
+
'MutableSet',
|
116
|
+
'Optional',
|
117
|
+
'Pattern',
|
118
|
+
'Reversible',
|
119
|
+
'Sequence',
|
120
|
+
'Set',
|
121
|
+
'Sized',
|
122
|
+
'TextIO',
|
123
|
+
'Tuple',
|
124
|
+
'Union',
|
125
|
+
'ValuesView',
|
126
|
+
'cast',
|
127
|
+
'no_type_check',
|
128
|
+
'no_type_check_decorator',
|
129
|
+
]
|
130
|
+
|
131
|
+
# for backward compatibility
|
132
|
+
PEP_560 = True
|
133
|
+
GenericMeta = type
|
134
|
+
|
135
|
+
# The functions below are modified copies of typing internal helpers.
|
136
|
+
# They are needed by _ProtocolMeta and they provide support for PEP 646.
|
137
|
+
|
138
|
+
|
139
|
+
class _Sentinel:
|
140
|
+
def __repr__(self):
|
141
|
+
return "<sentinel>"
|
142
|
+
|
143
|
+
|
144
|
+
_marker = _Sentinel()
|
145
|
+
|
146
|
+
|
147
|
+
def _check_generic(cls, parameters, elen=_marker):
|
148
|
+
"""Check correct count for parameters of a generic cls (internal helper).
|
149
|
+
This gives a nice error message in case of count mismatch.
|
150
|
+
"""
|
151
|
+
if not elen:
|
152
|
+
raise TypeError(f"{cls} is not a generic class")
|
153
|
+
if elen is _marker:
|
154
|
+
if not hasattr(cls, "__parameters__") or not cls.__parameters__:
|
155
|
+
raise TypeError(f"{cls} is not a generic class")
|
156
|
+
elen = len(cls.__parameters__)
|
157
|
+
alen = len(parameters)
|
158
|
+
if alen != elen:
|
159
|
+
if hasattr(cls, "__parameters__"):
|
160
|
+
parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
|
161
|
+
num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
|
162
|
+
if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
|
163
|
+
return
|
164
|
+
raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
|
165
|
+
f" actual {alen}, expected {elen}")
|
166
|
+
|
167
|
+
|
168
|
+
if sys.version_info >= (3, 10):
|
169
|
+
def _should_collect_from_parameters(t):
|
170
|
+
return isinstance(
|
171
|
+
t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
|
172
|
+
)
|
173
|
+
elif sys.version_info >= (3, 9):
|
174
|
+
def _should_collect_from_parameters(t):
|
175
|
+
return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
|
176
|
+
else:
|
177
|
+
def _should_collect_from_parameters(t):
|
178
|
+
return isinstance(t, typing._GenericAlias) and not t._special
|
179
|
+
|
180
|
+
|
181
|
+
def _collect_type_vars(types, typevar_types=None):
|
182
|
+
"""Collect all type variable contained in types in order of
|
183
|
+
first appearance (lexicographic order). For example::
|
184
|
+
|
185
|
+
_collect_type_vars((T, List[S, T])) == (T, S)
|
186
|
+
"""
|
187
|
+
if typevar_types is None:
|
188
|
+
typevar_types = typing.TypeVar
|
189
|
+
tvars = []
|
190
|
+
for t in types:
|
191
|
+
if (
|
192
|
+
isinstance(t, typevar_types) and
|
193
|
+
t not in tvars and
|
194
|
+
not _is_unpack(t)
|
195
|
+
):
|
196
|
+
tvars.append(t)
|
197
|
+
if _should_collect_from_parameters(t):
|
198
|
+
tvars.extend([t for t in t.__parameters__ if t not in tvars])
|
199
|
+
return tuple(tvars)
|
200
|
+
|
201
|
+
|
202
|
+
NoReturn = typing.NoReturn
|
203
|
+
|
204
|
+
# Some unconstrained type variables. These are used by the container types.
|
205
|
+
# (These are not for export.)
|
206
|
+
T = typing.TypeVar('T') # Any type.
|
207
|
+
KT = typing.TypeVar('KT') # Key type.
|
208
|
+
VT = typing.TypeVar('VT') # Value type.
|
209
|
+
T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
|
210
|
+
T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
|
211
|
+
|
212
|
+
|
213
|
+
if sys.version_info >= (3, 11):
|
214
|
+
from typing import Any
|
215
|
+
else:
|
216
|
+
|
217
|
+
class _AnyMeta(type):
|
218
|
+
def __instancecheck__(self, obj):
|
219
|
+
if self is Any:
|
220
|
+
raise TypeError("typing_extensions.Any cannot be used with isinstance()")
|
221
|
+
return super().__instancecheck__(obj)
|
222
|
+
|
223
|
+
def __repr__(self):
|
224
|
+
if self is Any:
|
225
|
+
return "typing_extensions.Any"
|
226
|
+
return super().__repr__()
|
227
|
+
|
228
|
+
class Any(metaclass=_AnyMeta):
|
229
|
+
"""Special type indicating an unconstrained type.
|
230
|
+
- Any is compatible with every type.
|
231
|
+
- Any assumed to have all methods.
|
232
|
+
- All values assumed to be instances of Any.
|
233
|
+
Note that all the above statements are true from the point of view of
|
234
|
+
static type checkers. At runtime, Any should not be used with instance
|
235
|
+
checks.
|
236
|
+
"""
|
237
|
+
def __new__(cls, *args, **kwargs):
|
238
|
+
if cls is Any:
|
239
|
+
raise TypeError("Any cannot be instantiated")
|
240
|
+
return super().__new__(cls, *args, **kwargs)
|
241
|
+
|
242
|
+
|
243
|
+
ClassVar = typing.ClassVar
|
244
|
+
|
245
|
+
|
246
|
+
class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
|
247
|
+
def __repr__(self):
|
248
|
+
return 'typing_extensions.' + self._name
|
249
|
+
|
250
|
+
|
251
|
+
# On older versions of typing there is an internal class named "Final".
|
252
|
+
# 3.8+
|
253
|
+
if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
|
254
|
+
Final = typing.Final
|
255
|
+
# 3.7
|
256
|
+
else:
|
257
|
+
class _FinalForm(_ExtensionsSpecialForm, _root=True):
|
258
|
+
def __getitem__(self, parameters):
|
259
|
+
item = typing._type_check(parameters,
|
260
|
+
f'{self._name} accepts only a single type.')
|
261
|
+
return typing._GenericAlias(self, (item,))
|
262
|
+
|
263
|
+
Final = _FinalForm('Final',
|
264
|
+
doc="""A special typing construct to indicate that a name
|
265
|
+
cannot be re-assigned or overridden in a subclass.
|
266
|
+
For example:
|
267
|
+
|
268
|
+
MAX_SIZE: Final = 9000
|
269
|
+
MAX_SIZE += 1 # Error reported by type checker
|
270
|
+
|
271
|
+
class Connection:
|
272
|
+
TIMEOUT: Final[int] = 10
|
273
|
+
class FastConnector(Connection):
|
274
|
+
TIMEOUT = 1 # Error reported by type checker
|
275
|
+
|
276
|
+
There is no runtime checking of these properties.""")
|
277
|
+
|
278
|
+
if sys.version_info >= (3, 11):
|
279
|
+
final = typing.final
|
280
|
+
else:
|
281
|
+
# @final exists in 3.8+, but we backport it for all versions
|
282
|
+
# before 3.11 to keep support for the __final__ attribute.
|
283
|
+
# See https://bugs.python.org/issue46342
|
284
|
+
def final(f):
|
285
|
+
"""This decorator can be used to indicate to type checkers that
|
286
|
+
the decorated method cannot be overridden, and decorated class
|
287
|
+
cannot be subclassed. For example:
|
288
|
+
|
289
|
+
class Base:
|
290
|
+
@final
|
291
|
+
def done(self) -> None:
|
292
|
+
...
|
293
|
+
class Sub(Base):
|
294
|
+
def done(self) -> None: # Error reported by type checker
|
295
|
+
...
|
296
|
+
@final
|
297
|
+
class Leaf:
|
298
|
+
...
|
299
|
+
class Other(Leaf): # Error reported by type checker
|
300
|
+
...
|
301
|
+
|
302
|
+
There is no runtime checking of these properties. The decorator
|
303
|
+
sets the ``__final__`` attribute to ``True`` on the decorated object
|
304
|
+
to allow runtime introspection.
|
305
|
+
"""
|
306
|
+
try:
|
307
|
+
f.__final__ = True
|
308
|
+
except (AttributeError, TypeError):
|
309
|
+
# Skip the attribute silently if it is not writable.
|
310
|
+
# AttributeError happens if the object has __slots__ or a
|
311
|
+
# read-only property, TypeError if it's a builtin class.
|
312
|
+
pass
|
313
|
+
return f
|
314
|
+
|
315
|
+
|
316
|
+
def IntVar(name):
|
317
|
+
return typing.TypeVar(name)
|
318
|
+
|
319
|
+
|
320
|
+
# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
|
321
|
+
if sys.version_info >= (3, 10, 1):
|
322
|
+
Literal = typing.Literal
|
323
|
+
else:
|
324
|
+
def _flatten_literal_params(parameters):
|
325
|
+
"""An internal helper for Literal creation: flatten Literals among parameters"""
|
326
|
+
params = []
|
327
|
+
for p in parameters:
|
328
|
+
if isinstance(p, _LiteralGenericAlias):
|
329
|
+
params.extend(p.__args__)
|
330
|
+
else:
|
331
|
+
params.append(p)
|
332
|
+
return tuple(params)
|
333
|
+
|
334
|
+
def _value_and_type_iter(params):
|
335
|
+
for p in params:
|
336
|
+
yield p, type(p)
|
337
|
+
|
338
|
+
class _LiteralGenericAlias(typing._GenericAlias, _root=True):
|
339
|
+
def __eq__(self, other):
|
340
|
+
if not isinstance(other, _LiteralGenericAlias):
|
341
|
+
return NotImplemented
|
342
|
+
these_args_deduped = set(_value_and_type_iter(self.__args__))
|
343
|
+
other_args_deduped = set(_value_and_type_iter(other.__args__))
|
344
|
+
return these_args_deduped == other_args_deduped
|
345
|
+
|
346
|
+
def __hash__(self):
|
347
|
+
return hash(frozenset(_value_and_type_iter(self.__args__)))
|
348
|
+
|
349
|
+
class _LiteralForm(_ExtensionsSpecialForm, _root=True):
|
350
|
+
def __init__(self, doc: str):
|
351
|
+
self._name = 'Literal'
|
352
|
+
self._doc = self.__doc__ = doc
|
353
|
+
|
354
|
+
def __getitem__(self, parameters):
|
355
|
+
if not isinstance(parameters, tuple):
|
356
|
+
parameters = (parameters,)
|
357
|
+
|
358
|
+
parameters = _flatten_literal_params(parameters)
|
359
|
+
|
360
|
+
val_type_pairs = list(_value_and_type_iter(parameters))
|
361
|
+
try:
|
362
|
+
deduped_pairs = set(val_type_pairs)
|
363
|
+
except TypeError:
|
364
|
+
# unhashable parameters
|
365
|
+
pass
|
366
|
+
else:
|
367
|
+
# similar logic to typing._deduplicate on Python 3.9+
|
368
|
+
if len(deduped_pairs) < len(val_type_pairs):
|
369
|
+
new_parameters = []
|
370
|
+
for pair in val_type_pairs:
|
371
|
+
if pair in deduped_pairs:
|
372
|
+
new_parameters.append(pair[0])
|
373
|
+
deduped_pairs.remove(pair)
|
374
|
+
assert not deduped_pairs, deduped_pairs
|
375
|
+
parameters = tuple(new_parameters)
|
376
|
+
|
377
|
+
return _LiteralGenericAlias(self, parameters)
|
378
|
+
|
379
|
+
Literal = _LiteralForm(doc="""\
|
380
|
+
A type that can be used to indicate to type checkers
|
381
|
+
that the corresponding value has a value literally equivalent
|
382
|
+
to the provided parameter. For example:
|
383
|
+
|
384
|
+
var: Literal[4] = 4
|
385
|
+
|
386
|
+
The type checker understands that 'var' is literally equal to
|
387
|
+
the value 4 and no other value.
|
388
|
+
|
389
|
+
Literal[...] cannot be subclassed. There is no runtime
|
390
|
+
checking verifying that the parameter is actually a value
|
391
|
+
instead of a type.""")
|
392
|
+
|
393
|
+
|
394
|
+
_overload_dummy = typing._overload_dummy
|
395
|
+
|
396
|
+
|
397
|
+
if hasattr(typing, "get_overloads"): # 3.11+
|
398
|
+
overload = typing.overload
|
399
|
+
get_overloads = typing.get_overloads
|
400
|
+
clear_overloads = typing.clear_overloads
|
401
|
+
else:
|
402
|
+
# {module: {qualname: {firstlineno: func}}}
|
403
|
+
_overload_registry = collections.defaultdict(
|
404
|
+
functools.partial(collections.defaultdict, dict)
|
405
|
+
)
|
406
|
+
|
407
|
+
def overload(func):
|
408
|
+
"""Decorator for overloaded functions/methods.
|
409
|
+
|
410
|
+
In a stub file, place two or more stub definitions for the same
|
411
|
+
function in a row, each decorated with @overload. For example:
|
412
|
+
|
413
|
+
@overload
|
414
|
+
def utf8(value: None) -> None: ...
|
415
|
+
@overload
|
416
|
+
def utf8(value: bytes) -> bytes: ...
|
417
|
+
@overload
|
418
|
+
def utf8(value: str) -> bytes: ...
|
419
|
+
|
420
|
+
In a non-stub file (i.e. a regular .py file), do the same but
|
421
|
+
follow it with an implementation. The implementation should *not*
|
422
|
+
be decorated with @overload. For example:
|
423
|
+
|
424
|
+
@overload
|
425
|
+
def utf8(value: None) -> None: ...
|
426
|
+
@overload
|
427
|
+
def utf8(value: bytes) -> bytes: ...
|
428
|
+
@overload
|
429
|
+
def utf8(value: str) -> bytes: ...
|
430
|
+
def utf8(value):
|
431
|
+
# implementation goes here
|
432
|
+
|
433
|
+
The overloads for a function can be retrieved at runtime using the
|
434
|
+
get_overloads() function.
|
435
|
+
"""
|
436
|
+
# classmethod and staticmethod
|
437
|
+
f = getattr(func, "__func__", func)
|
438
|
+
try:
|
439
|
+
_overload_registry[f.__module__][f.__qualname__][
|
440
|
+
f.__code__.co_firstlineno
|
441
|
+
] = func
|
442
|
+
except AttributeError:
|
443
|
+
# Not a normal function; ignore.
|
444
|
+
pass
|
445
|
+
return _overload_dummy
|
446
|
+
|
447
|
+
def get_overloads(func):
|
448
|
+
"""Return all defined overloads for *func* as a sequence."""
|
449
|
+
# classmethod and staticmethod
|
450
|
+
f = getattr(func, "__func__", func)
|
451
|
+
if f.__module__ not in _overload_registry:
|
452
|
+
return []
|
453
|
+
mod_dict = _overload_registry[f.__module__]
|
454
|
+
if f.__qualname__ not in mod_dict:
|
455
|
+
return []
|
456
|
+
return list(mod_dict[f.__qualname__].values())
|
457
|
+
|
458
|
+
def clear_overloads():
|
459
|
+
"""Clear all overloads in the registry."""
|
460
|
+
_overload_registry.clear()
|
461
|
+
|
462
|
+
|
463
|
+
# This is not a real generic class. Don't use outside annotations.
|
464
|
+
Type = typing.Type
|
465
|
+
|
466
|
+
# Various ABCs mimicking those in collections.abc.
|
467
|
+
# A few are simply re-exported for completeness.
|
468
|
+
|
469
|
+
|
470
|
+
Awaitable = typing.Awaitable
|
471
|
+
Coroutine = typing.Coroutine
|
472
|
+
AsyncIterable = typing.AsyncIterable
|
473
|
+
AsyncIterator = typing.AsyncIterator
|
474
|
+
Deque = typing.Deque
|
475
|
+
ContextManager = typing.ContextManager
|
476
|
+
AsyncContextManager = typing.AsyncContextManager
|
477
|
+
DefaultDict = typing.DefaultDict
|
478
|
+
|
479
|
+
# 3.7.2+
|
480
|
+
if hasattr(typing, 'OrderedDict'):
|
481
|
+
OrderedDict = typing.OrderedDict
|
482
|
+
# 3.7.0-3.7.2
|
483
|
+
else:
|
484
|
+
OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
|
485
|
+
|
486
|
+
Counter = typing.Counter
|
487
|
+
ChainMap = typing.ChainMap
|
488
|
+
AsyncGenerator = typing.AsyncGenerator
|
489
|
+
Text = typing.Text
|
490
|
+
TYPE_CHECKING = typing.TYPE_CHECKING
|
491
|
+
|
492
|
+
|
493
|
+
_PROTO_ALLOWLIST = {
|
494
|
+
'collections.abc': [
|
495
|
+
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
|
496
|
+
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
|
497
|
+
],
|
498
|
+
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
|
499
|
+
'typing_extensions': ['Buffer'],
|
500
|
+
}
|
501
|
+
|
502
|
+
|
503
|
+
_EXCLUDED_ATTRS = {
|
504
|
+
"__abstractmethods__", "__annotations__", "__weakref__", "_is_protocol",
|
505
|
+
"_is_runtime_protocol", "__dict__", "__slots__", "__parameters__",
|
506
|
+
"__orig_bases__", "__module__", "_MutableMapping__marker", "__doc__",
|
507
|
+
"__subclasshook__", "__orig_class__", "__init__", "__new__",
|
508
|
+
"__protocol_attrs__", "__callable_proto_members_only__",
|
509
|
+
}
|
510
|
+
|
511
|
+
if sys.version_info < (3, 8):
|
512
|
+
_EXCLUDED_ATTRS |= {
|
513
|
+
"_gorg", "__next_in_mro__", "__extra__", "__tree_hash__", "__args__",
|
514
|
+
"__origin__"
|
515
|
+
}
|
516
|
+
|
517
|
+
if sys.version_info >= (3, 9):
|
518
|
+
_EXCLUDED_ATTRS.add("__class_getitem__")
|
519
|
+
|
520
|
+
if sys.version_info >= (3, 12):
|
521
|
+
_EXCLUDED_ATTRS.add("__type_params__")
|
522
|
+
|
523
|
+
_EXCLUDED_ATTRS = frozenset(_EXCLUDED_ATTRS)
|
524
|
+
|
525
|
+
|
526
|
+
def _get_protocol_attrs(cls):
|
527
|
+
attrs = set()
|
528
|
+
for base in cls.__mro__[:-1]: # without object
|
529
|
+
if base.__name__ in {'Protocol', 'Generic'}:
|
530
|
+
continue
|
531
|
+
annotations = getattr(base, '__annotations__', {})
|
532
|
+
for attr in (*base.__dict__, *annotations):
|
533
|
+
if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
|
534
|
+
attrs.add(attr)
|
535
|
+
return attrs
|
536
|
+
|
537
|
+
|
538
|
+
def _maybe_adjust_parameters(cls):
|
539
|
+
"""Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.
|
540
|
+
|
541
|
+
The contents of this function are very similar
|
542
|
+
to logic found in typing.Generic.__init_subclass__
|
543
|
+
on the CPython main branch.
|
544
|
+
"""
|
545
|
+
tvars = []
|
546
|
+
if '__orig_bases__' in cls.__dict__:
|
547
|
+
tvars = _collect_type_vars(cls.__orig_bases__)
|
548
|
+
# Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
|
549
|
+
# If found, tvars must be a subset of it.
|
550
|
+
# If not found, tvars is it.
|
551
|
+
# Also check for and reject plain Generic,
|
552
|
+
# and reject multiple Generic[...] and/or Protocol[...].
|
553
|
+
gvars = None
|
554
|
+
for base in cls.__orig_bases__:
|
555
|
+
if (isinstance(base, typing._GenericAlias) and
|
556
|
+
base.__origin__ in (typing.Generic, Protocol)):
|
557
|
+
# for error messages
|
558
|
+
the_base = base.__origin__.__name__
|
559
|
+
if gvars is not None:
|
560
|
+
raise TypeError(
|
561
|
+
"Cannot inherit from Generic[...]"
|
562
|
+
" and/or Protocol[...] multiple types.")
|
563
|
+
gvars = base.__parameters__
|
564
|
+
if gvars is None:
|
565
|
+
gvars = tvars
|
566
|
+
else:
|
567
|
+
tvarset = set(tvars)
|
568
|
+
gvarset = set(gvars)
|
569
|
+
if not tvarset <= gvarset:
|
570
|
+
s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
|
571
|
+
s_args = ', '.join(str(g) for g in gvars)
|
572
|
+
raise TypeError(f"Some type variables ({s_vars}) are"
|
573
|
+
f" not listed in {the_base}[{s_args}]")
|
574
|
+
tvars = gvars
|
575
|
+
cls.__parameters__ = tuple(tvars)
|
576
|
+
|
577
|
+
|
578
|
+
def _caller(depth=2):
|
579
|
+
try:
|
580
|
+
return sys._getframe(depth).f_globals.get('__name__', '__main__')
|
581
|
+
except (AttributeError, ValueError): # For platforms without _getframe()
|
582
|
+
return None
|
583
|
+
|
584
|
+
|
585
|
+
# The performance of runtime-checkable protocols is significantly improved on Python 3.12,
|
586
|
+
# so we backport the 3.12 version of Protocol to Python <=3.11
|
587
|
+
if sys.version_info >= (3, 12):
|
588
|
+
Protocol = typing.Protocol
|
589
|
+
else:
|
590
|
+
def _allow_reckless_class_checks(depth=3):
|
591
|
+
"""Allow instance and class checks for special stdlib modules.
|
592
|
+
The abc and functools modules indiscriminately call isinstance() and
|
593
|
+
issubclass() on the whole MRO of a user class, which may contain protocols.
|
594
|
+
"""
|
595
|
+
return _caller(depth) in {'abc', 'functools', None}
|
596
|
+
|
597
|
+
def _no_init(self, *args, **kwargs):
|
598
|
+
if type(self)._is_protocol:
|
599
|
+
raise TypeError('Protocols cannot be instantiated')
|
600
|
+
|
601
|
+
if sys.version_info >= (3, 8):
|
602
|
+
# Inheriting from typing._ProtocolMeta isn't actually desirable,
|
603
|
+
# but is necessary to allow typing.Protocol and typing_extensions.Protocol
|
604
|
+
# to mix without getting TypeErrors about "metaclass conflict"
|
605
|
+
_typing_Protocol = typing.Protocol
|
606
|
+
_ProtocolMetaBase = type(_typing_Protocol)
|
607
|
+
else:
|
608
|
+
_typing_Protocol = _marker
|
609
|
+
_ProtocolMetaBase = abc.ABCMeta
|
610
|
+
|
611
|
+
class _ProtocolMeta(_ProtocolMetaBase):
|
612
|
+
# This metaclass is somewhat unfortunate,
|
613
|
+
# but is necessary for several reasons...
|
614
|
+
#
|
615
|
+
# NOTE: DO NOT call super() in any methods in this class
|
616
|
+
# That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
|
617
|
+
# and those are slow
|
618
|
+
def __new__(mcls, name, bases, namespace, **kwargs):
|
619
|
+
if name == "Protocol" and len(bases) < 2:
|
620
|
+
pass
|
621
|
+
elif {Protocol, _typing_Protocol} & set(bases):
|
622
|
+
for base in bases:
|
623
|
+
if not (
|
624
|
+
base in {object, typing.Generic, Protocol, _typing_Protocol}
|
625
|
+
or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
|
626
|
+
or is_protocol(base)
|
627
|
+
):
|
628
|
+
raise TypeError(
|
629
|
+
f"Protocols can only inherit from other protocols, "
|
630
|
+
f"got {base!r}"
|
631
|
+
)
|
632
|
+
return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
|
633
|
+
|
634
|
+
def __init__(cls, *args, **kwargs):
|
635
|
+
abc.ABCMeta.__init__(cls, *args, **kwargs)
|
636
|
+
if getattr(cls, "_is_protocol", False):
|
637
|
+
cls.__protocol_attrs__ = _get_protocol_attrs(cls)
|
638
|
+
# PEP 544 prohibits using issubclass()
|
639
|
+
# with protocols that have non-method members.
|
640
|
+
cls.__callable_proto_members_only__ = all(
|
641
|
+
callable(getattr(cls, attr, None)) for attr in cls.__protocol_attrs__
|
642
|
+
)
|
643
|
+
|
644
|
+
def __subclasscheck__(cls, other):
|
645
|
+
if cls is Protocol:
|
646
|
+
return type.__subclasscheck__(cls, other)
|
647
|
+
if (
|
648
|
+
getattr(cls, '_is_protocol', False)
|
649
|
+
and not _allow_reckless_class_checks()
|
650
|
+
):
|
651
|
+
if not isinstance(other, type):
|
652
|
+
# Same error message as for issubclass(1, int).
|
653
|
+
raise TypeError('issubclass() arg 1 must be a class')
|
654
|
+
if (
|
655
|
+
not cls.__callable_proto_members_only__
|
656
|
+
and cls.__dict__.get("__subclasshook__") is _proto_hook
|
657
|
+
):
|
658
|
+
raise TypeError(
|
659
|
+
"Protocols with non-method members don't support issubclass()"
|
660
|
+
)
|
661
|
+
if not getattr(cls, '_is_runtime_protocol', False):
|
662
|
+
raise TypeError(
|
663
|
+
"Instance and class checks can only be used with "
|
664
|
+
"@runtime_checkable protocols"
|
665
|
+
)
|
666
|
+
return abc.ABCMeta.__subclasscheck__(cls, other)
|
667
|
+
|
668
|
+
def __instancecheck__(cls, instance):
|
669
|
+
# We need this method for situations where attributes are
|
670
|
+
# assigned in __init__.
|
671
|
+
if cls is Protocol:
|
672
|
+
return type.__instancecheck__(cls, instance)
|
673
|
+
if not getattr(cls, "_is_protocol", False):
|
674
|
+
# i.e., it's a concrete subclass of a protocol
|
675
|
+
return abc.ABCMeta.__instancecheck__(cls, instance)
|
676
|
+
|
677
|
+
if (
|
678
|
+
not getattr(cls, '_is_runtime_protocol', False) and
|
679
|
+
not _allow_reckless_class_checks()
|
680
|
+
):
|
681
|
+
raise TypeError("Instance and class checks can only be used with"
|
682
|
+
" @runtime_checkable protocols")
|
683
|
+
|
684
|
+
if abc.ABCMeta.__instancecheck__(cls, instance):
|
685
|
+
return True
|
686
|
+
|
687
|
+
for attr in cls.__protocol_attrs__:
|
688
|
+
try:
|
689
|
+
val = inspect.getattr_static(instance, attr)
|
690
|
+
except AttributeError:
|
691
|
+
break
|
692
|
+
if val is None and callable(getattr(cls, attr, None)):
|
693
|
+
break
|
694
|
+
else:
|
695
|
+
return True
|
696
|
+
|
697
|
+
return False
|
698
|
+
|
699
|
+
def __eq__(cls, other):
|
700
|
+
# Hack so that typing.Generic.__class_getitem__
|
701
|
+
# treats typing_extensions.Protocol
|
702
|
+
# as equivalent to typing.Protocol on Python 3.8+
|
703
|
+
if abc.ABCMeta.__eq__(cls, other) is True:
|
704
|
+
return True
|
705
|
+
return (
|
706
|
+
cls is Protocol and other is getattr(typing, "Protocol", object())
|
707
|
+
)
|
708
|
+
|
709
|
+
# This has to be defined, or the abc-module cache
|
710
|
+
# complains about classes with this metaclass being unhashable,
|
711
|
+
# if we define only __eq__!
|
712
|
+
def __hash__(cls) -> int:
|
713
|
+
return type.__hash__(cls)
|
714
|
+
|
715
|
+
@classmethod
|
716
|
+
def _proto_hook(cls, other):
|
717
|
+
if not cls.__dict__.get('_is_protocol', False):
|
718
|
+
return NotImplemented
|
719
|
+
|
720
|
+
for attr in cls.__protocol_attrs__:
|
721
|
+
for base in other.__mro__:
|
722
|
+
# Check if the members appears in the class dictionary...
|
723
|
+
if attr in base.__dict__:
|
724
|
+
if base.__dict__[attr] is None:
|
725
|
+
return NotImplemented
|
726
|
+
break
|
727
|
+
|
728
|
+
# ...or in annotations, if it is a sub-protocol.
|
729
|
+
annotations = getattr(base, '__annotations__', {})
|
730
|
+
if (
|
731
|
+
isinstance(annotations, collections.abc.Mapping)
|
732
|
+
and attr in annotations
|
733
|
+
and is_protocol(other)
|
734
|
+
):
|
735
|
+
break
|
736
|
+
else:
|
737
|
+
return NotImplemented
|
738
|
+
return True
|
739
|
+
|
740
|
+
if sys.version_info >= (3, 8):
|
741
|
+
class Protocol(typing.Generic, metaclass=_ProtocolMeta):
|
742
|
+
__doc__ = typing.Protocol.__doc__
|
743
|
+
__slots__ = ()
|
744
|
+
_is_protocol = True
|
745
|
+
_is_runtime_protocol = False
|
746
|
+
|
747
|
+
def __init_subclass__(cls, *args, **kwargs):
|
748
|
+
super().__init_subclass__(*args, **kwargs)
|
749
|
+
|
750
|
+
# Determine if this is a protocol or a concrete subclass.
|
751
|
+
if not cls.__dict__.get('_is_protocol', False):
|
752
|
+
cls._is_protocol = any(b is Protocol for b in cls.__bases__)
|
753
|
+
|
754
|
+
# Set (or override) the protocol subclass hook.
|
755
|
+
if '__subclasshook__' not in cls.__dict__:
|
756
|
+
cls.__subclasshook__ = _proto_hook
|
757
|
+
|
758
|
+
# Prohibit instantiation for protocol classes
|
759
|
+
if cls._is_protocol and cls.__init__ is Protocol.__init__:
|
760
|
+
cls.__init__ = _no_init
|
761
|
+
|
762
|
+
else:
|
763
|
+
class Protocol(metaclass=_ProtocolMeta):
|
764
|
+
# There is quite a lot of overlapping code with typing.Generic.
|
765
|
+
# Unfortunately it is hard to avoid this on Python <3.8,
|
766
|
+
# as the typing module on Python 3.7 doesn't let us subclass typing.Generic!
|
767
|
+
"""Base class for protocol classes. Protocol classes are defined as::
|
768
|
+
|
769
|
+
class Proto(Protocol):
|
770
|
+
def meth(self) -> int:
|
771
|
+
...
|
772
|
+
|
773
|
+
Such classes are primarily used with static type checkers that recognize
|
774
|
+
structural subtyping (static duck-typing), for example::
|
775
|
+
|
776
|
+
class C:
|
777
|
+
def meth(self) -> int:
|
778
|
+
return 0
|
779
|
+
|
780
|
+
def func(x: Proto) -> int:
|
781
|
+
return x.meth()
|
782
|
+
|
783
|
+
func(C()) # Passes static type check
|
784
|
+
|
785
|
+
See PEP 544 for details. Protocol classes decorated with
|
786
|
+
@typing_extensions.runtime_checkable act
|
787
|
+
as simple-minded runtime-checkable protocols that check
|
788
|
+
only the presence of given attributes, ignoring their type signatures.
|
789
|
+
|
790
|
+
Protocol classes can be generic, they are defined as::
|
791
|
+
|
792
|
+
class GenProto(Protocol[T]):
|
793
|
+
def meth(self) -> T:
|
794
|
+
...
|
795
|
+
"""
|
796
|
+
__slots__ = ()
|
797
|
+
_is_protocol = True
|
798
|
+
_is_runtime_protocol = False
|
799
|
+
|
800
|
+
def __new__(cls, *args, **kwds):
|
801
|
+
if cls is Protocol:
|
802
|
+
raise TypeError("Type Protocol cannot be instantiated; "
|
803
|
+
"it can only be used as a base class")
|
804
|
+
return super().__new__(cls)
|
805
|
+
|
806
|
+
@typing._tp_cache
|
807
|
+
def __class_getitem__(cls, params):
|
808
|
+
if not isinstance(params, tuple):
|
809
|
+
params = (params,)
|
810
|
+
if not params and cls is not typing.Tuple:
|
811
|
+
raise TypeError(
|
812
|
+
f"Parameter list to {cls.__qualname__}[...] cannot be empty")
|
813
|
+
msg = "Parameters to generic types must be types."
|
814
|
+
params = tuple(typing._type_check(p, msg) for p in params)
|
815
|
+
if cls is Protocol:
|
816
|
+
# Generic can only be subscripted with unique type variables.
|
817
|
+
if not all(isinstance(p, typing.TypeVar) for p in params):
|
818
|
+
i = 0
|
819
|
+
while isinstance(params[i], typing.TypeVar):
|
820
|
+
i += 1
|
821
|
+
raise TypeError(
|
822
|
+
"Parameters to Protocol[...] must all be type variables."
|
823
|
+
f" Parameter {i + 1} is {params[i]}")
|
824
|
+
if len(set(params)) != len(params):
|
825
|
+
raise TypeError(
|
826
|
+
"Parameters to Protocol[...] must all be unique")
|
827
|
+
else:
|
828
|
+
# Subscripting a regular Generic subclass.
|
829
|
+
_check_generic(cls, params, len(cls.__parameters__))
|
830
|
+
return typing._GenericAlias(cls, params)
|
831
|
+
|
832
|
+
def __init_subclass__(cls, *args, **kwargs):
|
833
|
+
if '__orig_bases__' in cls.__dict__:
|
834
|
+
error = typing.Generic in cls.__orig_bases__
|
835
|
+
else:
|
836
|
+
error = typing.Generic in cls.__bases__
|
837
|
+
if error:
|
838
|
+
raise TypeError("Cannot inherit from plain Generic")
|
839
|
+
_maybe_adjust_parameters(cls)
|
840
|
+
|
841
|
+
# Determine if this is a protocol or a concrete subclass.
|
842
|
+
if not cls.__dict__.get('_is_protocol', None):
|
843
|
+
cls._is_protocol = any(b is Protocol for b in cls.__bases__)
|
844
|
+
|
845
|
+
# Set (or override) the protocol subclass hook.
|
846
|
+
if '__subclasshook__' not in cls.__dict__:
|
847
|
+
cls.__subclasshook__ = _proto_hook
|
848
|
+
|
849
|
+
# Prohibit instantiation for protocol classes
|
850
|
+
if cls._is_protocol and cls.__init__ is Protocol.__init__:
|
851
|
+
cls.__init__ = _no_init
|
852
|
+
|
853
|
+
|
854
|
+
if sys.version_info >= (3, 8):
|
855
|
+
runtime_checkable = typing.runtime_checkable
|
856
|
+
else:
|
857
|
+
def runtime_checkable(cls):
|
858
|
+
"""Mark a protocol class as a runtime protocol, so that it
|
859
|
+
can be used with isinstance() and issubclass(). Raise TypeError
|
860
|
+
if applied to a non-protocol class.
|
861
|
+
|
862
|
+
This allows a simple-minded structural check very similar to the
|
863
|
+
one-offs in collections.abc such as Hashable.
|
864
|
+
"""
|
865
|
+
if not (
|
866
|
+
(isinstance(cls, _ProtocolMeta) or issubclass(cls, typing.Generic))
|
867
|
+
and getattr(cls, "_is_protocol", False)
|
868
|
+
):
|
869
|
+
raise TypeError('@runtime_checkable can be only applied to protocol classes,'
|
870
|
+
f' got {cls!r}')
|
871
|
+
cls._is_runtime_protocol = True
|
872
|
+
return cls
|
873
|
+
|
874
|
+
|
875
|
+
# Exists for backwards compatibility.
|
876
|
+
runtime = runtime_checkable
|
877
|
+
|
878
|
+
|
879
|
+
# Our version of runtime-checkable protocols is faster on Python 3.7-3.11
|
880
|
+
if sys.version_info >= (3, 12):
|
881
|
+
SupportsInt = typing.SupportsInt
|
882
|
+
SupportsFloat = typing.SupportsFloat
|
883
|
+
SupportsComplex = typing.SupportsComplex
|
884
|
+
SupportsBytes = typing.SupportsBytes
|
885
|
+
SupportsIndex = typing.SupportsIndex
|
886
|
+
SupportsAbs = typing.SupportsAbs
|
887
|
+
SupportsRound = typing.SupportsRound
|
888
|
+
else:
|
889
|
+
@runtime_checkable
|
890
|
+
class SupportsInt(Protocol):
|
891
|
+
"""An ABC with one abstract method __int__."""
|
892
|
+
__slots__ = ()
|
893
|
+
|
894
|
+
@abc.abstractmethod
|
895
|
+
def __int__(self) -> int:
|
896
|
+
pass
|
897
|
+
|
898
|
+
@runtime_checkable
|
899
|
+
class SupportsFloat(Protocol):
|
900
|
+
"""An ABC with one abstract method __float__."""
|
901
|
+
__slots__ = ()
|
902
|
+
|
903
|
+
@abc.abstractmethod
|
904
|
+
def __float__(self) -> float:
|
905
|
+
pass
|
906
|
+
|
907
|
+
@runtime_checkable
|
908
|
+
class SupportsComplex(Protocol):
|
909
|
+
"""An ABC with one abstract method __complex__."""
|
910
|
+
__slots__ = ()
|
911
|
+
|
912
|
+
@abc.abstractmethod
|
913
|
+
def __complex__(self) -> complex:
|
914
|
+
pass
|
915
|
+
|
916
|
+
@runtime_checkable
|
917
|
+
class SupportsBytes(Protocol):
|
918
|
+
"""An ABC with one abstract method __bytes__."""
|
919
|
+
__slots__ = ()
|
920
|
+
|
921
|
+
@abc.abstractmethod
|
922
|
+
def __bytes__(self) -> bytes:
|
923
|
+
pass
|
924
|
+
|
925
|
+
@runtime_checkable
|
926
|
+
class SupportsIndex(Protocol):
|
927
|
+
__slots__ = ()
|
928
|
+
|
929
|
+
@abc.abstractmethod
|
930
|
+
def __index__(self) -> int:
|
931
|
+
pass
|
932
|
+
|
933
|
+
@runtime_checkable
|
934
|
+
class SupportsAbs(Protocol[T_co]):
|
935
|
+
"""
|
936
|
+
An ABC with one abstract method __abs__ that is covariant in its return type.
|
937
|
+
"""
|
938
|
+
__slots__ = ()
|
939
|
+
|
940
|
+
@abc.abstractmethod
|
941
|
+
def __abs__(self) -> T_co:
|
942
|
+
pass
|
943
|
+
|
944
|
+
@runtime_checkable
|
945
|
+
class SupportsRound(Protocol[T_co]):
|
946
|
+
"""
|
947
|
+
An ABC with one abstract method __round__ that is covariant in its return type.
|
948
|
+
"""
|
949
|
+
__slots__ = ()
|
950
|
+
|
951
|
+
@abc.abstractmethod
|
952
|
+
def __round__(self, ndigits: int = 0) -> T_co:
|
953
|
+
pass
|
954
|
+
|
955
|
+
|
956
|
+
def _ensure_subclassable(mro_entries):
|
957
|
+
def inner(func):
|
958
|
+
if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
|
959
|
+
cls_dict = {
|
960
|
+
"__call__": staticmethod(func),
|
961
|
+
"__mro_entries__": staticmethod(mro_entries)
|
962
|
+
}
|
963
|
+
t = type(func.__name__, (), cls_dict)
|
964
|
+
return functools.update_wrapper(t(), func)
|
965
|
+
else:
|
966
|
+
func.__mro_entries__ = mro_entries
|
967
|
+
return func
|
968
|
+
return inner
|
969
|
+
|
970
|
+
|
971
|
+
if sys.version_info >= (3, 13):
|
972
|
+
# The standard library TypedDict in Python 3.8 does not store runtime information
|
973
|
+
# about which (if any) keys are optional. See https://bugs.python.org/issue38834
|
974
|
+
# The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
|
975
|
+
# keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
|
976
|
+
# The standard library TypedDict below Python 3.11 does not store runtime
|
977
|
+
# information about optional and required keys when using Required or NotRequired.
|
978
|
+
# Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
|
979
|
+
# Aaaand on 3.12 we add __orig_bases__ to TypedDict
|
980
|
+
# to enable better runtime introspection.
|
981
|
+
# On 3.13 we deprecate some odd ways of creating TypedDicts.
|
982
|
+
TypedDict = typing.TypedDict
|
983
|
+
_TypedDictMeta = typing._TypedDictMeta
|
984
|
+
is_typeddict = typing.is_typeddict
|
985
|
+
else:
|
986
|
+
# 3.10.0 and later
|
987
|
+
_TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
|
988
|
+
|
989
|
+
if sys.version_info >= (3, 8):
|
990
|
+
_fake_name = "Protocol"
|
991
|
+
else:
|
992
|
+
_fake_name = "_Protocol"
|
993
|
+
|
994
|
+
class _TypedDictMeta(type):
|
995
|
+
def __new__(cls, name, bases, ns, total=True):
|
996
|
+
"""Create new typed dict class object.
|
997
|
+
|
998
|
+
This method is called when TypedDict is subclassed,
|
999
|
+
or when TypedDict is instantiated. This way
|
1000
|
+
TypedDict supports all three syntax forms described in its docstring.
|
1001
|
+
Subclasses and instances of TypedDict return actual dictionaries.
|
1002
|
+
"""
|
1003
|
+
for base in bases:
|
1004
|
+
if type(base) is not _TypedDictMeta and base is not typing.Generic:
|
1005
|
+
raise TypeError('cannot inherit from both a TypedDict type '
|
1006
|
+
'and a non-TypedDict base class')
|
1007
|
+
|
1008
|
+
if any(issubclass(b, typing.Generic) for b in bases):
|
1009
|
+
generic_base = (typing.Generic,)
|
1010
|
+
else:
|
1011
|
+
generic_base = ()
|
1012
|
+
|
1013
|
+
# typing.py generally doesn't let you inherit from plain Generic, unless
|
1014
|
+
# the name of the class happens to be "Protocol" (or "_Protocol" on 3.7).
|
1015
|
+
tp_dict = type.__new__(_TypedDictMeta, _fake_name, (*generic_base, dict), ns)
|
1016
|
+
tp_dict.__name__ = name
|
1017
|
+
if tp_dict.__qualname__ == _fake_name:
|
1018
|
+
tp_dict.__qualname__ = name
|
1019
|
+
|
1020
|
+
if not hasattr(tp_dict, '__orig_bases__'):
|
1021
|
+
tp_dict.__orig_bases__ = bases
|
1022
|
+
|
1023
|
+
annotations = {}
|
1024
|
+
own_annotations = ns.get('__annotations__', {})
|
1025
|
+
msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
|
1026
|
+
if _TAKES_MODULE:
|
1027
|
+
own_annotations = {
|
1028
|
+
n: typing._type_check(tp, msg, module=tp_dict.__module__)
|
1029
|
+
for n, tp in own_annotations.items()
|
1030
|
+
}
|
1031
|
+
else:
|
1032
|
+
own_annotations = {
|
1033
|
+
n: typing._type_check(tp, msg)
|
1034
|
+
for n, tp in own_annotations.items()
|
1035
|
+
}
|
1036
|
+
required_keys = set()
|
1037
|
+
optional_keys = set()
|
1038
|
+
|
1039
|
+
for base in bases:
|
1040
|
+
annotations.update(base.__dict__.get('__annotations__', {}))
|
1041
|
+
required_keys.update(base.__dict__.get('__required_keys__', ()))
|
1042
|
+
optional_keys.update(base.__dict__.get('__optional_keys__', ()))
|
1043
|
+
|
1044
|
+
annotations.update(own_annotations)
|
1045
|
+
for annotation_key, annotation_type in own_annotations.items():
|
1046
|
+
annotation_origin = get_origin(annotation_type)
|
1047
|
+
if annotation_origin is Annotated:
|
1048
|
+
annotation_args = get_args(annotation_type)
|
1049
|
+
if annotation_args:
|
1050
|
+
annotation_type = annotation_args[0]
|
1051
|
+
annotation_origin = get_origin(annotation_type)
|
1052
|
+
|
1053
|
+
if annotation_origin is Required:
|
1054
|
+
required_keys.add(annotation_key)
|
1055
|
+
elif annotation_origin is NotRequired:
|
1056
|
+
optional_keys.add(annotation_key)
|
1057
|
+
elif total:
|
1058
|
+
required_keys.add(annotation_key)
|
1059
|
+
else:
|
1060
|
+
optional_keys.add(annotation_key)
|
1061
|
+
|
1062
|
+
tp_dict.__annotations__ = annotations
|
1063
|
+
tp_dict.__required_keys__ = frozenset(required_keys)
|
1064
|
+
tp_dict.__optional_keys__ = frozenset(optional_keys)
|
1065
|
+
if not hasattr(tp_dict, '__total__'):
|
1066
|
+
tp_dict.__total__ = total
|
1067
|
+
return tp_dict
|
1068
|
+
|
1069
|
+
__call__ = dict # static method
|
1070
|
+
|
1071
|
+
def __subclasscheck__(cls, other):
|
1072
|
+
# Typed dicts are only for static structural subtyping.
|
1073
|
+
raise TypeError('TypedDict does not support instance and class checks')
|
1074
|
+
|
1075
|
+
__instancecheck__ = __subclasscheck__
|
1076
|
+
|
1077
|
+
_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
|
1078
|
+
|
1079
|
+
@_ensure_subclassable(lambda bases: (_TypedDict,))
|
1080
|
+
def TypedDict(__typename, __fields=_marker, *, total=True, **kwargs):
|
1081
|
+
"""A simple typed namespace. At runtime it is equivalent to a plain dict.
|
1082
|
+
|
1083
|
+
TypedDict creates a dictionary type such that a type checker will expect all
|
1084
|
+
instances to have a certain set of keys, where each key is
|
1085
|
+
associated with a value of a consistent type. This expectation
|
1086
|
+
is not checked at runtime.
|
1087
|
+
|
1088
|
+
Usage::
|
1089
|
+
|
1090
|
+
class Point2D(TypedDict):
|
1091
|
+
x: int
|
1092
|
+
y: int
|
1093
|
+
label: str
|
1094
|
+
|
1095
|
+
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
|
1096
|
+
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
|
1097
|
+
|
1098
|
+
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
|
1099
|
+
|
1100
|
+
The type info can be accessed via the Point2D.__annotations__ dict, and
|
1101
|
+
the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
|
1102
|
+
TypedDict supports an additional equivalent form::
|
1103
|
+
|
1104
|
+
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
|
1105
|
+
|
1106
|
+
By default, all keys must be present in a TypedDict. It is possible
|
1107
|
+
to override this by specifying totality::
|
1108
|
+
|
1109
|
+
class Point2D(TypedDict, total=False):
|
1110
|
+
x: int
|
1111
|
+
y: int
|
1112
|
+
|
1113
|
+
This means that a Point2D TypedDict can have any of the keys omitted. A type
|
1114
|
+
checker is only expected to support a literal False or True as the value of
|
1115
|
+
the total argument. True is the default, and makes all items defined in the
|
1116
|
+
class body be required.
|
1117
|
+
|
1118
|
+
The Required and NotRequired special forms can also be used to mark
|
1119
|
+
individual keys as being required or not required::
|
1120
|
+
|
1121
|
+
class Point2D(TypedDict):
|
1122
|
+
x: int # the "x" key must always be present (Required is the default)
|
1123
|
+
y: NotRequired[int] # the "y" key can be omitted
|
1124
|
+
|
1125
|
+
See PEP 655 for more details on Required and NotRequired.
|
1126
|
+
"""
|
1127
|
+
if __fields is _marker or __fields is None:
|
1128
|
+
if __fields is _marker:
|
1129
|
+
deprecated_thing = "Failing to pass a value for the 'fields' parameter"
|
1130
|
+
else:
|
1131
|
+
deprecated_thing = "Passing `None` as the 'fields' parameter"
|
1132
|
+
|
1133
|
+
example = f"`{__typename} = TypedDict({__typename!r}, {{}})`"
|
1134
|
+
deprecation_msg = (
|
1135
|
+
f"{deprecated_thing} is deprecated and will be disallowed in "
|
1136
|
+
"Python 3.15. To create a TypedDict class with 0 fields "
|
1137
|
+
"using the functional syntax, pass an empty dictionary, e.g. "
|
1138
|
+
) + example + "."
|
1139
|
+
warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
|
1140
|
+
__fields = kwargs
|
1141
|
+
elif kwargs:
|
1142
|
+
raise TypeError("TypedDict takes either a dict or keyword arguments,"
|
1143
|
+
" but not both")
|
1144
|
+
if kwargs:
|
1145
|
+
warnings.warn(
|
1146
|
+
"The kwargs-based syntax for TypedDict definitions is deprecated "
|
1147
|
+
"in Python 3.11, will be removed in Python 3.13, and may not be "
|
1148
|
+
"understood by third-party type checkers.",
|
1149
|
+
DeprecationWarning,
|
1150
|
+
stacklevel=2,
|
1151
|
+
)
|
1152
|
+
|
1153
|
+
ns = {'__annotations__': dict(__fields)}
|
1154
|
+
module = _caller()
|
1155
|
+
if module is not None:
|
1156
|
+
# Setting correct module is necessary to make typed dict classes pickleable.
|
1157
|
+
ns['__module__'] = module
|
1158
|
+
|
1159
|
+
td = _TypedDictMeta(__typename, (), ns, total=total)
|
1160
|
+
td.__orig_bases__ = (TypedDict,)
|
1161
|
+
return td
|
1162
|
+
|
1163
|
+
if hasattr(typing, "_TypedDictMeta"):
|
1164
|
+
_TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
|
1165
|
+
else:
|
1166
|
+
_TYPEDDICT_TYPES = (_TypedDictMeta,)
|
1167
|
+
|
1168
|
+
def is_typeddict(tp):
|
1169
|
+
"""Check if an annotation is a TypedDict class
|
1170
|
+
|
1171
|
+
For example::
|
1172
|
+
class Film(TypedDict):
|
1173
|
+
title: str
|
1174
|
+
year: int
|
1175
|
+
|
1176
|
+
is_typeddict(Film) # => True
|
1177
|
+
is_typeddict(Union[list, str]) # => False
|
1178
|
+
"""
|
1179
|
+
# On 3.8, this would otherwise return True
|
1180
|
+
if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
|
1181
|
+
return False
|
1182
|
+
return isinstance(tp, _TYPEDDICT_TYPES)
|
1183
|
+
|
1184
|
+
|
1185
|
+
if hasattr(typing, "assert_type"):
|
1186
|
+
assert_type = typing.assert_type
|
1187
|
+
|
1188
|
+
else:
|
1189
|
+
def assert_type(__val, __typ):
|
1190
|
+
"""Assert (to the type checker) that the value is of the given type.
|
1191
|
+
|
1192
|
+
When the type checker encounters a call to assert_type(), it
|
1193
|
+
emits an error if the value is not of the specified type::
|
1194
|
+
|
1195
|
+
def greet(name: str) -> None:
|
1196
|
+
assert_type(name, str) # ok
|
1197
|
+
assert_type(name, int) # type checker error
|
1198
|
+
|
1199
|
+
At runtime this returns the first argument unchanged and otherwise
|
1200
|
+
does nothing.
|
1201
|
+
"""
|
1202
|
+
return __val
|
1203
|
+
|
1204
|
+
|
1205
|
+
if hasattr(typing, "Required"):
|
1206
|
+
get_type_hints = typing.get_type_hints
|
1207
|
+
else:
|
1208
|
+
# replaces _strip_annotations()
|
1209
|
+
def _strip_extras(t):
|
1210
|
+
"""Strips Annotated, Required and NotRequired from a given type."""
|
1211
|
+
if isinstance(t, _AnnotatedAlias):
|
1212
|
+
return _strip_extras(t.__origin__)
|
1213
|
+
if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
|
1214
|
+
return _strip_extras(t.__args__[0])
|
1215
|
+
if isinstance(t, typing._GenericAlias):
|
1216
|
+
stripped_args = tuple(_strip_extras(a) for a in t.__args__)
|
1217
|
+
if stripped_args == t.__args__:
|
1218
|
+
return t
|
1219
|
+
return t.copy_with(stripped_args)
|
1220
|
+
if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
|
1221
|
+
stripped_args = tuple(_strip_extras(a) for a in t.__args__)
|
1222
|
+
if stripped_args == t.__args__:
|
1223
|
+
return t
|
1224
|
+
return _types.GenericAlias(t.__origin__, stripped_args)
|
1225
|
+
if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
|
1226
|
+
stripped_args = tuple(_strip_extras(a) for a in t.__args__)
|
1227
|
+
if stripped_args == t.__args__:
|
1228
|
+
return t
|
1229
|
+
return functools.reduce(operator.or_, stripped_args)
|
1230
|
+
|
1231
|
+
return t
|
1232
|
+
|
1233
|
+
def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
|
1234
|
+
"""Return type hints for an object.
|
1235
|
+
|
1236
|
+
This is often the same as obj.__annotations__, but it handles
|
1237
|
+
forward references encoded as string literals, adds Optional[t] if a
|
1238
|
+
default value equal to None is set and recursively replaces all
|
1239
|
+
'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
|
1240
|
+
(unless 'include_extras=True').
|
1241
|
+
|
1242
|
+
The argument may be a module, class, method, or function. The annotations
|
1243
|
+
are returned as a dictionary. For classes, annotations include also
|
1244
|
+
inherited members.
|
1245
|
+
|
1246
|
+
TypeError is raised if the argument is not of a type that can contain
|
1247
|
+
annotations, and an empty dictionary is returned if no annotations are
|
1248
|
+
present.
|
1249
|
+
|
1250
|
+
BEWARE -- the behavior of globalns and localns is counterintuitive
|
1251
|
+
(unless you are familiar with how eval() and exec() work). The
|
1252
|
+
search order is locals first, then globals.
|
1253
|
+
|
1254
|
+
- If no dict arguments are passed, an attempt is made to use the
|
1255
|
+
globals from obj (or the respective module's globals for classes),
|
1256
|
+
and these are also used as the locals. If the object does not appear
|
1257
|
+
to have globals, an empty dictionary is used.
|
1258
|
+
|
1259
|
+
- If one dict argument is passed, it is used for both globals and
|
1260
|
+
locals.
|
1261
|
+
|
1262
|
+
- If two dict arguments are passed, they specify globals and
|
1263
|
+
locals, respectively.
|
1264
|
+
"""
|
1265
|
+
if hasattr(typing, "Annotated"):
|
1266
|
+
hint = typing.get_type_hints(
|
1267
|
+
obj, globalns=globalns, localns=localns, include_extras=True
|
1268
|
+
)
|
1269
|
+
else:
|
1270
|
+
hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
|
1271
|
+
if include_extras:
|
1272
|
+
return hint
|
1273
|
+
return {k: _strip_extras(t) for k, t in hint.items()}
|
1274
|
+
|
1275
|
+
|
1276
|
+
# Python 3.9+ has PEP 593 (Annotated)
|
1277
|
+
if hasattr(typing, 'Annotated'):
|
1278
|
+
Annotated = typing.Annotated
|
1279
|
+
# Not exported and not a public API, but needed for get_origin() and get_args()
|
1280
|
+
# to work.
|
1281
|
+
_AnnotatedAlias = typing._AnnotatedAlias
|
1282
|
+
# 3.7-3.8
|
1283
|
+
else:
|
1284
|
+
class _AnnotatedAlias(typing._GenericAlias, _root=True):
|
1285
|
+
"""Runtime representation of an annotated type.
|
1286
|
+
|
1287
|
+
At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
|
1288
|
+
with extra annotations. The alias behaves like a normal typing alias,
|
1289
|
+
instantiating is the same as instantiating the underlying type, binding
|
1290
|
+
it to types is also the same.
|
1291
|
+
"""
|
1292
|
+
def __init__(self, origin, metadata):
|
1293
|
+
if isinstance(origin, _AnnotatedAlias):
|
1294
|
+
metadata = origin.__metadata__ + metadata
|
1295
|
+
origin = origin.__origin__
|
1296
|
+
super().__init__(origin, origin)
|
1297
|
+
self.__metadata__ = metadata
|
1298
|
+
|
1299
|
+
def copy_with(self, params):
|
1300
|
+
assert len(params) == 1
|
1301
|
+
new_type = params[0]
|
1302
|
+
return _AnnotatedAlias(new_type, self.__metadata__)
|
1303
|
+
|
1304
|
+
def __repr__(self):
|
1305
|
+
return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
|
1306
|
+
f"{', '.join(repr(a) for a in self.__metadata__)}]")
|
1307
|
+
|
1308
|
+
def __reduce__(self):
|
1309
|
+
return operator.getitem, (
|
1310
|
+
Annotated, (self.__origin__,) + self.__metadata__
|
1311
|
+
)
|
1312
|
+
|
1313
|
+
def __eq__(self, other):
|
1314
|
+
if not isinstance(other, _AnnotatedAlias):
|
1315
|
+
return NotImplemented
|
1316
|
+
if self.__origin__ != other.__origin__:
|
1317
|
+
return False
|
1318
|
+
return self.__metadata__ == other.__metadata__
|
1319
|
+
|
1320
|
+
def __hash__(self):
|
1321
|
+
return hash((self.__origin__, self.__metadata__))
|
1322
|
+
|
1323
|
+
class Annotated:
|
1324
|
+
"""Add context specific metadata to a type.
|
1325
|
+
|
1326
|
+
Example: Annotated[int, runtime_check.Unsigned] indicates to the
|
1327
|
+
hypothetical runtime_check module that this type is an unsigned int.
|
1328
|
+
Every other consumer of this type can ignore this metadata and treat
|
1329
|
+
this type as int.
|
1330
|
+
|
1331
|
+
The first argument to Annotated must be a valid type (and will be in
|
1332
|
+
the __origin__ field), the remaining arguments are kept as a tuple in
|
1333
|
+
the __extra__ field.
|
1334
|
+
|
1335
|
+
Details:
|
1336
|
+
|
1337
|
+
- It's an error to call `Annotated` with less than two arguments.
|
1338
|
+
- Nested Annotated are flattened::
|
1339
|
+
|
1340
|
+
Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
|
1341
|
+
|
1342
|
+
- Instantiating an annotated type is equivalent to instantiating the
|
1343
|
+
underlying type::
|
1344
|
+
|
1345
|
+
Annotated[C, Ann1](5) == C(5)
|
1346
|
+
|
1347
|
+
- Annotated can be used as a generic type alias::
|
1348
|
+
|
1349
|
+
Optimized = Annotated[T, runtime.Optimize()]
|
1350
|
+
Optimized[int] == Annotated[int, runtime.Optimize()]
|
1351
|
+
|
1352
|
+
OptimizedList = Annotated[List[T], runtime.Optimize()]
|
1353
|
+
OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
|
1354
|
+
"""
|
1355
|
+
|
1356
|
+
__slots__ = ()
|
1357
|
+
|
1358
|
+
def __new__(cls, *args, **kwargs):
|
1359
|
+
raise TypeError("Type Annotated cannot be instantiated.")
|
1360
|
+
|
1361
|
+
@typing._tp_cache
|
1362
|
+
def __class_getitem__(cls, params):
|
1363
|
+
if not isinstance(params, tuple) or len(params) < 2:
|
1364
|
+
raise TypeError("Annotated[...] should be used "
|
1365
|
+
"with at least two arguments (a type and an "
|
1366
|
+
"annotation).")
|
1367
|
+
allowed_special_forms = (ClassVar, Final)
|
1368
|
+
if get_origin(params[0]) in allowed_special_forms:
|
1369
|
+
origin = params[0]
|
1370
|
+
else:
|
1371
|
+
msg = "Annotated[t, ...]: t must be a type."
|
1372
|
+
origin = typing._type_check(params[0], msg)
|
1373
|
+
metadata = tuple(params[1:])
|
1374
|
+
return _AnnotatedAlias(origin, metadata)
|
1375
|
+
|
1376
|
+
def __init_subclass__(cls, *args, **kwargs):
|
1377
|
+
raise TypeError(
|
1378
|
+
f"Cannot subclass {cls.__module__}.Annotated"
|
1379
|
+
)
|
1380
|
+
|
1381
|
+
# Python 3.8 has get_origin() and get_args() but those implementations aren't
|
1382
|
+
# Annotated-aware, so we can't use those. Python 3.9's versions don't support
|
1383
|
+
# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
|
1384
|
+
if sys.version_info[:2] >= (3, 10):
|
1385
|
+
get_origin = typing.get_origin
|
1386
|
+
get_args = typing.get_args
|
1387
|
+
# 3.7-3.9
|
1388
|
+
else:
|
1389
|
+
try:
|
1390
|
+
# 3.9+
|
1391
|
+
from typing import _BaseGenericAlias
|
1392
|
+
except ImportError:
|
1393
|
+
_BaseGenericAlias = typing._GenericAlias
|
1394
|
+
try:
|
1395
|
+
# 3.9+
|
1396
|
+
from typing import GenericAlias as _typing_GenericAlias
|
1397
|
+
except ImportError:
|
1398
|
+
_typing_GenericAlias = typing._GenericAlias
|
1399
|
+
|
1400
|
+
def get_origin(tp):
|
1401
|
+
"""Get the unsubscripted version of a type.
|
1402
|
+
|
1403
|
+
This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
|
1404
|
+
and Annotated. Return None for unsupported types. Examples::
|
1405
|
+
|
1406
|
+
get_origin(Literal[42]) is Literal
|
1407
|
+
get_origin(int) is None
|
1408
|
+
get_origin(ClassVar[int]) is ClassVar
|
1409
|
+
get_origin(Generic) is Generic
|
1410
|
+
get_origin(Generic[T]) is Generic
|
1411
|
+
get_origin(Union[T, int]) is Union
|
1412
|
+
get_origin(List[Tuple[T, T]][int]) == list
|
1413
|
+
get_origin(P.args) is P
|
1414
|
+
"""
|
1415
|
+
if isinstance(tp, _AnnotatedAlias):
|
1416
|
+
return Annotated
|
1417
|
+
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
|
1418
|
+
ParamSpecArgs, ParamSpecKwargs)):
|
1419
|
+
return tp.__origin__
|
1420
|
+
if tp is typing.Generic:
|
1421
|
+
return typing.Generic
|
1422
|
+
return None
|
1423
|
+
|
1424
|
+
def get_args(tp):
|
1425
|
+
"""Get type arguments with all substitutions performed.
|
1426
|
+
|
1427
|
+
For unions, basic simplifications used by Union constructor are performed.
|
1428
|
+
Examples::
|
1429
|
+
get_args(Dict[str, int]) == (str, int)
|
1430
|
+
get_args(int) == ()
|
1431
|
+
get_args(Union[int, Union[T, int], str][int]) == (int, str)
|
1432
|
+
get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
|
1433
|
+
get_args(Callable[[], T][int]) == ([], int)
|
1434
|
+
"""
|
1435
|
+
if isinstance(tp, _AnnotatedAlias):
|
1436
|
+
return (tp.__origin__,) + tp.__metadata__
|
1437
|
+
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
|
1438
|
+
if getattr(tp, "_special", False):
|
1439
|
+
return ()
|
1440
|
+
res = tp.__args__
|
1441
|
+
if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
|
1442
|
+
res = (list(res[:-1]), res[-1])
|
1443
|
+
return res
|
1444
|
+
return ()
|
1445
|
+
|
1446
|
+
|
1447
|
+
# 3.10+
|
1448
|
+
if hasattr(typing, 'TypeAlias'):
|
1449
|
+
TypeAlias = typing.TypeAlias
|
1450
|
+
# 3.9
|
1451
|
+
elif sys.version_info[:2] >= (3, 9):
|
1452
|
+
@_ExtensionsSpecialForm
|
1453
|
+
def TypeAlias(self, parameters):
|
1454
|
+
"""Special marker indicating that an assignment should
|
1455
|
+
be recognized as a proper type alias definition by type
|
1456
|
+
checkers.
|
1457
|
+
|
1458
|
+
For example::
|
1459
|
+
|
1460
|
+
Predicate: TypeAlias = Callable[..., bool]
|
1461
|
+
|
1462
|
+
It's invalid when used anywhere except as in the example above.
|
1463
|
+
"""
|
1464
|
+
raise TypeError(f"{self} is not subscriptable")
|
1465
|
+
# 3.7-3.8
|
1466
|
+
else:
|
1467
|
+
TypeAlias = _ExtensionsSpecialForm(
|
1468
|
+
'TypeAlias',
|
1469
|
+
doc="""Special marker indicating that an assignment should
|
1470
|
+
be recognized as a proper type alias definition by type
|
1471
|
+
checkers.
|
1472
|
+
|
1473
|
+
For example::
|
1474
|
+
|
1475
|
+
Predicate: TypeAlias = Callable[..., bool]
|
1476
|
+
|
1477
|
+
It's invalid when used anywhere except as in the example
|
1478
|
+
above."""
|
1479
|
+
)
|
1480
|
+
|
1481
|
+
|
1482
|
+
def _set_default(type_param, default):
|
1483
|
+
if isinstance(default, (tuple, list)):
|
1484
|
+
type_param.__default__ = tuple((typing._type_check(d, "Default must be a type")
|
1485
|
+
for d in default))
|
1486
|
+
elif default != _marker:
|
1487
|
+
type_param.__default__ = typing._type_check(default, "Default must be a type")
|
1488
|
+
else:
|
1489
|
+
type_param.__default__ = None
|
1490
|
+
|
1491
|
+
|
1492
|
+
def _set_module(typevarlike):
|
1493
|
+
# for pickling:
|
1494
|
+
def_mod = _caller(depth=3)
|
1495
|
+
if def_mod != 'typing_extensions':
|
1496
|
+
typevarlike.__module__ = def_mod
|
1497
|
+
|
1498
|
+
|
1499
|
+
class _DefaultMixin:
|
1500
|
+
"""Mixin for TypeVarLike defaults."""
|
1501
|
+
|
1502
|
+
__slots__ = ()
|
1503
|
+
__init__ = _set_default
|
1504
|
+
|
1505
|
+
|
1506
|
+
# Classes using this metaclass must provide a _backported_typevarlike ClassVar
|
1507
|
+
class _TypeVarLikeMeta(type):
|
1508
|
+
def __instancecheck__(cls, __instance: Any) -> bool:
|
1509
|
+
return isinstance(__instance, cls._backported_typevarlike)
|
1510
|
+
|
1511
|
+
|
1512
|
+
# Add default and infer_variance parameters from PEP 696 and 695
|
1513
|
+
class TypeVar(metaclass=_TypeVarLikeMeta):
|
1514
|
+
"""Type variable."""
|
1515
|
+
|
1516
|
+
_backported_typevarlike = typing.TypeVar
|
1517
|
+
|
1518
|
+
def __new__(cls, name, *constraints, bound=None,
|
1519
|
+
covariant=False, contravariant=False,
|
1520
|
+
default=_marker, infer_variance=False):
|
1521
|
+
if hasattr(typing, "TypeAliasType"):
|
1522
|
+
# PEP 695 implemented, can pass infer_variance to typing.TypeVar
|
1523
|
+
typevar = typing.TypeVar(name, *constraints, bound=bound,
|
1524
|
+
covariant=covariant, contravariant=contravariant,
|
1525
|
+
infer_variance=infer_variance)
|
1526
|
+
else:
|
1527
|
+
typevar = typing.TypeVar(name, *constraints, bound=bound,
|
1528
|
+
covariant=covariant, contravariant=contravariant)
|
1529
|
+
if infer_variance and (covariant or contravariant):
|
1530
|
+
raise ValueError("Variance cannot be specified with infer_variance.")
|
1531
|
+
typevar.__infer_variance__ = infer_variance
|
1532
|
+
_set_default(typevar, default)
|
1533
|
+
_set_module(typevar)
|
1534
|
+
return typevar
|
1535
|
+
|
1536
|
+
def __init_subclass__(cls) -> None:
|
1537
|
+
raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
|
1538
|
+
|
1539
|
+
|
1540
|
+
# Python 3.10+ has PEP 612
|
1541
|
+
if hasattr(typing, 'ParamSpecArgs'):
|
1542
|
+
ParamSpecArgs = typing.ParamSpecArgs
|
1543
|
+
ParamSpecKwargs = typing.ParamSpecKwargs
|
1544
|
+
# 3.7-3.9
|
1545
|
+
else:
|
1546
|
+
class _Immutable:
|
1547
|
+
"""Mixin to indicate that object should not be copied."""
|
1548
|
+
__slots__ = ()
|
1549
|
+
|
1550
|
+
def __copy__(self):
|
1551
|
+
return self
|
1552
|
+
|
1553
|
+
def __deepcopy__(self, memo):
|
1554
|
+
return self
|
1555
|
+
|
1556
|
+
class ParamSpecArgs(_Immutable):
|
1557
|
+
"""The args for a ParamSpec object.
|
1558
|
+
|
1559
|
+
Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
|
1560
|
+
|
1561
|
+
ParamSpecArgs objects have a reference back to their ParamSpec:
|
1562
|
+
|
1563
|
+
P.args.__origin__ is P
|
1564
|
+
|
1565
|
+
This type is meant for runtime introspection and has no special meaning to
|
1566
|
+
static type checkers.
|
1567
|
+
"""
|
1568
|
+
def __init__(self, origin):
|
1569
|
+
self.__origin__ = origin
|
1570
|
+
|
1571
|
+
def __repr__(self):
|
1572
|
+
return f"{self.__origin__.__name__}.args"
|
1573
|
+
|
1574
|
+
def __eq__(self, other):
|
1575
|
+
if not isinstance(other, ParamSpecArgs):
|
1576
|
+
return NotImplemented
|
1577
|
+
return self.__origin__ == other.__origin__
|
1578
|
+
|
1579
|
+
class ParamSpecKwargs(_Immutable):
|
1580
|
+
"""The kwargs for a ParamSpec object.
|
1581
|
+
|
1582
|
+
Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
|
1583
|
+
|
1584
|
+
ParamSpecKwargs objects have a reference back to their ParamSpec:
|
1585
|
+
|
1586
|
+
P.kwargs.__origin__ is P
|
1587
|
+
|
1588
|
+
This type is meant for runtime introspection and has no special meaning to
|
1589
|
+
static type checkers.
|
1590
|
+
"""
|
1591
|
+
def __init__(self, origin):
|
1592
|
+
self.__origin__ = origin
|
1593
|
+
|
1594
|
+
def __repr__(self):
|
1595
|
+
return f"{self.__origin__.__name__}.kwargs"
|
1596
|
+
|
1597
|
+
def __eq__(self, other):
|
1598
|
+
if not isinstance(other, ParamSpecKwargs):
|
1599
|
+
return NotImplemented
|
1600
|
+
return self.__origin__ == other.__origin__
|
1601
|
+
|
1602
|
+
# 3.10+
|
1603
|
+
if hasattr(typing, 'ParamSpec'):
|
1604
|
+
|
1605
|
+
# Add default parameter - PEP 696
|
1606
|
+
class ParamSpec(metaclass=_TypeVarLikeMeta):
|
1607
|
+
"""Parameter specification."""
|
1608
|
+
|
1609
|
+
_backported_typevarlike = typing.ParamSpec
|
1610
|
+
|
1611
|
+
def __new__(cls, name, *, bound=None,
|
1612
|
+
covariant=False, contravariant=False,
|
1613
|
+
infer_variance=False, default=_marker):
|
1614
|
+
if hasattr(typing, "TypeAliasType"):
|
1615
|
+
# PEP 695 implemented, can pass infer_variance to typing.TypeVar
|
1616
|
+
paramspec = typing.ParamSpec(name, bound=bound,
|
1617
|
+
covariant=covariant,
|
1618
|
+
contravariant=contravariant,
|
1619
|
+
infer_variance=infer_variance)
|
1620
|
+
else:
|
1621
|
+
paramspec = typing.ParamSpec(name, bound=bound,
|
1622
|
+
covariant=covariant,
|
1623
|
+
contravariant=contravariant)
|
1624
|
+
paramspec.__infer_variance__ = infer_variance
|
1625
|
+
|
1626
|
+
_set_default(paramspec, default)
|
1627
|
+
_set_module(paramspec)
|
1628
|
+
return paramspec
|
1629
|
+
|
1630
|
+
def __init_subclass__(cls) -> None:
|
1631
|
+
raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
|
1632
|
+
|
1633
|
+
# 3.7-3.9
|
1634
|
+
else:
|
1635
|
+
|
1636
|
+
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
|
1637
|
+
class ParamSpec(list, _DefaultMixin):
|
1638
|
+
"""Parameter specification variable.
|
1639
|
+
|
1640
|
+
Usage::
|
1641
|
+
|
1642
|
+
P = ParamSpec('P')
|
1643
|
+
|
1644
|
+
Parameter specification variables exist primarily for the benefit of static
|
1645
|
+
type checkers. They are used to forward the parameter types of one
|
1646
|
+
callable to another callable, a pattern commonly found in higher order
|
1647
|
+
functions and decorators. They are only valid when used in ``Concatenate``,
|
1648
|
+
or s the first argument to ``Callable``. In Python 3.10 and higher,
|
1649
|
+
they are also supported in user-defined Generics at runtime.
|
1650
|
+
See class Generic for more information on generic types. An
|
1651
|
+
example for annotating a decorator::
|
1652
|
+
|
1653
|
+
T = TypeVar('T')
|
1654
|
+
P = ParamSpec('P')
|
1655
|
+
|
1656
|
+
def add_logging(f: Callable[P, T]) -> Callable[P, T]:
|
1657
|
+
'''A type-safe decorator to add logging to a function.'''
|
1658
|
+
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
|
1659
|
+
logging.info(f'{f.__name__} was called')
|
1660
|
+
return f(*args, **kwargs)
|
1661
|
+
return inner
|
1662
|
+
|
1663
|
+
@add_logging
|
1664
|
+
def add_two(x: float, y: float) -> float:
|
1665
|
+
'''Add two numbers together.'''
|
1666
|
+
return x + y
|
1667
|
+
|
1668
|
+
Parameter specification variables defined with covariant=True or
|
1669
|
+
contravariant=True can be used to declare covariant or contravariant
|
1670
|
+
generic types. These keyword arguments are valid, but their actual semantics
|
1671
|
+
are yet to be decided. See PEP 612 for details.
|
1672
|
+
|
1673
|
+
Parameter specification variables can be introspected. e.g.:
|
1674
|
+
|
1675
|
+
P.__name__ == 'T'
|
1676
|
+
P.__bound__ == None
|
1677
|
+
P.__covariant__ == False
|
1678
|
+
P.__contravariant__ == False
|
1679
|
+
|
1680
|
+
Note that only parameter specification variables defined in global scope can
|
1681
|
+
be pickled.
|
1682
|
+
"""
|
1683
|
+
|
1684
|
+
# Trick Generic __parameters__.
|
1685
|
+
__class__ = typing.TypeVar
|
1686
|
+
|
1687
|
+
@property
|
1688
|
+
def args(self):
|
1689
|
+
return ParamSpecArgs(self)
|
1690
|
+
|
1691
|
+
@property
|
1692
|
+
def kwargs(self):
|
1693
|
+
return ParamSpecKwargs(self)
|
1694
|
+
|
1695
|
+
def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
|
1696
|
+
infer_variance=False, default=_marker):
|
1697
|
+
super().__init__([self])
|
1698
|
+
self.__name__ = name
|
1699
|
+
self.__covariant__ = bool(covariant)
|
1700
|
+
self.__contravariant__ = bool(contravariant)
|
1701
|
+
self.__infer_variance__ = bool(infer_variance)
|
1702
|
+
if bound:
|
1703
|
+
self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
|
1704
|
+
else:
|
1705
|
+
self.__bound__ = None
|
1706
|
+
_DefaultMixin.__init__(self, default)
|
1707
|
+
|
1708
|
+
# for pickling:
|
1709
|
+
def_mod = _caller()
|
1710
|
+
if def_mod != 'typing_extensions':
|
1711
|
+
self.__module__ = def_mod
|
1712
|
+
|
1713
|
+
def __repr__(self):
|
1714
|
+
if self.__infer_variance__:
|
1715
|
+
prefix = ''
|
1716
|
+
elif self.__covariant__:
|
1717
|
+
prefix = '+'
|
1718
|
+
elif self.__contravariant__:
|
1719
|
+
prefix = '-'
|
1720
|
+
else:
|
1721
|
+
prefix = '~'
|
1722
|
+
return prefix + self.__name__
|
1723
|
+
|
1724
|
+
def __hash__(self):
|
1725
|
+
return object.__hash__(self)
|
1726
|
+
|
1727
|
+
def __eq__(self, other):
|
1728
|
+
return self is other
|
1729
|
+
|
1730
|
+
def __reduce__(self):
|
1731
|
+
return self.__name__
|
1732
|
+
|
1733
|
+
# Hack to get typing._type_check to pass.
|
1734
|
+
def __call__(self, *args, **kwargs):
|
1735
|
+
pass
|
1736
|
+
|
1737
|
+
|
1738
|
+
# 3.7-3.9
|
1739
|
+
if not hasattr(typing, 'Concatenate'):
|
1740
|
+
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
|
1741
|
+
class _ConcatenateGenericAlias(list):
|
1742
|
+
|
1743
|
+
# Trick Generic into looking into this for __parameters__.
|
1744
|
+
__class__ = typing._GenericAlias
|
1745
|
+
|
1746
|
+
# Flag in 3.8.
|
1747
|
+
_special = False
|
1748
|
+
|
1749
|
+
def __init__(self, origin, args):
|
1750
|
+
super().__init__(args)
|
1751
|
+
self.__origin__ = origin
|
1752
|
+
self.__args__ = args
|
1753
|
+
|
1754
|
+
def __repr__(self):
|
1755
|
+
_type_repr = typing._type_repr
|
1756
|
+
return (f'{_type_repr(self.__origin__)}'
|
1757
|
+
f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
|
1758
|
+
|
1759
|
+
def __hash__(self):
|
1760
|
+
return hash((self.__origin__, self.__args__))
|
1761
|
+
|
1762
|
+
# Hack to get typing._type_check to pass in Generic.
|
1763
|
+
def __call__(self, *args, **kwargs):
|
1764
|
+
pass
|
1765
|
+
|
1766
|
+
@property
|
1767
|
+
def __parameters__(self):
|
1768
|
+
return tuple(
|
1769
|
+
tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
|
1770
|
+
)
|
1771
|
+
|
1772
|
+
|
1773
|
+
# 3.7-3.9
|
1774
|
+
@typing._tp_cache
|
1775
|
+
def _concatenate_getitem(self, parameters):
|
1776
|
+
if parameters == ():
|
1777
|
+
raise TypeError("Cannot take a Concatenate of no types.")
|
1778
|
+
if not isinstance(parameters, tuple):
|
1779
|
+
parameters = (parameters,)
|
1780
|
+
if not isinstance(parameters[-1], ParamSpec):
|
1781
|
+
raise TypeError("The last parameter to Concatenate should be a "
|
1782
|
+
"ParamSpec variable.")
|
1783
|
+
msg = "Concatenate[arg, ...]: each arg must be a type."
|
1784
|
+
parameters = tuple(typing._type_check(p, msg) for p in parameters)
|
1785
|
+
return _ConcatenateGenericAlias(self, parameters)
|
1786
|
+
|
1787
|
+
|
1788
|
+
# 3.10+
|
1789
|
+
if hasattr(typing, 'Concatenate'):
|
1790
|
+
Concatenate = typing.Concatenate
|
1791
|
+
_ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811
|
1792
|
+
# 3.9
|
1793
|
+
elif sys.version_info[:2] >= (3, 9):
|
1794
|
+
@_ExtensionsSpecialForm
|
1795
|
+
def Concatenate(self, parameters):
|
1796
|
+
"""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
|
1797
|
+
higher order function which adds, removes or transforms parameters of a
|
1798
|
+
callable.
|
1799
|
+
|
1800
|
+
For example::
|
1801
|
+
|
1802
|
+
Callable[Concatenate[int, P], int]
|
1803
|
+
|
1804
|
+
See PEP 612 for detailed information.
|
1805
|
+
"""
|
1806
|
+
return _concatenate_getitem(self, parameters)
|
1807
|
+
# 3.7-8
|
1808
|
+
else:
|
1809
|
+
class _ConcatenateForm(_ExtensionsSpecialForm, _root=True):
|
1810
|
+
def __getitem__(self, parameters):
|
1811
|
+
return _concatenate_getitem(self, parameters)
|
1812
|
+
|
1813
|
+
Concatenate = _ConcatenateForm(
|
1814
|
+
'Concatenate',
|
1815
|
+
doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
|
1816
|
+
higher order function which adds, removes or transforms parameters of a
|
1817
|
+
callable.
|
1818
|
+
|
1819
|
+
For example::
|
1820
|
+
|
1821
|
+
Callable[Concatenate[int, P], int]
|
1822
|
+
|
1823
|
+
See PEP 612 for detailed information.
|
1824
|
+
""")
|
1825
|
+
|
1826
|
+
# 3.10+
|
1827
|
+
if hasattr(typing, 'TypeGuard'):
|
1828
|
+
TypeGuard = typing.TypeGuard
|
1829
|
+
# 3.9
|
1830
|
+
elif sys.version_info[:2] >= (3, 9):
|
1831
|
+
@_ExtensionsSpecialForm
|
1832
|
+
def TypeGuard(self, parameters):
|
1833
|
+
"""Special typing form used to annotate the return type of a user-defined
|
1834
|
+
type guard function. ``TypeGuard`` only accepts a single type argument.
|
1835
|
+
At runtime, functions marked this way should return a boolean.
|
1836
|
+
|
1837
|
+
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
|
1838
|
+
type checkers to determine a more precise type of an expression within a
|
1839
|
+
program's code flow. Usually type narrowing is done by analyzing
|
1840
|
+
conditional code flow and applying the narrowing to a block of code. The
|
1841
|
+
conditional expression here is sometimes referred to as a "type guard".
|
1842
|
+
|
1843
|
+
Sometimes it would be convenient to use a user-defined boolean function
|
1844
|
+
as a type guard. Such a function should use ``TypeGuard[...]`` as its
|
1845
|
+
return type to alert static type checkers to this intention.
|
1846
|
+
|
1847
|
+
Using ``-> TypeGuard`` tells the static type checker that for a given
|
1848
|
+
function:
|
1849
|
+
|
1850
|
+
1. The return value is a boolean.
|
1851
|
+
2. If the return value is ``True``, the type of its argument
|
1852
|
+
is the type inside ``TypeGuard``.
|
1853
|
+
|
1854
|
+
For example::
|
1855
|
+
|
1856
|
+
def is_str(val: Union[str, float]):
|
1857
|
+
# "isinstance" type guard
|
1858
|
+
if isinstance(val, str):
|
1859
|
+
# Type of ``val`` is narrowed to ``str``
|
1860
|
+
...
|
1861
|
+
else:
|
1862
|
+
# Else, type of ``val`` is narrowed to ``float``.
|
1863
|
+
...
|
1864
|
+
|
1865
|
+
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
|
1866
|
+
form of ``TypeA`` (it can even be a wider form) and this may lead to
|
1867
|
+
type-unsafe results. The main reason is to allow for things like
|
1868
|
+
narrowing ``List[object]`` to ``List[str]`` even though the latter is not
|
1869
|
+
a subtype of the former, since ``List`` is invariant. The responsibility of
|
1870
|
+
writing type-safe type guards is left to the user.
|
1871
|
+
|
1872
|
+
``TypeGuard`` also works with type variables. For more information, see
|
1873
|
+
PEP 647 (User-Defined Type Guards).
|
1874
|
+
"""
|
1875
|
+
item = typing._type_check(parameters, f'{self} accepts only a single type.')
|
1876
|
+
return typing._GenericAlias(self, (item,))
|
1877
|
+
# 3.7-3.8
|
1878
|
+
else:
|
1879
|
+
class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
|
1880
|
+
def __getitem__(self, parameters):
|
1881
|
+
item = typing._type_check(parameters,
|
1882
|
+
f'{self._name} accepts only a single type')
|
1883
|
+
return typing._GenericAlias(self, (item,))
|
1884
|
+
|
1885
|
+
TypeGuard = _TypeGuardForm(
|
1886
|
+
'TypeGuard',
|
1887
|
+
doc="""Special typing form used to annotate the return type of a user-defined
|
1888
|
+
type guard function. ``TypeGuard`` only accepts a single type argument.
|
1889
|
+
At runtime, functions marked this way should return a boolean.
|
1890
|
+
|
1891
|
+
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
|
1892
|
+
type checkers to determine a more precise type of an expression within a
|
1893
|
+
program's code flow. Usually type narrowing is done by analyzing
|
1894
|
+
conditional code flow and applying the narrowing to a block of code. The
|
1895
|
+
conditional expression here is sometimes referred to as a "type guard".
|
1896
|
+
|
1897
|
+
Sometimes it would be convenient to use a user-defined boolean function
|
1898
|
+
as a type guard. Such a function should use ``TypeGuard[...]`` as its
|
1899
|
+
return type to alert static type checkers to this intention.
|
1900
|
+
|
1901
|
+
Using ``-> TypeGuard`` tells the static type checker that for a given
|
1902
|
+
function:
|
1903
|
+
|
1904
|
+
1. The return value is a boolean.
|
1905
|
+
2. If the return value is ``True``, the type of its argument
|
1906
|
+
is the type inside ``TypeGuard``.
|
1907
|
+
|
1908
|
+
For example::
|
1909
|
+
|
1910
|
+
def is_str(val: Union[str, float]):
|
1911
|
+
# "isinstance" type guard
|
1912
|
+
if isinstance(val, str):
|
1913
|
+
# Type of ``val`` is narrowed to ``str``
|
1914
|
+
...
|
1915
|
+
else:
|
1916
|
+
# Else, type of ``val`` is narrowed to ``float``.
|
1917
|
+
...
|
1918
|
+
|
1919
|
+
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
|
1920
|
+
form of ``TypeA`` (it can even be a wider form) and this may lead to
|
1921
|
+
type-unsafe results. The main reason is to allow for things like
|
1922
|
+
narrowing ``List[object]`` to ``List[str]`` even though the latter is not
|
1923
|
+
a subtype of the former, since ``List`` is invariant. The responsibility of
|
1924
|
+
writing type-safe type guards is left to the user.
|
1925
|
+
|
1926
|
+
``TypeGuard`` also works with type variables. For more information, see
|
1927
|
+
PEP 647 (User-Defined Type Guards).
|
1928
|
+
""")
|
1929
|
+
|
1930
|
+
|
1931
|
+
# Vendored from cpython typing._SpecialFrom
|
1932
|
+
class _SpecialForm(typing._Final, _root=True):
|
1933
|
+
__slots__ = ('_name', '__doc__', '_getitem')
|
1934
|
+
|
1935
|
+
def __init__(self, getitem):
|
1936
|
+
self._getitem = getitem
|
1937
|
+
self._name = getitem.__name__
|
1938
|
+
self.__doc__ = getitem.__doc__
|
1939
|
+
|
1940
|
+
def __getattr__(self, item):
|
1941
|
+
if item in {'__name__', '__qualname__'}:
|
1942
|
+
return self._name
|
1943
|
+
|
1944
|
+
raise AttributeError(item)
|
1945
|
+
|
1946
|
+
def __mro_entries__(self, bases):
|
1947
|
+
raise TypeError(f"Cannot subclass {self!r}")
|
1948
|
+
|
1949
|
+
def __repr__(self):
|
1950
|
+
return f'typing_extensions.{self._name}'
|
1951
|
+
|
1952
|
+
def __reduce__(self):
|
1953
|
+
return self._name
|
1954
|
+
|
1955
|
+
def __call__(self, *args, **kwds):
|
1956
|
+
raise TypeError(f"Cannot instantiate {self!r}")
|
1957
|
+
|
1958
|
+
def __or__(self, other):
|
1959
|
+
return typing.Union[self, other]
|
1960
|
+
|
1961
|
+
def __ror__(self, other):
|
1962
|
+
return typing.Union[other, self]
|
1963
|
+
|
1964
|
+
def __instancecheck__(self, obj):
|
1965
|
+
raise TypeError(f"{self} cannot be used with isinstance()")
|
1966
|
+
|
1967
|
+
def __subclasscheck__(self, cls):
|
1968
|
+
raise TypeError(f"{self} cannot be used with issubclass()")
|
1969
|
+
|
1970
|
+
@typing._tp_cache
|
1971
|
+
def __getitem__(self, parameters):
|
1972
|
+
return self._getitem(self, parameters)
|
1973
|
+
|
1974
|
+
|
1975
|
+
if hasattr(typing, "LiteralString"):
|
1976
|
+
LiteralString = typing.LiteralString
|
1977
|
+
else:
|
1978
|
+
@_SpecialForm
|
1979
|
+
def LiteralString(self, params):
|
1980
|
+
"""Represents an arbitrary literal string.
|
1981
|
+
|
1982
|
+
Example::
|
1983
|
+
|
1984
|
+
from metaflow._vendor.v3_7.typing_extensions import LiteralString
|
1985
|
+
|
1986
|
+
def query(sql: LiteralString) -> ...:
|
1987
|
+
...
|
1988
|
+
|
1989
|
+
query("SELECT * FROM table") # ok
|
1990
|
+
query(f"SELECT * FROM {input()}") # not ok
|
1991
|
+
|
1992
|
+
See PEP 675 for details.
|
1993
|
+
|
1994
|
+
"""
|
1995
|
+
raise TypeError(f"{self} is not subscriptable")
|
1996
|
+
|
1997
|
+
|
1998
|
+
if hasattr(typing, "Self"):
|
1999
|
+
Self = typing.Self
|
2000
|
+
else:
|
2001
|
+
@_SpecialForm
|
2002
|
+
def Self(self, params):
|
2003
|
+
"""Used to spell the type of "self" in classes.
|
2004
|
+
|
2005
|
+
Example::
|
2006
|
+
|
2007
|
+
from typing import Self
|
2008
|
+
|
2009
|
+
class ReturnsSelf:
|
2010
|
+
def parse(self, data: bytes) -> Self:
|
2011
|
+
...
|
2012
|
+
return self
|
2013
|
+
|
2014
|
+
"""
|
2015
|
+
|
2016
|
+
raise TypeError(f"{self} is not subscriptable")
|
2017
|
+
|
2018
|
+
|
2019
|
+
if hasattr(typing, "Never"):
|
2020
|
+
Never = typing.Never
|
2021
|
+
else:
|
2022
|
+
@_SpecialForm
|
2023
|
+
def Never(self, params):
|
2024
|
+
"""The bottom type, a type that has no members.
|
2025
|
+
|
2026
|
+
This can be used to define a function that should never be
|
2027
|
+
called, or a function that never returns::
|
2028
|
+
|
2029
|
+
from metaflow._vendor.v3_7.typing_extensions import Never
|
2030
|
+
|
2031
|
+
def never_call_me(arg: Never) -> None:
|
2032
|
+
pass
|
2033
|
+
|
2034
|
+
def int_or_str(arg: int | str) -> None:
|
2035
|
+
never_call_me(arg) # type checker error
|
2036
|
+
match arg:
|
2037
|
+
case int():
|
2038
|
+
print("It's an int")
|
2039
|
+
case str():
|
2040
|
+
print("It's a str")
|
2041
|
+
case _:
|
2042
|
+
never_call_me(arg) # ok, arg is of type Never
|
2043
|
+
|
2044
|
+
"""
|
2045
|
+
|
2046
|
+
raise TypeError(f"{self} is not subscriptable")
|
2047
|
+
|
2048
|
+
|
2049
|
+
if hasattr(typing, 'Required'):
|
2050
|
+
Required = typing.Required
|
2051
|
+
NotRequired = typing.NotRequired
|
2052
|
+
elif sys.version_info[:2] >= (3, 9):
|
2053
|
+
@_ExtensionsSpecialForm
|
2054
|
+
def Required(self, parameters):
|
2055
|
+
"""A special typing construct to mark a key of a total=False TypedDict
|
2056
|
+
as required. For example:
|
2057
|
+
|
2058
|
+
class Movie(TypedDict, total=False):
|
2059
|
+
title: Required[str]
|
2060
|
+
year: int
|
2061
|
+
|
2062
|
+
m = Movie(
|
2063
|
+
title='The Matrix', # typechecker error if key is omitted
|
2064
|
+
year=1999,
|
2065
|
+
)
|
2066
|
+
|
2067
|
+
There is no runtime checking that a required key is actually provided
|
2068
|
+
when instantiating a related TypedDict.
|
2069
|
+
"""
|
2070
|
+
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
|
2071
|
+
return typing._GenericAlias(self, (item,))
|
2072
|
+
|
2073
|
+
@_ExtensionsSpecialForm
|
2074
|
+
def NotRequired(self, parameters):
|
2075
|
+
"""A special typing construct to mark a key of a TypedDict as
|
2076
|
+
potentially missing. For example:
|
2077
|
+
|
2078
|
+
class Movie(TypedDict):
|
2079
|
+
title: str
|
2080
|
+
year: NotRequired[int]
|
2081
|
+
|
2082
|
+
m = Movie(
|
2083
|
+
title='The Matrix', # typechecker error if key is omitted
|
2084
|
+
year=1999,
|
2085
|
+
)
|
2086
|
+
"""
|
2087
|
+
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
|
2088
|
+
return typing._GenericAlias(self, (item,))
|
2089
|
+
|
2090
|
+
else:
|
2091
|
+
class _RequiredForm(_ExtensionsSpecialForm, _root=True):
|
2092
|
+
def __getitem__(self, parameters):
|
2093
|
+
item = typing._type_check(parameters,
|
2094
|
+
f'{self._name} accepts only a single type.')
|
2095
|
+
return typing._GenericAlias(self, (item,))
|
2096
|
+
|
2097
|
+
Required = _RequiredForm(
|
2098
|
+
'Required',
|
2099
|
+
doc="""A special typing construct to mark a key of a total=False TypedDict
|
2100
|
+
as required. For example:
|
2101
|
+
|
2102
|
+
class Movie(TypedDict, total=False):
|
2103
|
+
title: Required[str]
|
2104
|
+
year: int
|
2105
|
+
|
2106
|
+
m = Movie(
|
2107
|
+
title='The Matrix', # typechecker error if key is omitted
|
2108
|
+
year=1999,
|
2109
|
+
)
|
2110
|
+
|
2111
|
+
There is no runtime checking that a required key is actually provided
|
2112
|
+
when instantiating a related TypedDict.
|
2113
|
+
""")
|
2114
|
+
NotRequired = _RequiredForm(
|
2115
|
+
'NotRequired',
|
2116
|
+
doc="""A special typing construct to mark a key of a TypedDict as
|
2117
|
+
potentially missing. For example:
|
2118
|
+
|
2119
|
+
class Movie(TypedDict):
|
2120
|
+
title: str
|
2121
|
+
year: NotRequired[int]
|
2122
|
+
|
2123
|
+
m = Movie(
|
2124
|
+
title='The Matrix', # typechecker error if key is omitted
|
2125
|
+
year=1999,
|
2126
|
+
)
|
2127
|
+
""")
|
2128
|
+
|
2129
|
+
|
2130
|
+
_UNPACK_DOC = """\
|
2131
|
+
Type unpack operator.
|
2132
|
+
|
2133
|
+
The type unpack operator takes the child types from some container type,
|
2134
|
+
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
|
2135
|
+
example:
|
2136
|
+
|
2137
|
+
# For some generic class `Foo`:
|
2138
|
+
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
|
2139
|
+
|
2140
|
+
Ts = TypeVarTuple('Ts')
|
2141
|
+
# Specifies that `Bar` is generic in an arbitrary number of types.
|
2142
|
+
# (Think of `Ts` as a tuple of an arbitrary number of individual
|
2143
|
+
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
|
2144
|
+
# `Generic[]`.)
|
2145
|
+
class Bar(Generic[Unpack[Ts]]): ...
|
2146
|
+
Bar[int] # Valid
|
2147
|
+
Bar[int, str] # Also valid
|
2148
|
+
|
2149
|
+
From Python 3.11, this can also be done using the `*` operator:
|
2150
|
+
|
2151
|
+
Foo[*tuple[int, str]]
|
2152
|
+
class Bar(Generic[*Ts]): ...
|
2153
|
+
|
2154
|
+
The operator can also be used along with a `TypedDict` to annotate
|
2155
|
+
`**kwargs` in a function signature. For instance:
|
2156
|
+
|
2157
|
+
class Movie(TypedDict):
|
2158
|
+
name: str
|
2159
|
+
year: int
|
2160
|
+
|
2161
|
+
# This function expects two keyword arguments - *name* of type `str` and
|
2162
|
+
# *year* of type `int`.
|
2163
|
+
def foo(**kwargs: Unpack[Movie]): ...
|
2164
|
+
|
2165
|
+
Note that there is only some runtime checking of this operator. Not
|
2166
|
+
everything the runtime allows may be accepted by static type checkers.
|
2167
|
+
|
2168
|
+
For more information, see PEP 646 and PEP 692.
|
2169
|
+
"""
|
2170
|
+
|
2171
|
+
|
2172
|
+
if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
|
2173
|
+
Unpack = typing.Unpack
|
2174
|
+
|
2175
|
+
def _is_unpack(obj):
|
2176
|
+
return get_origin(obj) is Unpack
|
2177
|
+
|
2178
|
+
elif sys.version_info[:2] >= (3, 9):
|
2179
|
+
class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
|
2180
|
+
def __init__(self, getitem):
|
2181
|
+
super().__init__(getitem)
|
2182
|
+
self.__doc__ = _UNPACK_DOC
|
2183
|
+
|
2184
|
+
class _UnpackAlias(typing._GenericAlias, _root=True):
|
2185
|
+
__class__ = typing.TypeVar
|
2186
|
+
|
2187
|
+
@_UnpackSpecialForm
|
2188
|
+
def Unpack(self, parameters):
|
2189
|
+
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
|
2190
|
+
return _UnpackAlias(self, (item,))
|
2191
|
+
|
2192
|
+
def _is_unpack(obj):
|
2193
|
+
return isinstance(obj, _UnpackAlias)
|
2194
|
+
|
2195
|
+
else:
|
2196
|
+
class _UnpackAlias(typing._GenericAlias, _root=True):
|
2197
|
+
__class__ = typing.TypeVar
|
2198
|
+
|
2199
|
+
class _UnpackForm(_ExtensionsSpecialForm, _root=True):
|
2200
|
+
def __getitem__(self, parameters):
|
2201
|
+
item = typing._type_check(parameters,
|
2202
|
+
f'{self._name} accepts only a single type.')
|
2203
|
+
return _UnpackAlias(self, (item,))
|
2204
|
+
|
2205
|
+
Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
|
2206
|
+
|
2207
|
+
def _is_unpack(obj):
|
2208
|
+
return isinstance(obj, _UnpackAlias)
|
2209
|
+
|
2210
|
+
|
2211
|
+
if hasattr(typing, "TypeVarTuple"): # 3.11+
|
2212
|
+
|
2213
|
+
# Add default parameter - PEP 696
|
2214
|
+
class TypeVarTuple(metaclass=_TypeVarLikeMeta):
|
2215
|
+
"""Type variable tuple."""
|
2216
|
+
|
2217
|
+
_backported_typevarlike = typing.TypeVarTuple
|
2218
|
+
|
2219
|
+
def __new__(cls, name, *, default=_marker):
|
2220
|
+
tvt = typing.TypeVarTuple(name)
|
2221
|
+
_set_default(tvt, default)
|
2222
|
+
_set_module(tvt)
|
2223
|
+
return tvt
|
2224
|
+
|
2225
|
+
def __init_subclass__(self, *args, **kwds):
|
2226
|
+
raise TypeError("Cannot subclass special typing classes")
|
2227
|
+
|
2228
|
+
else:
|
2229
|
+
class TypeVarTuple(_DefaultMixin):
|
2230
|
+
"""Type variable tuple.
|
2231
|
+
|
2232
|
+
Usage::
|
2233
|
+
|
2234
|
+
Ts = TypeVarTuple('Ts')
|
2235
|
+
|
2236
|
+
In the same way that a normal type variable is a stand-in for a single
|
2237
|
+
type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
|
2238
|
+
type such as ``Tuple[int, str]``.
|
2239
|
+
|
2240
|
+
Type variable tuples can be used in ``Generic`` declarations.
|
2241
|
+
Consider the following example::
|
2242
|
+
|
2243
|
+
class Array(Generic[*Ts]): ...
|
2244
|
+
|
2245
|
+
The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
|
2246
|
+
where ``T1`` and ``T2`` are type variables. To use these type variables
|
2247
|
+
as type parameters of ``Array``, we must *unpack* the type variable tuple using
|
2248
|
+
the star operator: ``*Ts``. The signature of ``Array`` then behaves
|
2249
|
+
as if we had simply written ``class Array(Generic[T1, T2]): ...``.
|
2250
|
+
In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
|
2251
|
+
us to parameterise the class with an *arbitrary* number of type parameters.
|
2252
|
+
|
2253
|
+
Type variable tuples can be used anywhere a normal ``TypeVar`` can.
|
2254
|
+
This includes class definitions, as shown above, as well as function
|
2255
|
+
signatures and variable annotations::
|
2256
|
+
|
2257
|
+
class Array(Generic[*Ts]):
|
2258
|
+
|
2259
|
+
def __init__(self, shape: Tuple[*Ts]):
|
2260
|
+
self._shape: Tuple[*Ts] = shape
|
2261
|
+
|
2262
|
+
def get_shape(self) -> Tuple[*Ts]:
|
2263
|
+
return self._shape
|
2264
|
+
|
2265
|
+
shape = (Height(480), Width(640))
|
2266
|
+
x: Array[Height, Width] = Array(shape)
|
2267
|
+
y = abs(x) # Inferred type is Array[Height, Width]
|
2268
|
+
z = x + x # ... is Array[Height, Width]
|
2269
|
+
x.get_shape() # ... is tuple[Height, Width]
|
2270
|
+
|
2271
|
+
"""
|
2272
|
+
|
2273
|
+
# Trick Generic __parameters__.
|
2274
|
+
__class__ = typing.TypeVar
|
2275
|
+
|
2276
|
+
def __iter__(self):
|
2277
|
+
yield self.__unpacked__
|
2278
|
+
|
2279
|
+
def __init__(self, name, *, default=_marker):
|
2280
|
+
self.__name__ = name
|
2281
|
+
_DefaultMixin.__init__(self, default)
|
2282
|
+
|
2283
|
+
# for pickling:
|
2284
|
+
def_mod = _caller()
|
2285
|
+
if def_mod != 'typing_extensions':
|
2286
|
+
self.__module__ = def_mod
|
2287
|
+
|
2288
|
+
self.__unpacked__ = Unpack[self]
|
2289
|
+
|
2290
|
+
def __repr__(self):
|
2291
|
+
return self.__name__
|
2292
|
+
|
2293
|
+
def __hash__(self):
|
2294
|
+
return object.__hash__(self)
|
2295
|
+
|
2296
|
+
def __eq__(self, other):
|
2297
|
+
return self is other
|
2298
|
+
|
2299
|
+
def __reduce__(self):
|
2300
|
+
return self.__name__
|
2301
|
+
|
2302
|
+
def __init_subclass__(self, *args, **kwds):
|
2303
|
+
if '_root' not in kwds:
|
2304
|
+
raise TypeError("Cannot subclass special typing classes")
|
2305
|
+
|
2306
|
+
|
2307
|
+
if hasattr(typing, "reveal_type"):
|
2308
|
+
reveal_type = typing.reveal_type
|
2309
|
+
else:
|
2310
|
+
def reveal_type(__obj: T) -> T:
|
2311
|
+
"""Reveal the inferred type of a variable.
|
2312
|
+
|
2313
|
+
When a static type checker encounters a call to ``reveal_type()``,
|
2314
|
+
it will emit the inferred type of the argument::
|
2315
|
+
|
2316
|
+
x: int = 1
|
2317
|
+
reveal_type(x)
|
2318
|
+
|
2319
|
+
Running a static type checker (e.g., ``mypy``) on this example
|
2320
|
+
will produce output similar to 'Revealed type is "builtins.int"'.
|
2321
|
+
|
2322
|
+
At runtime, the function prints the runtime type of the
|
2323
|
+
argument and returns it unchanged.
|
2324
|
+
|
2325
|
+
"""
|
2326
|
+
print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr)
|
2327
|
+
return __obj
|
2328
|
+
|
2329
|
+
|
2330
|
+
if hasattr(typing, "assert_never"):
|
2331
|
+
assert_never = typing.assert_never
|
2332
|
+
else:
|
2333
|
+
def assert_never(__arg: Never) -> Never:
|
2334
|
+
"""Assert to the type checker that a line of code is unreachable.
|
2335
|
+
|
2336
|
+
Example::
|
2337
|
+
|
2338
|
+
def int_or_str(arg: int | str) -> None:
|
2339
|
+
match arg:
|
2340
|
+
case int():
|
2341
|
+
print("It's an int")
|
2342
|
+
case str():
|
2343
|
+
print("It's a str")
|
2344
|
+
case _:
|
2345
|
+
assert_never(arg)
|
2346
|
+
|
2347
|
+
If a type checker finds that a call to assert_never() is
|
2348
|
+
reachable, it will emit an error.
|
2349
|
+
|
2350
|
+
At runtime, this throws an exception when called.
|
2351
|
+
|
2352
|
+
"""
|
2353
|
+
raise AssertionError("Expected code to be unreachable")
|
2354
|
+
|
2355
|
+
|
2356
|
+
if sys.version_info >= (3, 12):
|
2357
|
+
# dataclass_transform exists in 3.11 but lacks the frozen_default parameter
|
2358
|
+
dataclass_transform = typing.dataclass_transform
|
2359
|
+
else:
|
2360
|
+
def dataclass_transform(
|
2361
|
+
*,
|
2362
|
+
eq_default: bool = True,
|
2363
|
+
order_default: bool = False,
|
2364
|
+
kw_only_default: bool = False,
|
2365
|
+
frozen_default: bool = False,
|
2366
|
+
field_specifiers: typing.Tuple[
|
2367
|
+
typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
|
2368
|
+
...
|
2369
|
+
] = (),
|
2370
|
+
**kwargs: typing.Any,
|
2371
|
+
) -> typing.Callable[[T], T]:
|
2372
|
+
"""Decorator that marks a function, class, or metaclass as providing
|
2373
|
+
dataclass-like behavior.
|
2374
|
+
|
2375
|
+
Example:
|
2376
|
+
|
2377
|
+
from metaflow._vendor.v3_7.typing_extensions import dataclass_transform
|
2378
|
+
|
2379
|
+
_T = TypeVar("_T")
|
2380
|
+
|
2381
|
+
# Used on a decorator function
|
2382
|
+
@dataclass_transform()
|
2383
|
+
def create_model(cls: type[_T]) -> type[_T]:
|
2384
|
+
...
|
2385
|
+
return cls
|
2386
|
+
|
2387
|
+
@create_model
|
2388
|
+
class CustomerModel:
|
2389
|
+
id: int
|
2390
|
+
name: str
|
2391
|
+
|
2392
|
+
# Used on a base class
|
2393
|
+
@dataclass_transform()
|
2394
|
+
class ModelBase: ...
|
2395
|
+
|
2396
|
+
class CustomerModel(ModelBase):
|
2397
|
+
id: int
|
2398
|
+
name: str
|
2399
|
+
|
2400
|
+
# Used on a metaclass
|
2401
|
+
@dataclass_transform()
|
2402
|
+
class ModelMeta(type): ...
|
2403
|
+
|
2404
|
+
class ModelBase(metaclass=ModelMeta): ...
|
2405
|
+
|
2406
|
+
class CustomerModel(ModelBase):
|
2407
|
+
id: int
|
2408
|
+
name: str
|
2409
|
+
|
2410
|
+
Each of the ``CustomerModel`` classes defined in this example will now
|
2411
|
+
behave similarly to a dataclass created with the ``@dataclasses.dataclass``
|
2412
|
+
decorator. For example, the type checker will synthesize an ``__init__``
|
2413
|
+
method.
|
2414
|
+
|
2415
|
+
The arguments to this decorator can be used to customize this behavior:
|
2416
|
+
- ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
|
2417
|
+
True or False if it is omitted by the caller.
|
2418
|
+
- ``order_default`` indicates whether the ``order`` parameter is
|
2419
|
+
assumed to be True or False if it is omitted by the caller.
|
2420
|
+
- ``kw_only_default`` indicates whether the ``kw_only`` parameter is
|
2421
|
+
assumed to be True or False if it is omitted by the caller.
|
2422
|
+
- ``frozen_default`` indicates whether the ``frozen`` parameter is
|
2423
|
+
assumed to be True or False if it is omitted by the caller.
|
2424
|
+
- ``field_specifiers`` specifies a static list of supported classes
|
2425
|
+
or functions that describe fields, similar to ``dataclasses.field()``.
|
2426
|
+
|
2427
|
+
At runtime, this decorator records its arguments in the
|
2428
|
+
``__dataclass_transform__`` attribute on the decorated object.
|
2429
|
+
|
2430
|
+
See PEP 681 for details.
|
2431
|
+
|
2432
|
+
"""
|
2433
|
+
def decorator(cls_or_fn):
|
2434
|
+
cls_or_fn.__dataclass_transform__ = {
|
2435
|
+
"eq_default": eq_default,
|
2436
|
+
"order_default": order_default,
|
2437
|
+
"kw_only_default": kw_only_default,
|
2438
|
+
"frozen_default": frozen_default,
|
2439
|
+
"field_specifiers": field_specifiers,
|
2440
|
+
"kwargs": kwargs,
|
2441
|
+
}
|
2442
|
+
return cls_or_fn
|
2443
|
+
return decorator
|
2444
|
+
|
2445
|
+
|
2446
|
+
if hasattr(typing, "override"):
|
2447
|
+
override = typing.override
|
2448
|
+
else:
|
2449
|
+
_F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
|
2450
|
+
|
2451
|
+
def override(__arg: _F) -> _F:
|
2452
|
+
"""Indicate that a method is intended to override a method in a base class.
|
2453
|
+
|
2454
|
+
Usage:
|
2455
|
+
|
2456
|
+
class Base:
|
2457
|
+
def method(self) -> None: ...
|
2458
|
+
pass
|
2459
|
+
|
2460
|
+
class Child(Base):
|
2461
|
+
@override
|
2462
|
+
def method(self) -> None:
|
2463
|
+
super().method()
|
2464
|
+
|
2465
|
+
When this decorator is applied to a method, the type checker will
|
2466
|
+
validate that it overrides a method with the same name on a base class.
|
2467
|
+
This helps prevent bugs that may occur when a base class is changed
|
2468
|
+
without an equivalent change to a child class.
|
2469
|
+
|
2470
|
+
There is no runtime checking of these properties. The decorator
|
2471
|
+
sets the ``__override__`` attribute to ``True`` on the decorated object
|
2472
|
+
to allow runtime introspection.
|
2473
|
+
|
2474
|
+
See PEP 698 for details.
|
2475
|
+
|
2476
|
+
"""
|
2477
|
+
try:
|
2478
|
+
__arg.__override__ = True
|
2479
|
+
except (AttributeError, TypeError):
|
2480
|
+
# Skip the attribute silently if it is not writable.
|
2481
|
+
# AttributeError happens if the object has __slots__ or a
|
2482
|
+
# read-only property, TypeError if it's a builtin class.
|
2483
|
+
pass
|
2484
|
+
return __arg
|
2485
|
+
|
2486
|
+
|
2487
|
+
if hasattr(typing, "deprecated"):
|
2488
|
+
deprecated = typing.deprecated
|
2489
|
+
else:
|
2490
|
+
_T = typing.TypeVar("_T")
|
2491
|
+
|
2492
|
+
def deprecated(
|
2493
|
+
__msg: str,
|
2494
|
+
*,
|
2495
|
+
category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
|
2496
|
+
stacklevel: int = 1,
|
2497
|
+
) -> typing.Callable[[_T], _T]:
|
2498
|
+
"""Indicate that a class, function or overload is deprecated.
|
2499
|
+
|
2500
|
+
Usage:
|
2501
|
+
|
2502
|
+
@deprecated("Use B instead")
|
2503
|
+
class A:
|
2504
|
+
pass
|
2505
|
+
|
2506
|
+
@deprecated("Use g instead")
|
2507
|
+
def f():
|
2508
|
+
pass
|
2509
|
+
|
2510
|
+
@overload
|
2511
|
+
@deprecated("int support is deprecated")
|
2512
|
+
def g(x: int) -> int: ...
|
2513
|
+
@overload
|
2514
|
+
def g(x: str) -> int: ...
|
2515
|
+
|
2516
|
+
When this decorator is applied to an object, the type checker
|
2517
|
+
will generate a diagnostic on usage of the deprecated object.
|
2518
|
+
|
2519
|
+
The warning specified by ``category`` will be emitted on use
|
2520
|
+
of deprecated objects. For functions, that happens on calls;
|
2521
|
+
for classes, on instantiation. If the ``category`` is ``None``,
|
2522
|
+
no warning is emitted. The ``stacklevel`` determines where the
|
2523
|
+
warning is emitted. If it is ``1`` (the default), the warning
|
2524
|
+
is emitted at the direct caller of the deprecated object; if it
|
2525
|
+
is higher, it is emitted further up the stack.
|
2526
|
+
|
2527
|
+
The decorator sets the ``__deprecated__``
|
2528
|
+
attribute on the decorated object to the deprecation message
|
2529
|
+
passed to the decorator. If applied to an overload, the decorator
|
2530
|
+
must be after the ``@overload`` decorator for the attribute to
|
2531
|
+
exist on the overload as returned by ``get_overloads()``.
|
2532
|
+
|
2533
|
+
See PEP 702 for details.
|
2534
|
+
|
2535
|
+
"""
|
2536
|
+
def decorator(__arg: _T) -> _T:
|
2537
|
+
if category is None:
|
2538
|
+
__arg.__deprecated__ = __msg
|
2539
|
+
return __arg
|
2540
|
+
elif isinstance(__arg, type):
|
2541
|
+
original_new = __arg.__new__
|
2542
|
+
has_init = __arg.__init__ is not object.__init__
|
2543
|
+
|
2544
|
+
@functools.wraps(original_new)
|
2545
|
+
def __new__(cls, *args, **kwargs):
|
2546
|
+
warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
|
2547
|
+
if original_new is not object.__new__:
|
2548
|
+
return original_new(cls, *args, **kwargs)
|
2549
|
+
# Mirrors a similar check in object.__new__.
|
2550
|
+
elif not has_init and (args or kwargs):
|
2551
|
+
raise TypeError(f"{cls.__name__}() takes no arguments")
|
2552
|
+
else:
|
2553
|
+
return original_new(cls)
|
2554
|
+
|
2555
|
+
__arg.__new__ = staticmethod(__new__)
|
2556
|
+
__arg.__deprecated__ = __new__.__deprecated__ = __msg
|
2557
|
+
return __arg
|
2558
|
+
elif callable(__arg):
|
2559
|
+
@functools.wraps(__arg)
|
2560
|
+
def wrapper(*args, **kwargs):
|
2561
|
+
warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
|
2562
|
+
return __arg(*args, **kwargs)
|
2563
|
+
|
2564
|
+
__arg.__deprecated__ = wrapper.__deprecated__ = __msg
|
2565
|
+
return wrapper
|
2566
|
+
else:
|
2567
|
+
raise TypeError(
|
2568
|
+
"@deprecated decorator with non-None category must be applied to "
|
2569
|
+
f"a class or callable, not {__arg!r}"
|
2570
|
+
)
|
2571
|
+
|
2572
|
+
return decorator
|
2573
|
+
|
2574
|
+
|
2575
|
+
# We have to do some monkey patching to deal with the dual nature of
|
2576
|
+
# Unpack/TypeVarTuple:
|
2577
|
+
# - We want Unpack to be a kind of TypeVar so it gets accepted in
|
2578
|
+
# Generic[Unpack[Ts]]
|
2579
|
+
# - We want it to *not* be treated as a TypeVar for the purposes of
|
2580
|
+
# counting generic parameters, so that when we subscript a generic,
|
2581
|
+
# the runtime doesn't try to substitute the Unpack with the subscripted type.
|
2582
|
+
if not hasattr(typing, "TypeVarTuple"):
|
2583
|
+
typing._collect_type_vars = _collect_type_vars
|
2584
|
+
typing._check_generic = _check_generic
|
2585
|
+
|
2586
|
+
|
2587
|
+
# Backport typing.NamedTuple as it exists in Python 3.12.
|
2588
|
+
# In 3.11, the ability to define generic `NamedTuple`s was supported.
|
2589
|
+
# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
|
2590
|
+
# On 3.12, we added __orig_bases__ to call-based NamedTuples
|
2591
|
+
# On 3.13, we deprecated kwargs-based NamedTuples
|
2592
|
+
if sys.version_info >= (3, 13):
|
2593
|
+
NamedTuple = typing.NamedTuple
|
2594
|
+
else:
|
2595
|
+
def _make_nmtuple(name, types, module, defaults=()):
|
2596
|
+
fields = [n for n, t in types]
|
2597
|
+
annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
|
2598
|
+
for n, t in types}
|
2599
|
+
nm_tpl = collections.namedtuple(name, fields,
|
2600
|
+
defaults=defaults, module=module)
|
2601
|
+
nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
|
2602
|
+
# The `_field_types` attribute was removed in 3.9;
|
2603
|
+
# in earlier versions, it is the same as the `__annotations__` attribute
|
2604
|
+
if sys.version_info < (3, 9):
|
2605
|
+
nm_tpl._field_types = annotations
|
2606
|
+
return nm_tpl
|
2607
|
+
|
2608
|
+
_prohibited_namedtuple_fields = typing._prohibited
|
2609
|
+
_special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
|
2610
|
+
|
2611
|
+
class _NamedTupleMeta(type):
|
2612
|
+
def __new__(cls, typename, bases, ns):
|
2613
|
+
assert _NamedTuple in bases
|
2614
|
+
for base in bases:
|
2615
|
+
if base is not _NamedTuple and base is not typing.Generic:
|
2616
|
+
raise TypeError(
|
2617
|
+
'can only inherit from a NamedTuple type and Generic')
|
2618
|
+
bases = tuple(tuple if base is _NamedTuple else base for base in bases)
|
2619
|
+
types = ns.get('__annotations__', {})
|
2620
|
+
default_names = []
|
2621
|
+
for field_name in types:
|
2622
|
+
if field_name in ns:
|
2623
|
+
default_names.append(field_name)
|
2624
|
+
elif default_names:
|
2625
|
+
raise TypeError(f"Non-default namedtuple field {field_name} "
|
2626
|
+
f"cannot follow default field"
|
2627
|
+
f"{'s' if len(default_names) > 1 else ''} "
|
2628
|
+
f"{', '.join(default_names)}")
|
2629
|
+
nm_tpl = _make_nmtuple(
|
2630
|
+
typename, types.items(),
|
2631
|
+
defaults=[ns[n] for n in default_names],
|
2632
|
+
module=ns['__module__']
|
2633
|
+
)
|
2634
|
+
nm_tpl.__bases__ = bases
|
2635
|
+
if typing.Generic in bases:
|
2636
|
+
if hasattr(typing, '_generic_class_getitem'): # 3.12+
|
2637
|
+
nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
|
2638
|
+
else:
|
2639
|
+
class_getitem = typing.Generic.__class_getitem__.__func__
|
2640
|
+
nm_tpl.__class_getitem__ = classmethod(class_getitem)
|
2641
|
+
# update from user namespace without overriding special namedtuple attributes
|
2642
|
+
for key in ns:
|
2643
|
+
if key in _prohibited_namedtuple_fields:
|
2644
|
+
raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
|
2645
|
+
elif key not in _special_namedtuple_fields and key not in nm_tpl._fields:
|
2646
|
+
setattr(nm_tpl, key, ns[key])
|
2647
|
+
if typing.Generic in bases:
|
2648
|
+
nm_tpl.__init_subclass__()
|
2649
|
+
return nm_tpl
|
2650
|
+
|
2651
|
+
_NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
|
2652
|
+
|
2653
|
+
def _namedtuple_mro_entries(bases):
|
2654
|
+
assert NamedTuple in bases
|
2655
|
+
return (_NamedTuple,)
|
2656
|
+
|
2657
|
+
@_ensure_subclassable(_namedtuple_mro_entries)
|
2658
|
+
def NamedTuple(__typename, __fields=_marker, **kwargs):
|
2659
|
+
"""Typed version of namedtuple.
|
2660
|
+
|
2661
|
+
Usage::
|
2662
|
+
|
2663
|
+
class Employee(NamedTuple):
|
2664
|
+
name: str
|
2665
|
+
id: int
|
2666
|
+
|
2667
|
+
This is equivalent to::
|
2668
|
+
|
2669
|
+
Employee = collections.namedtuple('Employee', ['name', 'id'])
|
2670
|
+
|
2671
|
+
The resulting class has an extra __annotations__ attribute, giving a
|
2672
|
+
dict that maps field names to types. (The field names are also in
|
2673
|
+
the _fields attribute, which is part of the namedtuple API.)
|
2674
|
+
An alternative equivalent functional syntax is also accepted::
|
2675
|
+
|
2676
|
+
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
|
2677
|
+
"""
|
2678
|
+
if __fields is _marker:
|
2679
|
+
if kwargs:
|
2680
|
+
deprecated_thing = "Creating NamedTuple classes using keyword arguments"
|
2681
|
+
deprecation_msg = (
|
2682
|
+
"{name} is deprecated and will be disallowed in Python {remove}. "
|
2683
|
+
"Use the class-based or functional syntax instead."
|
2684
|
+
)
|
2685
|
+
else:
|
2686
|
+
deprecated_thing = "Failing to pass a value for the 'fields' parameter"
|
2687
|
+
example = f"`{__typename} = NamedTuple({__typename!r}, [])`"
|
2688
|
+
deprecation_msg = (
|
2689
|
+
"{name} is deprecated and will be disallowed in Python {remove}. "
|
2690
|
+
"To create a NamedTuple class with 0 fields "
|
2691
|
+
"using the functional syntax, "
|
2692
|
+
"pass an empty list, e.g. "
|
2693
|
+
) + example + "."
|
2694
|
+
elif __fields is None:
|
2695
|
+
if kwargs:
|
2696
|
+
raise TypeError(
|
2697
|
+
"Cannot pass `None` as the 'fields' parameter "
|
2698
|
+
"and also specify fields using keyword arguments"
|
2699
|
+
)
|
2700
|
+
else:
|
2701
|
+
deprecated_thing = "Passing `None` as the 'fields' parameter"
|
2702
|
+
example = f"`{__typename} = NamedTuple({__typename!r}, [])`"
|
2703
|
+
deprecation_msg = (
|
2704
|
+
"{name} is deprecated and will be disallowed in Python {remove}. "
|
2705
|
+
"To create a NamedTuple class with 0 fields "
|
2706
|
+
"using the functional syntax, "
|
2707
|
+
"pass an empty list, e.g. "
|
2708
|
+
) + example + "."
|
2709
|
+
elif kwargs:
|
2710
|
+
raise TypeError("Either list of fields or keywords"
|
2711
|
+
" can be provided to NamedTuple, not both")
|
2712
|
+
if __fields is _marker or __fields is None:
|
2713
|
+
warnings.warn(
|
2714
|
+
deprecation_msg.format(name=deprecated_thing, remove="3.15"),
|
2715
|
+
DeprecationWarning,
|
2716
|
+
stacklevel=2,
|
2717
|
+
)
|
2718
|
+
__fields = kwargs.items()
|
2719
|
+
nt = _make_nmtuple(__typename, __fields, module=_caller())
|
2720
|
+
nt.__orig_bases__ = (NamedTuple,)
|
2721
|
+
return nt
|
2722
|
+
|
2723
|
+
# On 3.8+, alter the signature so that it matches typing.NamedTuple.
|
2724
|
+
# The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7,
|
2725
|
+
# so just leave the signature as it is on 3.7.
|
2726
|
+
if sys.version_info >= (3, 8):
|
2727
|
+
_new_signature = '(typename, fields=None, /, **kwargs)'
|
2728
|
+
if isinstance(NamedTuple, _types.FunctionType):
|
2729
|
+
NamedTuple.__text_signature__ = _new_signature
|
2730
|
+
else:
|
2731
|
+
NamedTuple.__call__.__text_signature__ = _new_signature
|
2732
|
+
|
2733
|
+
|
2734
|
+
if hasattr(collections.abc, "Buffer"):
|
2735
|
+
Buffer = collections.abc.Buffer
|
2736
|
+
else:
|
2737
|
+
class Buffer(abc.ABC):
|
2738
|
+
"""Base class for classes that implement the buffer protocol.
|
2739
|
+
|
2740
|
+
The buffer protocol allows Python objects to expose a low-level
|
2741
|
+
memory buffer interface. Before Python 3.12, it is not possible
|
2742
|
+
to implement the buffer protocol in pure Python code, or even
|
2743
|
+
to check whether a class implements the buffer protocol. In
|
2744
|
+
Python 3.12 and higher, the ``__buffer__`` method allows access
|
2745
|
+
to the buffer protocol from Python code, and the
|
2746
|
+
``collections.abc.Buffer`` ABC allows checking whether a class
|
2747
|
+
implements the buffer protocol.
|
2748
|
+
|
2749
|
+
To indicate support for the buffer protocol in earlier versions,
|
2750
|
+
inherit from this ABC, either in a stub file or at runtime,
|
2751
|
+
or use ABC registration. This ABC provides no methods, because
|
2752
|
+
there is no Python-accessible methods shared by pre-3.12 buffer
|
2753
|
+
classes. It is useful primarily for static checks.
|
2754
|
+
|
2755
|
+
"""
|
2756
|
+
|
2757
|
+
# As a courtesy, register the most common stdlib buffer classes.
|
2758
|
+
Buffer.register(memoryview)
|
2759
|
+
Buffer.register(bytearray)
|
2760
|
+
Buffer.register(bytes)
|
2761
|
+
|
2762
|
+
|
2763
|
+
# Backport of types.get_original_bases, available on 3.12+ in CPython
|
2764
|
+
if hasattr(_types, "get_original_bases"):
|
2765
|
+
get_original_bases = _types.get_original_bases
|
2766
|
+
else:
|
2767
|
+
def get_original_bases(__cls):
|
2768
|
+
"""Return the class's "original" bases prior to modification by `__mro_entries__`.
|
2769
|
+
|
2770
|
+
Examples::
|
2771
|
+
|
2772
|
+
from typing import TypeVar, Generic
|
2773
|
+
from metaflow._vendor.v3_7.typing_extensions import NamedTuple, TypedDict
|
2774
|
+
|
2775
|
+
T = TypeVar("T")
|
2776
|
+
class Foo(Generic[T]): ...
|
2777
|
+
class Bar(Foo[int], float): ...
|
2778
|
+
class Baz(list[str]): ...
|
2779
|
+
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
|
2780
|
+
Spam = TypedDict("Spam", {"a": int, "b": str})
|
2781
|
+
|
2782
|
+
assert get_original_bases(Bar) == (Foo[int], float)
|
2783
|
+
assert get_original_bases(Baz) == (list[str],)
|
2784
|
+
assert get_original_bases(Eggs) == (NamedTuple,)
|
2785
|
+
assert get_original_bases(Spam) == (TypedDict,)
|
2786
|
+
assert get_original_bases(int) == (object,)
|
2787
|
+
"""
|
2788
|
+
try:
|
2789
|
+
return __cls.__orig_bases__
|
2790
|
+
except AttributeError:
|
2791
|
+
try:
|
2792
|
+
return __cls.__bases__
|
2793
|
+
except AttributeError:
|
2794
|
+
raise TypeError(
|
2795
|
+
f'Expected an instance of type, not {type(__cls).__name__!r}'
|
2796
|
+
) from None
|
2797
|
+
|
2798
|
+
|
2799
|
+
# NewType is a class on Python 3.10+, making it pickleable
|
2800
|
+
# The error message for subclassing instances of NewType was improved on 3.11+
|
2801
|
+
if sys.version_info >= (3, 11):
|
2802
|
+
NewType = typing.NewType
|
2803
|
+
else:
|
2804
|
+
class NewType:
|
2805
|
+
"""NewType creates simple unique types with almost zero
|
2806
|
+
runtime overhead. NewType(name, tp) is considered a subtype of tp
|
2807
|
+
by static type checkers. At runtime, NewType(name, tp) returns
|
2808
|
+
a dummy callable that simply returns its argument. Usage::
|
2809
|
+
UserId = NewType('UserId', int)
|
2810
|
+
def name_by_id(user_id: UserId) -> str:
|
2811
|
+
...
|
2812
|
+
UserId('user') # Fails type check
|
2813
|
+
name_by_id(42) # Fails type check
|
2814
|
+
name_by_id(UserId(42)) # OK
|
2815
|
+
num = UserId(5) + 1 # type: int
|
2816
|
+
"""
|
2817
|
+
|
2818
|
+
def __call__(self, obj):
|
2819
|
+
return obj
|
2820
|
+
|
2821
|
+
def __init__(self, name, tp):
|
2822
|
+
self.__qualname__ = name
|
2823
|
+
if '.' in name:
|
2824
|
+
name = name.rpartition('.')[-1]
|
2825
|
+
self.__name__ = name
|
2826
|
+
self.__supertype__ = tp
|
2827
|
+
def_mod = _caller()
|
2828
|
+
if def_mod != 'typing_extensions':
|
2829
|
+
self.__module__ = def_mod
|
2830
|
+
|
2831
|
+
def __mro_entries__(self, bases):
|
2832
|
+
# We defined __mro_entries__ to get a better error message
|
2833
|
+
# if a user attempts to subclass a NewType instance. bpo-46170
|
2834
|
+
supercls_name = self.__name__
|
2835
|
+
|
2836
|
+
class Dummy:
|
2837
|
+
def __init_subclass__(cls):
|
2838
|
+
subcls_name = cls.__name__
|
2839
|
+
raise TypeError(
|
2840
|
+
f"Cannot subclass an instance of NewType. "
|
2841
|
+
f"Perhaps you were looking for: "
|
2842
|
+
f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
|
2843
|
+
)
|
2844
|
+
|
2845
|
+
return (Dummy,)
|
2846
|
+
|
2847
|
+
def __repr__(self):
|
2848
|
+
return f'{self.__module__}.{self.__qualname__}'
|
2849
|
+
|
2850
|
+
def __reduce__(self):
|
2851
|
+
return self.__qualname__
|
2852
|
+
|
2853
|
+
if sys.version_info >= (3, 10):
|
2854
|
+
# PEP 604 methods
|
2855
|
+
# It doesn't make sense to have these methods on Python <3.10
|
2856
|
+
|
2857
|
+
def __or__(self, other):
|
2858
|
+
return typing.Union[self, other]
|
2859
|
+
|
2860
|
+
def __ror__(self, other):
|
2861
|
+
return typing.Union[other, self]
|
2862
|
+
|
2863
|
+
|
2864
|
+
if hasattr(typing, "TypeAliasType"):
|
2865
|
+
TypeAliasType = typing.TypeAliasType
|
2866
|
+
else:
|
2867
|
+
def _is_unionable(obj):
|
2868
|
+
"""Corresponds to is_unionable() in unionobject.c in CPython."""
|
2869
|
+
return obj is None or isinstance(obj, (
|
2870
|
+
type,
|
2871
|
+
_types.GenericAlias,
|
2872
|
+
_types.UnionType,
|
2873
|
+
TypeAliasType,
|
2874
|
+
))
|
2875
|
+
|
2876
|
+
class TypeAliasType:
|
2877
|
+
"""Create named, parameterized type aliases.
|
2878
|
+
|
2879
|
+
This provides a backport of the new `type` statement in Python 3.12:
|
2880
|
+
|
2881
|
+
type ListOrSet[T] = list[T] | set[T]
|
2882
|
+
|
2883
|
+
is equivalent to:
|
2884
|
+
|
2885
|
+
T = TypeVar("T")
|
2886
|
+
ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
|
2887
|
+
|
2888
|
+
The name ListOrSet can then be used as an alias for the type it refers to.
|
2889
|
+
|
2890
|
+
The type_params argument should contain all the type parameters used
|
2891
|
+
in the value of the type alias. If the alias is not generic, this
|
2892
|
+
argument is omitted.
|
2893
|
+
|
2894
|
+
Static type checkers should only support type aliases declared using
|
2895
|
+
TypeAliasType that follow these rules:
|
2896
|
+
|
2897
|
+
- The first argument (the name) must be a string literal.
|
2898
|
+
- The TypeAliasType instance must be immediately assigned to a variable
|
2899
|
+
of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
|
2900
|
+
as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
|
2901
|
+
|
2902
|
+
"""
|
2903
|
+
|
2904
|
+
def __init__(self, name: str, value, *, type_params=()):
|
2905
|
+
if not isinstance(name, str):
|
2906
|
+
raise TypeError("TypeAliasType name must be a string")
|
2907
|
+
self.__value__ = value
|
2908
|
+
self.__type_params__ = type_params
|
2909
|
+
|
2910
|
+
parameters = []
|
2911
|
+
for type_param in type_params:
|
2912
|
+
if isinstance(type_param, TypeVarTuple):
|
2913
|
+
parameters.extend(type_param)
|
2914
|
+
else:
|
2915
|
+
parameters.append(type_param)
|
2916
|
+
self.__parameters__ = tuple(parameters)
|
2917
|
+
def_mod = _caller()
|
2918
|
+
if def_mod != 'typing_extensions':
|
2919
|
+
self.__module__ = def_mod
|
2920
|
+
# Setting this attribute closes the TypeAliasType from further modification
|
2921
|
+
self.__name__ = name
|
2922
|
+
|
2923
|
+
def __setattr__(self, __name: str, __value: object) -> None:
|
2924
|
+
if hasattr(self, "__name__"):
|
2925
|
+
self._raise_attribute_error(__name)
|
2926
|
+
super().__setattr__(__name, __value)
|
2927
|
+
|
2928
|
+
def __delattr__(self, __name: str) -> Never:
|
2929
|
+
self._raise_attribute_error(__name)
|
2930
|
+
|
2931
|
+
def _raise_attribute_error(self, name: str) -> Never:
|
2932
|
+
# Match the Python 3.12 error messages exactly
|
2933
|
+
if name == "__name__":
|
2934
|
+
raise AttributeError("readonly attribute")
|
2935
|
+
elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
|
2936
|
+
raise AttributeError(
|
2937
|
+
f"attribute '{name}' of 'typing.TypeAliasType' objects "
|
2938
|
+
"is not writable"
|
2939
|
+
)
|
2940
|
+
else:
|
2941
|
+
raise AttributeError(
|
2942
|
+
f"'typing.TypeAliasType' object has no attribute '{name}'"
|
2943
|
+
)
|
2944
|
+
|
2945
|
+
def __repr__(self) -> str:
|
2946
|
+
return self.__name__
|
2947
|
+
|
2948
|
+
def __getitem__(self, parameters):
|
2949
|
+
if not isinstance(parameters, tuple):
|
2950
|
+
parameters = (parameters,)
|
2951
|
+
parameters = [
|
2952
|
+
typing._type_check(
|
2953
|
+
item, f'Subscripting {self.__name__} requires a type.'
|
2954
|
+
)
|
2955
|
+
for item in parameters
|
2956
|
+
]
|
2957
|
+
return typing._GenericAlias(self, tuple(parameters))
|
2958
|
+
|
2959
|
+
def __reduce__(self):
|
2960
|
+
return self.__name__
|
2961
|
+
|
2962
|
+
def __init_subclass__(cls, *args, **kwargs):
|
2963
|
+
raise TypeError(
|
2964
|
+
"type 'typing_extensions.TypeAliasType' is not an acceptable base type"
|
2965
|
+
)
|
2966
|
+
|
2967
|
+
# The presence of this method convinces typing._type_check
|
2968
|
+
# that TypeAliasTypes are types.
|
2969
|
+
def __call__(self):
|
2970
|
+
raise TypeError("Type alias is not callable")
|
2971
|
+
|
2972
|
+
if sys.version_info >= (3, 10):
|
2973
|
+
def __or__(self, right):
|
2974
|
+
# For forward compatibility with 3.12, reject Unions
|
2975
|
+
# that are not accepted by the built-in Union.
|
2976
|
+
if not _is_unionable(right):
|
2977
|
+
return NotImplemented
|
2978
|
+
return typing.Union[self, right]
|
2979
|
+
|
2980
|
+
def __ror__(self, left):
|
2981
|
+
if not _is_unionable(left):
|
2982
|
+
return NotImplemented
|
2983
|
+
return typing.Union[left, self]
|
2984
|
+
|
2985
|
+
|
2986
|
+
if hasattr(typing, "is_protocol"):
|
2987
|
+
is_protocol = typing.is_protocol
|
2988
|
+
get_protocol_members = typing.get_protocol_members
|
2989
|
+
else:
|
2990
|
+
def is_protocol(__tp: type) -> bool:
|
2991
|
+
"""Return True if the given type is a Protocol.
|
2992
|
+
|
2993
|
+
Example::
|
2994
|
+
|
2995
|
+
>>> from typing_extensions import Protocol, is_protocol
|
2996
|
+
>>> class P(Protocol):
|
2997
|
+
... def a(self) -> str: ...
|
2998
|
+
... b: int
|
2999
|
+
>>> is_protocol(P)
|
3000
|
+
True
|
3001
|
+
>>> is_protocol(int)
|
3002
|
+
False
|
3003
|
+
"""
|
3004
|
+
return (
|
3005
|
+
isinstance(__tp, type)
|
3006
|
+
and getattr(__tp, '_is_protocol', False)
|
3007
|
+
and __tp is not Protocol
|
3008
|
+
and __tp is not getattr(typing, "Protocol", object())
|
3009
|
+
)
|
3010
|
+
|
3011
|
+
def get_protocol_members(__tp: type) -> typing.FrozenSet[str]:
|
3012
|
+
"""Return the set of members defined in a Protocol.
|
3013
|
+
|
3014
|
+
Example::
|
3015
|
+
|
3016
|
+
>>> from typing_extensions import Protocol, get_protocol_members
|
3017
|
+
>>> class P(Protocol):
|
3018
|
+
... def a(self) -> str: ...
|
3019
|
+
... b: int
|
3020
|
+
>>> get_protocol_members(P)
|
3021
|
+
frozenset({'a', 'b'})
|
3022
|
+
|
3023
|
+
Raise a TypeError for arguments that are not Protocols.
|
3024
|
+
"""
|
3025
|
+
if not is_protocol(__tp):
|
3026
|
+
raise TypeError(f'{__tp!r} is not a Protocol')
|
3027
|
+
if hasattr(__tp, '__protocol_attrs__'):
|
3028
|
+
return frozenset(__tp.__protocol_attrs__)
|
3029
|
+
return frozenset(_get_protocol_attrs(__tp))
|
3030
|
+
|
3031
|
+
|
3032
|
+
# Aliases for items that have always been in typing.
|
3033
|
+
# Explicitly assign these (rather than using `from typing import *` at the top),
|
3034
|
+
# so that we get a CI error if one of these is deleted from typing.py
|
3035
|
+
# in a future version of Python
|
3036
|
+
AbstractSet = typing.AbstractSet
|
3037
|
+
AnyStr = typing.AnyStr
|
3038
|
+
BinaryIO = typing.BinaryIO
|
3039
|
+
Callable = typing.Callable
|
3040
|
+
Collection = typing.Collection
|
3041
|
+
Container = typing.Container
|
3042
|
+
Dict = typing.Dict
|
3043
|
+
ForwardRef = typing.ForwardRef
|
3044
|
+
FrozenSet = typing.FrozenSet
|
3045
|
+
Generator = typing.Generator
|
3046
|
+
Generic = typing.Generic
|
3047
|
+
Hashable = typing.Hashable
|
3048
|
+
IO = typing.IO
|
3049
|
+
ItemsView = typing.ItemsView
|
3050
|
+
Iterable = typing.Iterable
|
3051
|
+
Iterator = typing.Iterator
|
3052
|
+
KeysView = typing.KeysView
|
3053
|
+
List = typing.List
|
3054
|
+
Mapping = typing.Mapping
|
3055
|
+
MappingView = typing.MappingView
|
3056
|
+
Match = typing.Match
|
3057
|
+
MutableMapping = typing.MutableMapping
|
3058
|
+
MutableSequence = typing.MutableSequence
|
3059
|
+
MutableSet = typing.MutableSet
|
3060
|
+
Optional = typing.Optional
|
3061
|
+
Pattern = typing.Pattern
|
3062
|
+
Reversible = typing.Reversible
|
3063
|
+
Sequence = typing.Sequence
|
3064
|
+
Set = typing.Set
|
3065
|
+
Sized = typing.Sized
|
3066
|
+
TextIO = typing.TextIO
|
3067
|
+
Tuple = typing.Tuple
|
3068
|
+
Union = typing.Union
|
3069
|
+
ValuesView = typing.ValuesView
|
3070
|
+
cast = typing.cast
|
3071
|
+
no_type_check = typing.no_type_check
|
3072
|
+
no_type_check_decorator = typing.no_type_check_decorator
|