metaflow 2.11.16__py2.py3-none-any.whl → 2.12.0__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.
Files changed (46) hide show
  1. metaflow/__init__.py +5 -0
  2. metaflow/_vendor/importlib_metadata/__init__.py +1063 -0
  3. metaflow/_vendor/importlib_metadata/_adapters.py +68 -0
  4. metaflow/_vendor/importlib_metadata/_collections.py +30 -0
  5. metaflow/_vendor/importlib_metadata/_compat.py +71 -0
  6. metaflow/_vendor/importlib_metadata/_functools.py +104 -0
  7. metaflow/_vendor/importlib_metadata/_itertools.py +73 -0
  8. metaflow/_vendor/importlib_metadata/_meta.py +48 -0
  9. metaflow/_vendor/importlib_metadata/_text.py +99 -0
  10. metaflow/_vendor/importlib_metadata/py.typed +0 -0
  11. metaflow/_vendor/typeguard/__init__.py +48 -0
  12. metaflow/_vendor/typeguard/_checkers.py +906 -0
  13. metaflow/_vendor/typeguard/_config.py +108 -0
  14. metaflow/_vendor/typeguard/_decorators.py +237 -0
  15. metaflow/_vendor/typeguard/_exceptions.py +42 -0
  16. metaflow/_vendor/typeguard/_functions.py +307 -0
  17. metaflow/_vendor/typeguard/_importhook.py +213 -0
  18. metaflow/_vendor/typeguard/_memo.py +48 -0
  19. metaflow/_vendor/typeguard/_pytest_plugin.py +100 -0
  20. metaflow/_vendor/typeguard/_suppression.py +88 -0
  21. metaflow/_vendor/typeguard/_transformer.py +1193 -0
  22. metaflow/_vendor/typeguard/_union_transformer.py +54 -0
  23. metaflow/_vendor/typeguard/_utils.py +169 -0
  24. metaflow/_vendor/typeguard/py.typed +0 -0
  25. metaflow/_vendor/typing_extensions.py +3053 -0
  26. metaflow/cli.py +48 -36
  27. metaflow/cmd/develop/stubs.py +2 -0
  28. metaflow/extension_support/__init__.py +2 -0
  29. metaflow/parameters.py +1 -0
  30. metaflow/plugins/aws/batch/batch_decorator.py +3 -3
  31. metaflow/plugins/kubernetes/kubernetes_job.py +0 -5
  32. metaflow/runner/__init__.py +0 -0
  33. metaflow/runner/click_api.py +406 -0
  34. metaflow/runner/metaflow_runner.py +452 -0
  35. metaflow/runner/nbrun.py +246 -0
  36. metaflow/runner/subprocess_manager.py +552 -0
  37. metaflow/vendor.py +0 -1
  38. metaflow/version.py +1 -1
  39. {metaflow-2.11.16.dist-info → metaflow-2.12.0.dist-info}/METADATA +2 -2
  40. {metaflow-2.11.16.dist-info → metaflow-2.12.0.dist-info}/RECORD +45 -17
  41. metaflow/_vendor/v3_7/__init__.py +0 -1
  42. /metaflow/_vendor/{v3_7/zipp.py → zipp.py} +0 -0
  43. {metaflow-2.11.16.dist-info → metaflow-2.12.0.dist-info}/LICENSE +0 -0
  44. {metaflow-2.11.16.dist-info → metaflow-2.12.0.dist-info}/WHEEL +0 -0
  45. {metaflow-2.11.16.dist-info → metaflow-2.12.0.dist-info}/entry_points.txt +0 -0
  46. {metaflow-2.11.16.dist-info → metaflow-2.12.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,3053 @@
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
+ if sys.version_info >= (3, 13):
957
+ # The standard library TypedDict in Python 3.8 does not store runtime information
958
+ # about which (if any) keys are optional. See https://bugs.python.org/issue38834
959
+ # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
960
+ # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
961
+ # The standard library TypedDict below Python 3.11 does not store runtime
962
+ # information about optional and required keys when using Required or NotRequired.
963
+ # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
964
+ # Aaaand on 3.12 we add __orig_bases__ to TypedDict
965
+ # to enable better runtime introspection.
966
+ # On 3.13 we deprecate some odd ways of creating TypedDicts.
967
+ TypedDict = typing.TypedDict
968
+ _TypedDictMeta = typing._TypedDictMeta
969
+ is_typeddict = typing.is_typeddict
970
+ else:
971
+ # 3.10.0 and later
972
+ _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
973
+
974
+ if sys.version_info >= (3, 8):
975
+ _fake_name = "Protocol"
976
+ else:
977
+ _fake_name = "_Protocol"
978
+
979
+ class _TypedDictMeta(type):
980
+ def __new__(cls, name, bases, ns, total=True):
981
+ """Create new typed dict class object.
982
+
983
+ This method is called when TypedDict is subclassed,
984
+ or when TypedDict is instantiated. This way
985
+ TypedDict supports all three syntax forms described in its docstring.
986
+ Subclasses and instances of TypedDict return actual dictionaries.
987
+ """
988
+ for base in bases:
989
+ if type(base) is not _TypedDictMeta and base is not typing.Generic:
990
+ raise TypeError('cannot inherit from both a TypedDict type '
991
+ 'and a non-TypedDict base class')
992
+
993
+ if any(issubclass(b, typing.Generic) for b in bases):
994
+ generic_base = (typing.Generic,)
995
+ else:
996
+ generic_base = ()
997
+
998
+ # typing.py generally doesn't let you inherit from plain Generic, unless
999
+ # the name of the class happens to be "Protocol" (or "_Protocol" on 3.7).
1000
+ tp_dict = type.__new__(_TypedDictMeta, _fake_name, (*generic_base, dict), ns)
1001
+ tp_dict.__name__ = name
1002
+ if tp_dict.__qualname__ == _fake_name:
1003
+ tp_dict.__qualname__ = name
1004
+
1005
+ if not hasattr(tp_dict, '__orig_bases__'):
1006
+ tp_dict.__orig_bases__ = bases
1007
+
1008
+ annotations = {}
1009
+ own_annotations = ns.get('__annotations__', {})
1010
+ msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
1011
+ if _TAKES_MODULE:
1012
+ own_annotations = {
1013
+ n: typing._type_check(tp, msg, module=tp_dict.__module__)
1014
+ for n, tp in own_annotations.items()
1015
+ }
1016
+ else:
1017
+ own_annotations = {
1018
+ n: typing._type_check(tp, msg)
1019
+ for n, tp in own_annotations.items()
1020
+ }
1021
+ required_keys = set()
1022
+ optional_keys = set()
1023
+
1024
+ for base in bases:
1025
+ annotations.update(base.__dict__.get('__annotations__', {}))
1026
+ required_keys.update(base.__dict__.get('__required_keys__', ()))
1027
+ optional_keys.update(base.__dict__.get('__optional_keys__', ()))
1028
+
1029
+ annotations.update(own_annotations)
1030
+ for annotation_key, annotation_type in own_annotations.items():
1031
+ annotation_origin = get_origin(annotation_type)
1032
+ if annotation_origin is Annotated:
1033
+ annotation_args = get_args(annotation_type)
1034
+ if annotation_args:
1035
+ annotation_type = annotation_args[0]
1036
+ annotation_origin = get_origin(annotation_type)
1037
+
1038
+ if annotation_origin is Required:
1039
+ required_keys.add(annotation_key)
1040
+ elif annotation_origin is NotRequired:
1041
+ optional_keys.add(annotation_key)
1042
+ elif total:
1043
+ required_keys.add(annotation_key)
1044
+ else:
1045
+ optional_keys.add(annotation_key)
1046
+
1047
+ tp_dict.__annotations__ = annotations
1048
+ tp_dict.__required_keys__ = frozenset(required_keys)
1049
+ tp_dict.__optional_keys__ = frozenset(optional_keys)
1050
+ if not hasattr(tp_dict, '__total__'):
1051
+ tp_dict.__total__ = total
1052
+ return tp_dict
1053
+
1054
+ __call__ = dict # static method
1055
+
1056
+ def __subclasscheck__(cls, other):
1057
+ # Typed dicts are only for static structural subtyping.
1058
+ raise TypeError('TypedDict does not support instance and class checks')
1059
+
1060
+ __instancecheck__ = __subclasscheck__
1061
+
1062
+ def TypedDict(__typename, __fields=_marker, *, total=True, **kwargs):
1063
+ """A simple typed namespace. At runtime it is equivalent to a plain dict.
1064
+
1065
+ TypedDict creates a dictionary type such that a type checker will expect all
1066
+ instances to have a certain set of keys, where each key is
1067
+ associated with a value of a consistent type. This expectation
1068
+ is not checked at runtime.
1069
+
1070
+ Usage::
1071
+
1072
+ class Point2D(TypedDict):
1073
+ x: int
1074
+ y: int
1075
+ label: str
1076
+
1077
+ a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1078
+ b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1079
+
1080
+ assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1081
+
1082
+ The type info can be accessed via the Point2D.__annotations__ dict, and
1083
+ the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1084
+ TypedDict supports an additional equivalent form::
1085
+
1086
+ Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1087
+
1088
+ By default, all keys must be present in a TypedDict. It is possible
1089
+ to override this by specifying totality::
1090
+
1091
+ class Point2D(TypedDict, total=False):
1092
+ x: int
1093
+ y: int
1094
+
1095
+ This means that a Point2D TypedDict can have any of the keys omitted. A type
1096
+ checker is only expected to support a literal False or True as the value of
1097
+ the total argument. True is the default, and makes all items defined in the
1098
+ class body be required.
1099
+
1100
+ The Required and NotRequired special forms can also be used to mark
1101
+ individual keys as being required or not required::
1102
+
1103
+ class Point2D(TypedDict):
1104
+ x: int # the "x" key must always be present (Required is the default)
1105
+ y: NotRequired[int] # the "y" key can be omitted
1106
+
1107
+ See PEP 655 for more details on Required and NotRequired.
1108
+ """
1109
+ if __fields is _marker or __fields is None:
1110
+ if __fields is _marker:
1111
+ deprecated_thing = "Failing to pass a value for the 'fields' parameter"
1112
+ else:
1113
+ deprecated_thing = "Passing `None` as the 'fields' parameter"
1114
+
1115
+ example = f"`{__typename} = TypedDict({__typename!r}, {{}})`"
1116
+ deprecation_msg = (
1117
+ f"{deprecated_thing} is deprecated and will be disallowed in "
1118
+ "Python 3.15. To create a TypedDict class with 0 fields "
1119
+ "using the functional syntax, pass an empty dictionary, e.g. "
1120
+ ) + example + "."
1121
+ warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
1122
+ __fields = kwargs
1123
+ elif kwargs:
1124
+ raise TypeError("TypedDict takes either a dict or keyword arguments,"
1125
+ " but not both")
1126
+ if kwargs:
1127
+ warnings.warn(
1128
+ "The kwargs-based syntax for TypedDict definitions is deprecated "
1129
+ "in Python 3.11, will be removed in Python 3.13, and may not be "
1130
+ "understood by third-party type checkers.",
1131
+ DeprecationWarning,
1132
+ stacklevel=2,
1133
+ )
1134
+
1135
+ ns = {'__annotations__': dict(__fields)}
1136
+ module = _caller()
1137
+ if module is not None:
1138
+ # Setting correct module is necessary to make typed dict classes pickleable.
1139
+ ns['__module__'] = module
1140
+
1141
+ td = _TypedDictMeta(__typename, (), ns, total=total)
1142
+ td.__orig_bases__ = (TypedDict,)
1143
+ return td
1144
+
1145
+ _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
1146
+ TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
1147
+
1148
+ if hasattr(typing, "_TypedDictMeta"):
1149
+ _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
1150
+ else:
1151
+ _TYPEDDICT_TYPES = (_TypedDictMeta,)
1152
+
1153
+ def is_typeddict(tp):
1154
+ """Check if an annotation is a TypedDict class
1155
+
1156
+ For example::
1157
+ class Film(TypedDict):
1158
+ title: str
1159
+ year: int
1160
+
1161
+ is_typeddict(Film) # => True
1162
+ is_typeddict(Union[list, str]) # => False
1163
+ """
1164
+ # On 3.8, this would otherwise return True
1165
+ if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
1166
+ return False
1167
+ return isinstance(tp, _TYPEDDICT_TYPES)
1168
+
1169
+
1170
+ if hasattr(typing, "assert_type"):
1171
+ assert_type = typing.assert_type
1172
+
1173
+ else:
1174
+ def assert_type(__val, __typ):
1175
+ """Assert (to the type checker) that the value is of the given type.
1176
+
1177
+ When the type checker encounters a call to assert_type(), it
1178
+ emits an error if the value is not of the specified type::
1179
+
1180
+ def greet(name: str) -> None:
1181
+ assert_type(name, str) # ok
1182
+ assert_type(name, int) # type checker error
1183
+
1184
+ At runtime this returns the first argument unchanged and otherwise
1185
+ does nothing.
1186
+ """
1187
+ return __val
1188
+
1189
+
1190
+ if hasattr(typing, "Required"):
1191
+ get_type_hints = typing.get_type_hints
1192
+ else:
1193
+ # replaces _strip_annotations()
1194
+ def _strip_extras(t):
1195
+ """Strips Annotated, Required and NotRequired from a given type."""
1196
+ if isinstance(t, _AnnotatedAlias):
1197
+ return _strip_extras(t.__origin__)
1198
+ if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
1199
+ return _strip_extras(t.__args__[0])
1200
+ if isinstance(t, typing._GenericAlias):
1201
+ stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1202
+ if stripped_args == t.__args__:
1203
+ return t
1204
+ return t.copy_with(stripped_args)
1205
+ if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
1206
+ stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1207
+ if stripped_args == t.__args__:
1208
+ return t
1209
+ return _types.GenericAlias(t.__origin__, stripped_args)
1210
+ if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
1211
+ stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1212
+ if stripped_args == t.__args__:
1213
+ return t
1214
+ return functools.reduce(operator.or_, stripped_args)
1215
+
1216
+ return t
1217
+
1218
+ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1219
+ """Return type hints for an object.
1220
+
1221
+ This is often the same as obj.__annotations__, but it handles
1222
+ forward references encoded as string literals, adds Optional[t] if a
1223
+ default value equal to None is set and recursively replaces all
1224
+ 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
1225
+ (unless 'include_extras=True').
1226
+
1227
+ The argument may be a module, class, method, or function. The annotations
1228
+ are returned as a dictionary. For classes, annotations include also
1229
+ inherited members.
1230
+
1231
+ TypeError is raised if the argument is not of a type that can contain
1232
+ annotations, and an empty dictionary is returned if no annotations are
1233
+ present.
1234
+
1235
+ BEWARE -- the behavior of globalns and localns is counterintuitive
1236
+ (unless you are familiar with how eval() and exec() work). The
1237
+ search order is locals first, then globals.
1238
+
1239
+ - If no dict arguments are passed, an attempt is made to use the
1240
+ globals from obj (or the respective module's globals for classes),
1241
+ and these are also used as the locals. If the object does not appear
1242
+ to have globals, an empty dictionary is used.
1243
+
1244
+ - If one dict argument is passed, it is used for both globals and
1245
+ locals.
1246
+
1247
+ - If two dict arguments are passed, they specify globals and
1248
+ locals, respectively.
1249
+ """
1250
+ if hasattr(typing, "Annotated"):
1251
+ hint = typing.get_type_hints(
1252
+ obj, globalns=globalns, localns=localns, include_extras=True
1253
+ )
1254
+ else:
1255
+ hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
1256
+ if include_extras:
1257
+ return hint
1258
+ return {k: _strip_extras(t) for k, t in hint.items()}
1259
+
1260
+
1261
+ # Python 3.9+ has PEP 593 (Annotated)
1262
+ if hasattr(typing, 'Annotated'):
1263
+ Annotated = typing.Annotated
1264
+ # Not exported and not a public API, but needed for get_origin() and get_args()
1265
+ # to work.
1266
+ _AnnotatedAlias = typing._AnnotatedAlias
1267
+ # 3.7-3.8
1268
+ else:
1269
+ class _AnnotatedAlias(typing._GenericAlias, _root=True):
1270
+ """Runtime representation of an annotated type.
1271
+
1272
+ At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1273
+ with extra annotations. The alias behaves like a normal typing alias,
1274
+ instantiating is the same as instantiating the underlying type, binding
1275
+ it to types is also the same.
1276
+ """
1277
+ def __init__(self, origin, metadata):
1278
+ if isinstance(origin, _AnnotatedAlias):
1279
+ metadata = origin.__metadata__ + metadata
1280
+ origin = origin.__origin__
1281
+ super().__init__(origin, origin)
1282
+ self.__metadata__ = metadata
1283
+
1284
+ def copy_with(self, params):
1285
+ assert len(params) == 1
1286
+ new_type = params[0]
1287
+ return _AnnotatedAlias(new_type, self.__metadata__)
1288
+
1289
+ def __repr__(self):
1290
+ return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1291
+ f"{', '.join(repr(a) for a in self.__metadata__)}]")
1292
+
1293
+ def __reduce__(self):
1294
+ return operator.getitem, (
1295
+ Annotated, (self.__origin__,) + self.__metadata__
1296
+ )
1297
+
1298
+ def __eq__(self, other):
1299
+ if not isinstance(other, _AnnotatedAlias):
1300
+ return NotImplemented
1301
+ if self.__origin__ != other.__origin__:
1302
+ return False
1303
+ return self.__metadata__ == other.__metadata__
1304
+
1305
+ def __hash__(self):
1306
+ return hash((self.__origin__, self.__metadata__))
1307
+
1308
+ class Annotated:
1309
+ """Add context specific metadata to a type.
1310
+
1311
+ Example: Annotated[int, runtime_check.Unsigned] indicates to the
1312
+ hypothetical runtime_check module that this type is an unsigned int.
1313
+ Every other consumer of this type can ignore this metadata and treat
1314
+ this type as int.
1315
+
1316
+ The first argument to Annotated must be a valid type (and will be in
1317
+ the __origin__ field), the remaining arguments are kept as a tuple in
1318
+ the __extra__ field.
1319
+
1320
+ Details:
1321
+
1322
+ - It's an error to call `Annotated` with less than two arguments.
1323
+ - Nested Annotated are flattened::
1324
+
1325
+ Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1326
+
1327
+ - Instantiating an annotated type is equivalent to instantiating the
1328
+ underlying type::
1329
+
1330
+ Annotated[C, Ann1](5) == C(5)
1331
+
1332
+ - Annotated can be used as a generic type alias::
1333
+
1334
+ Optimized = Annotated[T, runtime.Optimize()]
1335
+ Optimized[int] == Annotated[int, runtime.Optimize()]
1336
+
1337
+ OptimizedList = Annotated[List[T], runtime.Optimize()]
1338
+ OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1339
+ """
1340
+
1341
+ __slots__ = ()
1342
+
1343
+ def __new__(cls, *args, **kwargs):
1344
+ raise TypeError("Type Annotated cannot be instantiated.")
1345
+
1346
+ @typing._tp_cache
1347
+ def __class_getitem__(cls, params):
1348
+ if not isinstance(params, tuple) or len(params) < 2:
1349
+ raise TypeError("Annotated[...] should be used "
1350
+ "with at least two arguments (a type and an "
1351
+ "annotation).")
1352
+ allowed_special_forms = (ClassVar, Final)
1353
+ if get_origin(params[0]) in allowed_special_forms:
1354
+ origin = params[0]
1355
+ else:
1356
+ msg = "Annotated[t, ...]: t must be a type."
1357
+ origin = typing._type_check(params[0], msg)
1358
+ metadata = tuple(params[1:])
1359
+ return _AnnotatedAlias(origin, metadata)
1360
+
1361
+ def __init_subclass__(cls, *args, **kwargs):
1362
+ raise TypeError(
1363
+ f"Cannot subclass {cls.__module__}.Annotated"
1364
+ )
1365
+
1366
+ # Python 3.8 has get_origin() and get_args() but those implementations aren't
1367
+ # Annotated-aware, so we can't use those. Python 3.9's versions don't support
1368
+ # ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1369
+ if sys.version_info[:2] >= (3, 10):
1370
+ get_origin = typing.get_origin
1371
+ get_args = typing.get_args
1372
+ # 3.7-3.9
1373
+ else:
1374
+ try:
1375
+ # 3.9+
1376
+ from typing import _BaseGenericAlias
1377
+ except ImportError:
1378
+ _BaseGenericAlias = typing._GenericAlias
1379
+ try:
1380
+ # 3.9+
1381
+ from typing import GenericAlias as _typing_GenericAlias
1382
+ except ImportError:
1383
+ _typing_GenericAlias = typing._GenericAlias
1384
+
1385
+ def get_origin(tp):
1386
+ """Get the unsubscripted version of a type.
1387
+
1388
+ This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1389
+ and Annotated. Return None for unsupported types. Examples::
1390
+
1391
+ get_origin(Literal[42]) is Literal
1392
+ get_origin(int) is None
1393
+ get_origin(ClassVar[int]) is ClassVar
1394
+ get_origin(Generic) is Generic
1395
+ get_origin(Generic[T]) is Generic
1396
+ get_origin(Union[T, int]) is Union
1397
+ get_origin(List[Tuple[T, T]][int]) == list
1398
+ get_origin(P.args) is P
1399
+ """
1400
+ if isinstance(tp, _AnnotatedAlias):
1401
+ return Annotated
1402
+ if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
1403
+ ParamSpecArgs, ParamSpecKwargs)):
1404
+ return tp.__origin__
1405
+ if tp is typing.Generic:
1406
+ return typing.Generic
1407
+ return None
1408
+
1409
+ def get_args(tp):
1410
+ """Get type arguments with all substitutions performed.
1411
+
1412
+ For unions, basic simplifications used by Union constructor are performed.
1413
+ Examples::
1414
+ get_args(Dict[str, int]) == (str, int)
1415
+ get_args(int) == ()
1416
+ get_args(Union[int, Union[T, int], str][int]) == (int, str)
1417
+ get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1418
+ get_args(Callable[[], T][int]) == ([], int)
1419
+ """
1420
+ if isinstance(tp, _AnnotatedAlias):
1421
+ return (tp.__origin__,) + tp.__metadata__
1422
+ if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
1423
+ if getattr(tp, "_special", False):
1424
+ return ()
1425
+ res = tp.__args__
1426
+ if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1427
+ res = (list(res[:-1]), res[-1])
1428
+ return res
1429
+ return ()
1430
+
1431
+
1432
+ # 3.10+
1433
+ if hasattr(typing, 'TypeAlias'):
1434
+ TypeAlias = typing.TypeAlias
1435
+ # 3.9
1436
+ elif sys.version_info[:2] >= (3, 9):
1437
+ @_ExtensionsSpecialForm
1438
+ def TypeAlias(self, parameters):
1439
+ """Special marker indicating that an assignment should
1440
+ be recognized as a proper type alias definition by type
1441
+ checkers.
1442
+
1443
+ For example::
1444
+
1445
+ Predicate: TypeAlias = Callable[..., bool]
1446
+
1447
+ It's invalid when used anywhere except as in the example above.
1448
+ """
1449
+ raise TypeError(f"{self} is not subscriptable")
1450
+ # 3.7-3.8
1451
+ else:
1452
+ TypeAlias = _ExtensionsSpecialForm(
1453
+ 'TypeAlias',
1454
+ doc="""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
1463
+ above."""
1464
+ )
1465
+
1466
+
1467
+ def _set_default(type_param, default):
1468
+ if isinstance(default, (tuple, list)):
1469
+ type_param.__default__ = tuple((typing._type_check(d, "Default must be a type")
1470
+ for d in default))
1471
+ elif default != _marker:
1472
+ type_param.__default__ = typing._type_check(default, "Default must be a type")
1473
+ else:
1474
+ type_param.__default__ = None
1475
+
1476
+
1477
+ def _set_module(typevarlike):
1478
+ # for pickling:
1479
+ def_mod = _caller(depth=3)
1480
+ if def_mod != 'typing_extensions':
1481
+ typevarlike.__module__ = def_mod
1482
+
1483
+
1484
+ class _DefaultMixin:
1485
+ """Mixin for TypeVarLike defaults."""
1486
+
1487
+ __slots__ = ()
1488
+ __init__ = _set_default
1489
+
1490
+
1491
+ # Classes using this metaclass must provide a _backported_typevarlike ClassVar
1492
+ class _TypeVarLikeMeta(type):
1493
+ def __instancecheck__(cls, __instance: Any) -> bool:
1494
+ return isinstance(__instance, cls._backported_typevarlike)
1495
+
1496
+
1497
+ # Add default and infer_variance parameters from PEP 696 and 695
1498
+ class TypeVar(metaclass=_TypeVarLikeMeta):
1499
+ """Type variable."""
1500
+
1501
+ _backported_typevarlike = typing.TypeVar
1502
+
1503
+ def __new__(cls, name, *constraints, bound=None,
1504
+ covariant=False, contravariant=False,
1505
+ default=_marker, infer_variance=False):
1506
+ if hasattr(typing, "TypeAliasType"):
1507
+ # PEP 695 implemented, can pass infer_variance to typing.TypeVar
1508
+ typevar = typing.TypeVar(name, *constraints, bound=bound,
1509
+ covariant=covariant, contravariant=contravariant,
1510
+ infer_variance=infer_variance)
1511
+ else:
1512
+ typevar = typing.TypeVar(name, *constraints, bound=bound,
1513
+ covariant=covariant, contravariant=contravariant)
1514
+ if infer_variance and (covariant or contravariant):
1515
+ raise ValueError("Variance cannot be specified with infer_variance.")
1516
+ typevar.__infer_variance__ = infer_variance
1517
+ _set_default(typevar, default)
1518
+ _set_module(typevar)
1519
+ return typevar
1520
+
1521
+ def __init_subclass__(cls) -> None:
1522
+ raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
1523
+
1524
+
1525
+ # Python 3.10+ has PEP 612
1526
+ if hasattr(typing, 'ParamSpecArgs'):
1527
+ ParamSpecArgs = typing.ParamSpecArgs
1528
+ ParamSpecKwargs = typing.ParamSpecKwargs
1529
+ # 3.7-3.9
1530
+ else:
1531
+ class _Immutable:
1532
+ """Mixin to indicate that object should not be copied."""
1533
+ __slots__ = ()
1534
+
1535
+ def __copy__(self):
1536
+ return self
1537
+
1538
+ def __deepcopy__(self, memo):
1539
+ return self
1540
+
1541
+ class ParamSpecArgs(_Immutable):
1542
+ """The args for a ParamSpec object.
1543
+
1544
+ Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1545
+
1546
+ ParamSpecArgs objects have a reference back to their ParamSpec:
1547
+
1548
+ P.args.__origin__ is P
1549
+
1550
+ This type is meant for runtime introspection and has no special meaning to
1551
+ static type checkers.
1552
+ """
1553
+ def __init__(self, origin):
1554
+ self.__origin__ = origin
1555
+
1556
+ def __repr__(self):
1557
+ return f"{self.__origin__.__name__}.args"
1558
+
1559
+ def __eq__(self, other):
1560
+ if not isinstance(other, ParamSpecArgs):
1561
+ return NotImplemented
1562
+ return self.__origin__ == other.__origin__
1563
+
1564
+ class ParamSpecKwargs(_Immutable):
1565
+ """The kwargs for a ParamSpec object.
1566
+
1567
+ Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1568
+
1569
+ ParamSpecKwargs objects have a reference back to their ParamSpec:
1570
+
1571
+ P.kwargs.__origin__ is P
1572
+
1573
+ This type is meant for runtime introspection and has no special meaning to
1574
+ static type checkers.
1575
+ """
1576
+ def __init__(self, origin):
1577
+ self.__origin__ = origin
1578
+
1579
+ def __repr__(self):
1580
+ return f"{self.__origin__.__name__}.kwargs"
1581
+
1582
+ def __eq__(self, other):
1583
+ if not isinstance(other, ParamSpecKwargs):
1584
+ return NotImplemented
1585
+ return self.__origin__ == other.__origin__
1586
+
1587
+ # 3.10+
1588
+ if hasattr(typing, 'ParamSpec'):
1589
+
1590
+ # Add default parameter - PEP 696
1591
+ class ParamSpec(metaclass=_TypeVarLikeMeta):
1592
+ """Parameter specification."""
1593
+
1594
+ _backported_typevarlike = typing.ParamSpec
1595
+
1596
+ def __new__(cls, name, *, bound=None,
1597
+ covariant=False, contravariant=False,
1598
+ infer_variance=False, default=_marker):
1599
+ if hasattr(typing, "TypeAliasType"):
1600
+ # PEP 695 implemented, can pass infer_variance to typing.TypeVar
1601
+ paramspec = typing.ParamSpec(name, bound=bound,
1602
+ covariant=covariant,
1603
+ contravariant=contravariant,
1604
+ infer_variance=infer_variance)
1605
+ else:
1606
+ paramspec = typing.ParamSpec(name, bound=bound,
1607
+ covariant=covariant,
1608
+ contravariant=contravariant)
1609
+ paramspec.__infer_variance__ = infer_variance
1610
+
1611
+ _set_default(paramspec, default)
1612
+ _set_module(paramspec)
1613
+ return paramspec
1614
+
1615
+ def __init_subclass__(cls) -> None:
1616
+ raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
1617
+
1618
+ # 3.7-3.9
1619
+ else:
1620
+
1621
+ # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1622
+ class ParamSpec(list, _DefaultMixin):
1623
+ """Parameter specification variable.
1624
+
1625
+ Usage::
1626
+
1627
+ P = ParamSpec('P')
1628
+
1629
+ Parameter specification variables exist primarily for the benefit of static
1630
+ type checkers. They are used to forward the parameter types of one
1631
+ callable to another callable, a pattern commonly found in higher order
1632
+ functions and decorators. They are only valid when used in ``Concatenate``,
1633
+ or s the first argument to ``Callable``. In Python 3.10 and higher,
1634
+ they are also supported in user-defined Generics at runtime.
1635
+ See class Generic for more information on generic types. An
1636
+ example for annotating a decorator::
1637
+
1638
+ T = TypeVar('T')
1639
+ P = ParamSpec('P')
1640
+
1641
+ def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1642
+ '''A type-safe decorator to add logging to a function.'''
1643
+ def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1644
+ logging.info(f'{f.__name__} was called')
1645
+ return f(*args, **kwargs)
1646
+ return inner
1647
+
1648
+ @add_logging
1649
+ def add_two(x: float, y: float) -> float:
1650
+ '''Add two numbers together.'''
1651
+ return x + y
1652
+
1653
+ Parameter specification variables defined with covariant=True or
1654
+ contravariant=True can be used to declare covariant or contravariant
1655
+ generic types. These keyword arguments are valid, but their actual semantics
1656
+ are yet to be decided. See PEP 612 for details.
1657
+
1658
+ Parameter specification variables can be introspected. e.g.:
1659
+
1660
+ P.__name__ == 'T'
1661
+ P.__bound__ == None
1662
+ P.__covariant__ == False
1663
+ P.__contravariant__ == False
1664
+
1665
+ Note that only parameter specification variables defined in global scope can
1666
+ be pickled.
1667
+ """
1668
+
1669
+ # Trick Generic __parameters__.
1670
+ __class__ = typing.TypeVar
1671
+
1672
+ @property
1673
+ def args(self):
1674
+ return ParamSpecArgs(self)
1675
+
1676
+ @property
1677
+ def kwargs(self):
1678
+ return ParamSpecKwargs(self)
1679
+
1680
+ def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1681
+ infer_variance=False, default=_marker):
1682
+ super().__init__([self])
1683
+ self.__name__ = name
1684
+ self.__covariant__ = bool(covariant)
1685
+ self.__contravariant__ = bool(contravariant)
1686
+ self.__infer_variance__ = bool(infer_variance)
1687
+ if bound:
1688
+ self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1689
+ else:
1690
+ self.__bound__ = None
1691
+ _DefaultMixin.__init__(self, default)
1692
+
1693
+ # for pickling:
1694
+ def_mod = _caller()
1695
+ if def_mod != 'typing_extensions':
1696
+ self.__module__ = def_mod
1697
+
1698
+ def __repr__(self):
1699
+ if self.__infer_variance__:
1700
+ prefix = ''
1701
+ elif self.__covariant__:
1702
+ prefix = '+'
1703
+ elif self.__contravariant__:
1704
+ prefix = '-'
1705
+ else:
1706
+ prefix = '~'
1707
+ return prefix + self.__name__
1708
+
1709
+ def __hash__(self):
1710
+ return object.__hash__(self)
1711
+
1712
+ def __eq__(self, other):
1713
+ return self is other
1714
+
1715
+ def __reduce__(self):
1716
+ return self.__name__
1717
+
1718
+ # Hack to get typing._type_check to pass.
1719
+ def __call__(self, *args, **kwargs):
1720
+ pass
1721
+
1722
+
1723
+ # 3.7-3.9
1724
+ if not hasattr(typing, 'Concatenate'):
1725
+ # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1726
+ class _ConcatenateGenericAlias(list):
1727
+
1728
+ # Trick Generic into looking into this for __parameters__.
1729
+ __class__ = typing._GenericAlias
1730
+
1731
+ # Flag in 3.8.
1732
+ _special = False
1733
+
1734
+ def __init__(self, origin, args):
1735
+ super().__init__(args)
1736
+ self.__origin__ = origin
1737
+ self.__args__ = args
1738
+
1739
+ def __repr__(self):
1740
+ _type_repr = typing._type_repr
1741
+ return (f'{_type_repr(self.__origin__)}'
1742
+ f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1743
+
1744
+ def __hash__(self):
1745
+ return hash((self.__origin__, self.__args__))
1746
+
1747
+ # Hack to get typing._type_check to pass in Generic.
1748
+ def __call__(self, *args, **kwargs):
1749
+ pass
1750
+
1751
+ @property
1752
+ def __parameters__(self):
1753
+ return tuple(
1754
+ tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1755
+ )
1756
+
1757
+
1758
+ # 3.7-3.9
1759
+ @typing._tp_cache
1760
+ def _concatenate_getitem(self, parameters):
1761
+ if parameters == ():
1762
+ raise TypeError("Cannot take a Concatenate of no types.")
1763
+ if not isinstance(parameters, tuple):
1764
+ parameters = (parameters,)
1765
+ if not isinstance(parameters[-1], ParamSpec):
1766
+ raise TypeError("The last parameter to Concatenate should be a "
1767
+ "ParamSpec variable.")
1768
+ msg = "Concatenate[arg, ...]: each arg must be a type."
1769
+ parameters = tuple(typing._type_check(p, msg) for p in parameters)
1770
+ return _ConcatenateGenericAlias(self, parameters)
1771
+
1772
+
1773
+ # 3.10+
1774
+ if hasattr(typing, 'Concatenate'):
1775
+ Concatenate = typing.Concatenate
1776
+ _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811
1777
+ # 3.9
1778
+ elif sys.version_info[:2] >= (3, 9):
1779
+ @_ExtensionsSpecialForm
1780
+ def Concatenate(self, parameters):
1781
+ """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1782
+ higher order function which adds, removes or transforms parameters of a
1783
+ callable.
1784
+
1785
+ For example::
1786
+
1787
+ Callable[Concatenate[int, P], int]
1788
+
1789
+ See PEP 612 for detailed information.
1790
+ """
1791
+ return _concatenate_getitem(self, parameters)
1792
+ # 3.7-8
1793
+ else:
1794
+ class _ConcatenateForm(_ExtensionsSpecialForm, _root=True):
1795
+ def __getitem__(self, parameters):
1796
+ return _concatenate_getitem(self, parameters)
1797
+
1798
+ Concatenate = _ConcatenateForm(
1799
+ 'Concatenate',
1800
+ doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1801
+ higher order function which adds, removes or transforms parameters of a
1802
+ callable.
1803
+
1804
+ For example::
1805
+
1806
+ Callable[Concatenate[int, P], int]
1807
+
1808
+ See PEP 612 for detailed information.
1809
+ """)
1810
+
1811
+ # 3.10+
1812
+ if hasattr(typing, 'TypeGuard'):
1813
+ TypeGuard = typing.TypeGuard
1814
+ # 3.9
1815
+ elif sys.version_info[:2] >= (3, 9):
1816
+ @_ExtensionsSpecialForm
1817
+ def TypeGuard(self, parameters):
1818
+ """Special typing form used to annotate the return type of a user-defined
1819
+ type guard function. ``TypeGuard`` only accepts a single type argument.
1820
+ At runtime, functions marked this way should return a boolean.
1821
+
1822
+ ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1823
+ type checkers to determine a more precise type of an expression within a
1824
+ program's code flow. Usually type narrowing is done by analyzing
1825
+ conditional code flow and applying the narrowing to a block of code. The
1826
+ conditional expression here is sometimes referred to as a "type guard".
1827
+
1828
+ Sometimes it would be convenient to use a user-defined boolean function
1829
+ as a type guard. Such a function should use ``TypeGuard[...]`` as its
1830
+ return type to alert static type checkers to this intention.
1831
+
1832
+ Using ``-> TypeGuard`` tells the static type checker that for a given
1833
+ function:
1834
+
1835
+ 1. The return value is a boolean.
1836
+ 2. If the return value is ``True``, the type of its argument
1837
+ is the type inside ``TypeGuard``.
1838
+
1839
+ For example::
1840
+
1841
+ def is_str(val: Union[str, float]):
1842
+ # "isinstance" type guard
1843
+ if isinstance(val, str):
1844
+ # Type of ``val`` is narrowed to ``str``
1845
+ ...
1846
+ else:
1847
+ # Else, type of ``val`` is narrowed to ``float``.
1848
+ ...
1849
+
1850
+ Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1851
+ form of ``TypeA`` (it can even be a wider form) and this may lead to
1852
+ type-unsafe results. The main reason is to allow for things like
1853
+ narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1854
+ a subtype of the former, since ``List`` is invariant. The responsibility of
1855
+ writing type-safe type guards is left to the user.
1856
+
1857
+ ``TypeGuard`` also works with type variables. For more information, see
1858
+ PEP 647 (User-Defined Type Guards).
1859
+ """
1860
+ item = typing._type_check(parameters, f'{self} accepts only a single type.')
1861
+ return typing._GenericAlias(self, (item,))
1862
+ # 3.7-3.8
1863
+ else:
1864
+ class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
1865
+ def __getitem__(self, parameters):
1866
+ item = typing._type_check(parameters,
1867
+ f'{self._name} accepts only a single type')
1868
+ return typing._GenericAlias(self, (item,))
1869
+
1870
+ TypeGuard = _TypeGuardForm(
1871
+ 'TypeGuard',
1872
+ doc="""Special typing form used to annotate the return type of a user-defined
1873
+ type guard function. ``TypeGuard`` only accepts a single type argument.
1874
+ At runtime, functions marked this way should return a boolean.
1875
+
1876
+ ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1877
+ type checkers to determine a more precise type of an expression within a
1878
+ program's code flow. Usually type narrowing is done by analyzing
1879
+ conditional code flow and applying the narrowing to a block of code. The
1880
+ conditional expression here is sometimes referred to as a "type guard".
1881
+
1882
+ Sometimes it would be convenient to use a user-defined boolean function
1883
+ as a type guard. Such a function should use ``TypeGuard[...]`` as its
1884
+ return type to alert static type checkers to this intention.
1885
+
1886
+ Using ``-> TypeGuard`` tells the static type checker that for a given
1887
+ function:
1888
+
1889
+ 1. The return value is a boolean.
1890
+ 2. If the return value is ``True``, the type of its argument
1891
+ is the type inside ``TypeGuard``.
1892
+
1893
+ For example::
1894
+
1895
+ def is_str(val: Union[str, float]):
1896
+ # "isinstance" type guard
1897
+ if isinstance(val, str):
1898
+ # Type of ``val`` is narrowed to ``str``
1899
+ ...
1900
+ else:
1901
+ # Else, type of ``val`` is narrowed to ``float``.
1902
+ ...
1903
+
1904
+ Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1905
+ form of ``TypeA`` (it can even be a wider form) and this may lead to
1906
+ type-unsafe results. The main reason is to allow for things like
1907
+ narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1908
+ a subtype of the former, since ``List`` is invariant. The responsibility of
1909
+ writing type-safe type guards is left to the user.
1910
+
1911
+ ``TypeGuard`` also works with type variables. For more information, see
1912
+ PEP 647 (User-Defined Type Guards).
1913
+ """)
1914
+
1915
+
1916
+ # Vendored from cpython typing._SpecialFrom
1917
+ class _SpecialForm(typing._Final, _root=True):
1918
+ __slots__ = ('_name', '__doc__', '_getitem')
1919
+
1920
+ def __init__(self, getitem):
1921
+ self._getitem = getitem
1922
+ self._name = getitem.__name__
1923
+ self.__doc__ = getitem.__doc__
1924
+
1925
+ def __getattr__(self, item):
1926
+ if item in {'__name__', '__qualname__'}:
1927
+ return self._name
1928
+
1929
+ raise AttributeError(item)
1930
+
1931
+ def __mro_entries__(self, bases):
1932
+ raise TypeError(f"Cannot subclass {self!r}")
1933
+
1934
+ def __repr__(self):
1935
+ return f'typing_extensions.{self._name}'
1936
+
1937
+ def __reduce__(self):
1938
+ return self._name
1939
+
1940
+ def __call__(self, *args, **kwds):
1941
+ raise TypeError(f"Cannot instantiate {self!r}")
1942
+
1943
+ def __or__(self, other):
1944
+ return typing.Union[self, other]
1945
+
1946
+ def __ror__(self, other):
1947
+ return typing.Union[other, self]
1948
+
1949
+ def __instancecheck__(self, obj):
1950
+ raise TypeError(f"{self} cannot be used with isinstance()")
1951
+
1952
+ def __subclasscheck__(self, cls):
1953
+ raise TypeError(f"{self} cannot be used with issubclass()")
1954
+
1955
+ @typing._tp_cache
1956
+ def __getitem__(self, parameters):
1957
+ return self._getitem(self, parameters)
1958
+
1959
+
1960
+ if hasattr(typing, "LiteralString"):
1961
+ LiteralString = typing.LiteralString
1962
+ else:
1963
+ @_SpecialForm
1964
+ def LiteralString(self, params):
1965
+ """Represents an arbitrary literal string.
1966
+
1967
+ Example::
1968
+
1969
+ from metaflow._vendor.typing_extensions import LiteralString
1970
+
1971
+ def query(sql: LiteralString) -> ...:
1972
+ ...
1973
+
1974
+ query("SELECT * FROM table") # ok
1975
+ query(f"SELECT * FROM {input()}") # not ok
1976
+
1977
+ See PEP 675 for details.
1978
+
1979
+ """
1980
+ raise TypeError(f"{self} is not subscriptable")
1981
+
1982
+
1983
+ if hasattr(typing, "Self"):
1984
+ Self = typing.Self
1985
+ else:
1986
+ @_SpecialForm
1987
+ def Self(self, params):
1988
+ """Used to spell the type of "self" in classes.
1989
+
1990
+ Example::
1991
+
1992
+ from typing import Self
1993
+
1994
+ class ReturnsSelf:
1995
+ def parse(self, data: bytes) -> Self:
1996
+ ...
1997
+ return self
1998
+
1999
+ """
2000
+
2001
+ raise TypeError(f"{self} is not subscriptable")
2002
+
2003
+
2004
+ if hasattr(typing, "Never"):
2005
+ Never = typing.Never
2006
+ else:
2007
+ @_SpecialForm
2008
+ def Never(self, params):
2009
+ """The bottom type, a type that has no members.
2010
+
2011
+ This can be used to define a function that should never be
2012
+ called, or a function that never returns::
2013
+
2014
+ from metaflow._vendor.typing_extensions import Never
2015
+
2016
+ def never_call_me(arg: Never) -> None:
2017
+ pass
2018
+
2019
+ def int_or_str(arg: int | str) -> None:
2020
+ never_call_me(arg) # type checker error
2021
+ match arg:
2022
+ case int():
2023
+ print("It's an int")
2024
+ case str():
2025
+ print("It's a str")
2026
+ case _:
2027
+ never_call_me(arg) # ok, arg is of type Never
2028
+
2029
+ """
2030
+
2031
+ raise TypeError(f"{self} is not subscriptable")
2032
+
2033
+
2034
+ if hasattr(typing, 'Required'):
2035
+ Required = typing.Required
2036
+ NotRequired = typing.NotRequired
2037
+ elif sys.version_info[:2] >= (3, 9):
2038
+ @_ExtensionsSpecialForm
2039
+ def Required(self, parameters):
2040
+ """A special typing construct to mark a key of a total=False TypedDict
2041
+ as required. For example:
2042
+
2043
+ class Movie(TypedDict, total=False):
2044
+ title: Required[str]
2045
+ year: int
2046
+
2047
+ m = Movie(
2048
+ title='The Matrix', # typechecker error if key is omitted
2049
+ year=1999,
2050
+ )
2051
+
2052
+ There is no runtime checking that a required key is actually provided
2053
+ when instantiating a related TypedDict.
2054
+ """
2055
+ item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2056
+ return typing._GenericAlias(self, (item,))
2057
+
2058
+ @_ExtensionsSpecialForm
2059
+ def NotRequired(self, parameters):
2060
+ """A special typing construct to mark a key of a TypedDict as
2061
+ potentially missing. For example:
2062
+
2063
+ class Movie(TypedDict):
2064
+ title: str
2065
+ year: NotRequired[int]
2066
+
2067
+ m = Movie(
2068
+ title='The Matrix', # typechecker error if key is omitted
2069
+ year=1999,
2070
+ )
2071
+ """
2072
+ item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2073
+ return typing._GenericAlias(self, (item,))
2074
+
2075
+ else:
2076
+ class _RequiredForm(_ExtensionsSpecialForm, _root=True):
2077
+ def __getitem__(self, parameters):
2078
+ item = typing._type_check(parameters,
2079
+ f'{self._name} accepts only a single type.')
2080
+ return typing._GenericAlias(self, (item,))
2081
+
2082
+ Required = _RequiredForm(
2083
+ 'Required',
2084
+ doc="""A special typing construct to mark a key of a total=False TypedDict
2085
+ as required. For example:
2086
+
2087
+ class Movie(TypedDict, total=False):
2088
+ title: Required[str]
2089
+ year: int
2090
+
2091
+ m = Movie(
2092
+ title='The Matrix', # typechecker error if key is omitted
2093
+ year=1999,
2094
+ )
2095
+
2096
+ There is no runtime checking that a required key is actually provided
2097
+ when instantiating a related TypedDict.
2098
+ """)
2099
+ NotRequired = _RequiredForm(
2100
+ 'NotRequired',
2101
+ doc="""A special typing construct to mark a key of a TypedDict as
2102
+ potentially missing. For example:
2103
+
2104
+ class Movie(TypedDict):
2105
+ title: str
2106
+ year: NotRequired[int]
2107
+
2108
+ m = Movie(
2109
+ title='The Matrix', # typechecker error if key is omitted
2110
+ year=1999,
2111
+ )
2112
+ """)
2113
+
2114
+
2115
+ _UNPACK_DOC = """\
2116
+ Type unpack operator.
2117
+
2118
+ The type unpack operator takes the child types from some container type,
2119
+ such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
2120
+ example:
2121
+
2122
+ # For some generic class `Foo`:
2123
+ Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
2124
+
2125
+ Ts = TypeVarTuple('Ts')
2126
+ # Specifies that `Bar` is generic in an arbitrary number of types.
2127
+ # (Think of `Ts` as a tuple of an arbitrary number of individual
2128
+ # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
2129
+ # `Generic[]`.)
2130
+ class Bar(Generic[Unpack[Ts]]): ...
2131
+ Bar[int] # Valid
2132
+ Bar[int, str] # Also valid
2133
+
2134
+ From Python 3.11, this can also be done using the `*` operator:
2135
+
2136
+ Foo[*tuple[int, str]]
2137
+ class Bar(Generic[*Ts]): ...
2138
+
2139
+ The operator can also be used along with a `TypedDict` to annotate
2140
+ `**kwargs` in a function signature. For instance:
2141
+
2142
+ class Movie(TypedDict):
2143
+ name: str
2144
+ year: int
2145
+
2146
+ # This function expects two keyword arguments - *name* of type `str` and
2147
+ # *year* of type `int`.
2148
+ def foo(**kwargs: Unpack[Movie]): ...
2149
+
2150
+ Note that there is only some runtime checking of this operator. Not
2151
+ everything the runtime allows may be accepted by static type checkers.
2152
+
2153
+ For more information, see PEP 646 and PEP 692.
2154
+ """
2155
+
2156
+
2157
+ if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
2158
+ Unpack = typing.Unpack
2159
+
2160
+ def _is_unpack(obj):
2161
+ return get_origin(obj) is Unpack
2162
+
2163
+ elif sys.version_info[:2] >= (3, 9):
2164
+ class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
2165
+ def __init__(self, getitem):
2166
+ super().__init__(getitem)
2167
+ self.__doc__ = _UNPACK_DOC
2168
+
2169
+ class _UnpackAlias(typing._GenericAlias, _root=True):
2170
+ __class__ = typing.TypeVar
2171
+
2172
+ @_UnpackSpecialForm
2173
+ def Unpack(self, parameters):
2174
+ item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2175
+ return _UnpackAlias(self, (item,))
2176
+
2177
+ def _is_unpack(obj):
2178
+ return isinstance(obj, _UnpackAlias)
2179
+
2180
+ else:
2181
+ class _UnpackAlias(typing._GenericAlias, _root=True):
2182
+ __class__ = typing.TypeVar
2183
+
2184
+ class _UnpackForm(_ExtensionsSpecialForm, _root=True):
2185
+ def __getitem__(self, parameters):
2186
+ item = typing._type_check(parameters,
2187
+ f'{self._name} accepts only a single type.')
2188
+ return _UnpackAlias(self, (item,))
2189
+
2190
+ Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
2191
+
2192
+ def _is_unpack(obj):
2193
+ return isinstance(obj, _UnpackAlias)
2194
+
2195
+
2196
+ if hasattr(typing, "TypeVarTuple"): # 3.11+
2197
+
2198
+ # Add default parameter - PEP 696
2199
+ class TypeVarTuple(metaclass=_TypeVarLikeMeta):
2200
+ """Type variable tuple."""
2201
+
2202
+ _backported_typevarlike = typing.TypeVarTuple
2203
+
2204
+ def __new__(cls, name, *, default=_marker):
2205
+ tvt = typing.TypeVarTuple(name)
2206
+ _set_default(tvt, default)
2207
+ _set_module(tvt)
2208
+ return tvt
2209
+
2210
+ def __init_subclass__(self, *args, **kwds):
2211
+ raise TypeError("Cannot subclass special typing classes")
2212
+
2213
+ else:
2214
+ class TypeVarTuple(_DefaultMixin):
2215
+ """Type variable tuple.
2216
+
2217
+ Usage::
2218
+
2219
+ Ts = TypeVarTuple('Ts')
2220
+
2221
+ In the same way that a normal type variable is a stand-in for a single
2222
+ type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
2223
+ type such as ``Tuple[int, str]``.
2224
+
2225
+ Type variable tuples can be used in ``Generic`` declarations.
2226
+ Consider the following example::
2227
+
2228
+ class Array(Generic[*Ts]): ...
2229
+
2230
+ The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
2231
+ where ``T1`` and ``T2`` are type variables. To use these type variables
2232
+ as type parameters of ``Array``, we must *unpack* the type variable tuple using
2233
+ the star operator: ``*Ts``. The signature of ``Array`` then behaves
2234
+ as if we had simply written ``class Array(Generic[T1, T2]): ...``.
2235
+ In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
2236
+ us to parameterise the class with an *arbitrary* number of type parameters.
2237
+
2238
+ Type variable tuples can be used anywhere a normal ``TypeVar`` can.
2239
+ This includes class definitions, as shown above, as well as function
2240
+ signatures and variable annotations::
2241
+
2242
+ class Array(Generic[*Ts]):
2243
+
2244
+ def __init__(self, shape: Tuple[*Ts]):
2245
+ self._shape: Tuple[*Ts] = shape
2246
+
2247
+ def get_shape(self) -> Tuple[*Ts]:
2248
+ return self._shape
2249
+
2250
+ shape = (Height(480), Width(640))
2251
+ x: Array[Height, Width] = Array(shape)
2252
+ y = abs(x) # Inferred type is Array[Height, Width]
2253
+ z = x + x # ... is Array[Height, Width]
2254
+ x.get_shape() # ... is tuple[Height, Width]
2255
+
2256
+ """
2257
+
2258
+ # Trick Generic __parameters__.
2259
+ __class__ = typing.TypeVar
2260
+
2261
+ def __iter__(self):
2262
+ yield self.__unpacked__
2263
+
2264
+ def __init__(self, name, *, default=_marker):
2265
+ self.__name__ = name
2266
+ _DefaultMixin.__init__(self, default)
2267
+
2268
+ # for pickling:
2269
+ def_mod = _caller()
2270
+ if def_mod != 'typing_extensions':
2271
+ self.__module__ = def_mod
2272
+
2273
+ self.__unpacked__ = Unpack[self]
2274
+
2275
+ def __repr__(self):
2276
+ return self.__name__
2277
+
2278
+ def __hash__(self):
2279
+ return object.__hash__(self)
2280
+
2281
+ def __eq__(self, other):
2282
+ return self is other
2283
+
2284
+ def __reduce__(self):
2285
+ return self.__name__
2286
+
2287
+ def __init_subclass__(self, *args, **kwds):
2288
+ if '_root' not in kwds:
2289
+ raise TypeError("Cannot subclass special typing classes")
2290
+
2291
+
2292
+ if hasattr(typing, "reveal_type"):
2293
+ reveal_type = typing.reveal_type
2294
+ else:
2295
+ def reveal_type(__obj: T) -> T:
2296
+ """Reveal the inferred type of a variable.
2297
+
2298
+ When a static type checker encounters a call to ``reveal_type()``,
2299
+ it will emit the inferred type of the argument::
2300
+
2301
+ x: int = 1
2302
+ reveal_type(x)
2303
+
2304
+ Running a static type checker (e.g., ``mypy``) on this example
2305
+ will produce output similar to 'Revealed type is "builtins.int"'.
2306
+
2307
+ At runtime, the function prints the runtime type of the
2308
+ argument and returns it unchanged.
2309
+
2310
+ """
2311
+ print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr)
2312
+ return __obj
2313
+
2314
+
2315
+ if hasattr(typing, "assert_never"):
2316
+ assert_never = typing.assert_never
2317
+ else:
2318
+ def assert_never(__arg: Never) -> Never:
2319
+ """Assert to the type checker that a line of code is unreachable.
2320
+
2321
+ Example::
2322
+
2323
+ def int_or_str(arg: int | str) -> None:
2324
+ match arg:
2325
+ case int():
2326
+ print("It's an int")
2327
+ case str():
2328
+ print("It's a str")
2329
+ case _:
2330
+ assert_never(arg)
2331
+
2332
+ If a type checker finds that a call to assert_never() is
2333
+ reachable, it will emit an error.
2334
+
2335
+ At runtime, this throws an exception when called.
2336
+
2337
+ """
2338
+ raise AssertionError("Expected code to be unreachable")
2339
+
2340
+
2341
+ if sys.version_info >= (3, 12):
2342
+ # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
2343
+ dataclass_transform = typing.dataclass_transform
2344
+ else:
2345
+ def dataclass_transform(
2346
+ *,
2347
+ eq_default: bool = True,
2348
+ order_default: bool = False,
2349
+ kw_only_default: bool = False,
2350
+ frozen_default: bool = False,
2351
+ field_specifiers: typing.Tuple[
2352
+ typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
2353
+ ...
2354
+ ] = (),
2355
+ **kwargs: typing.Any,
2356
+ ) -> typing.Callable[[T], T]:
2357
+ """Decorator that marks a function, class, or metaclass as providing
2358
+ dataclass-like behavior.
2359
+
2360
+ Example:
2361
+
2362
+ from metaflow._vendor.typing_extensions import dataclass_transform
2363
+
2364
+ _T = TypeVar("_T")
2365
+
2366
+ # Used on a decorator function
2367
+ @dataclass_transform()
2368
+ def create_model(cls: type[_T]) -> type[_T]:
2369
+ ...
2370
+ return cls
2371
+
2372
+ @create_model
2373
+ class CustomerModel:
2374
+ id: int
2375
+ name: str
2376
+
2377
+ # Used on a base class
2378
+ @dataclass_transform()
2379
+ class ModelBase: ...
2380
+
2381
+ class CustomerModel(ModelBase):
2382
+ id: int
2383
+ name: str
2384
+
2385
+ # Used on a metaclass
2386
+ @dataclass_transform()
2387
+ class ModelMeta(type): ...
2388
+
2389
+ class ModelBase(metaclass=ModelMeta): ...
2390
+
2391
+ class CustomerModel(ModelBase):
2392
+ id: int
2393
+ name: str
2394
+
2395
+ Each of the ``CustomerModel`` classes defined in this example will now
2396
+ behave similarly to a dataclass created with the ``@dataclasses.dataclass``
2397
+ decorator. For example, the type checker will synthesize an ``__init__``
2398
+ method.
2399
+
2400
+ The arguments to this decorator can be used to customize this behavior:
2401
+ - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
2402
+ True or False if it is omitted by the caller.
2403
+ - ``order_default`` indicates whether the ``order`` parameter is
2404
+ assumed to be True or False if it is omitted by the caller.
2405
+ - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
2406
+ assumed to be True or False if it is omitted by the caller.
2407
+ - ``frozen_default`` indicates whether the ``frozen`` parameter is
2408
+ assumed to be True or False if it is omitted by the caller.
2409
+ - ``field_specifiers`` specifies a static list of supported classes
2410
+ or functions that describe fields, similar to ``dataclasses.field()``.
2411
+
2412
+ At runtime, this decorator records its arguments in the
2413
+ ``__dataclass_transform__`` attribute on the decorated object.
2414
+
2415
+ See PEP 681 for details.
2416
+
2417
+ """
2418
+ def decorator(cls_or_fn):
2419
+ cls_or_fn.__dataclass_transform__ = {
2420
+ "eq_default": eq_default,
2421
+ "order_default": order_default,
2422
+ "kw_only_default": kw_only_default,
2423
+ "frozen_default": frozen_default,
2424
+ "field_specifiers": field_specifiers,
2425
+ "kwargs": kwargs,
2426
+ }
2427
+ return cls_or_fn
2428
+ return decorator
2429
+
2430
+
2431
+ if hasattr(typing, "override"):
2432
+ override = typing.override
2433
+ else:
2434
+ _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
2435
+
2436
+ def override(__arg: _F) -> _F:
2437
+ """Indicate that a method is intended to override a method in a base class.
2438
+
2439
+ Usage:
2440
+
2441
+ class Base:
2442
+ def method(self) -> None: ...
2443
+ pass
2444
+
2445
+ class Child(Base):
2446
+ @override
2447
+ def method(self) -> None:
2448
+ super().method()
2449
+
2450
+ When this decorator is applied to a method, the type checker will
2451
+ validate that it overrides a method with the same name on a base class.
2452
+ This helps prevent bugs that may occur when a base class is changed
2453
+ without an equivalent change to a child class.
2454
+
2455
+ There is no runtime checking of these properties. The decorator
2456
+ sets the ``__override__`` attribute to ``True`` on the decorated object
2457
+ to allow runtime introspection.
2458
+
2459
+ See PEP 698 for details.
2460
+
2461
+ """
2462
+ try:
2463
+ __arg.__override__ = True
2464
+ except (AttributeError, TypeError):
2465
+ # Skip the attribute silently if it is not writable.
2466
+ # AttributeError happens if the object has __slots__ or a
2467
+ # read-only property, TypeError if it's a builtin class.
2468
+ pass
2469
+ return __arg
2470
+
2471
+
2472
+ if hasattr(typing, "deprecated"):
2473
+ deprecated = typing.deprecated
2474
+ else:
2475
+ _T = typing.TypeVar("_T")
2476
+
2477
+ def deprecated(
2478
+ __msg: str,
2479
+ *,
2480
+ category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
2481
+ stacklevel: int = 1,
2482
+ ) -> typing.Callable[[_T], _T]:
2483
+ """Indicate that a class, function or overload is deprecated.
2484
+
2485
+ Usage:
2486
+
2487
+ @deprecated("Use B instead")
2488
+ class A:
2489
+ pass
2490
+
2491
+ @deprecated("Use g instead")
2492
+ def f():
2493
+ pass
2494
+
2495
+ @overload
2496
+ @deprecated("int support is deprecated")
2497
+ def g(x: int) -> int: ...
2498
+ @overload
2499
+ def g(x: str) -> int: ...
2500
+
2501
+ When this decorator is applied to an object, the type checker
2502
+ will generate a diagnostic on usage of the deprecated object.
2503
+
2504
+ The warning specified by ``category`` will be emitted on use
2505
+ of deprecated objects. For functions, that happens on calls;
2506
+ for classes, on instantiation. If the ``category`` is ``None``,
2507
+ no warning is emitted. The ``stacklevel`` determines where the
2508
+ warning is emitted. If it is ``1`` (the default), the warning
2509
+ is emitted at the direct caller of the deprecated object; if it
2510
+ is higher, it is emitted further up the stack.
2511
+
2512
+ The decorator sets the ``__deprecated__``
2513
+ attribute on the decorated object to the deprecation message
2514
+ passed to the decorator. If applied to an overload, the decorator
2515
+ must be after the ``@overload`` decorator for the attribute to
2516
+ exist on the overload as returned by ``get_overloads()``.
2517
+
2518
+ See PEP 702 for details.
2519
+
2520
+ """
2521
+ def decorator(__arg: _T) -> _T:
2522
+ if category is None:
2523
+ __arg.__deprecated__ = __msg
2524
+ return __arg
2525
+ elif isinstance(__arg, type):
2526
+ original_new = __arg.__new__
2527
+ has_init = __arg.__init__ is not object.__init__
2528
+
2529
+ @functools.wraps(original_new)
2530
+ def __new__(cls, *args, **kwargs):
2531
+ warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
2532
+ if original_new is not object.__new__:
2533
+ return original_new(cls, *args, **kwargs)
2534
+ # Mirrors a similar check in object.__new__.
2535
+ elif not has_init and (args or kwargs):
2536
+ raise TypeError(f"{cls.__name__}() takes no arguments")
2537
+ else:
2538
+ return original_new(cls)
2539
+
2540
+ __arg.__new__ = staticmethod(__new__)
2541
+ __arg.__deprecated__ = __new__.__deprecated__ = __msg
2542
+ return __arg
2543
+ elif callable(__arg):
2544
+ @functools.wraps(__arg)
2545
+ def wrapper(*args, **kwargs):
2546
+ warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
2547
+ return __arg(*args, **kwargs)
2548
+
2549
+ __arg.__deprecated__ = wrapper.__deprecated__ = __msg
2550
+ return wrapper
2551
+ else:
2552
+ raise TypeError(
2553
+ "@deprecated decorator with non-None category must be applied to "
2554
+ f"a class or callable, not {__arg!r}"
2555
+ )
2556
+
2557
+ return decorator
2558
+
2559
+
2560
+ # We have to do some monkey patching to deal with the dual nature of
2561
+ # Unpack/TypeVarTuple:
2562
+ # - We want Unpack to be a kind of TypeVar so it gets accepted in
2563
+ # Generic[Unpack[Ts]]
2564
+ # - We want it to *not* be treated as a TypeVar for the purposes of
2565
+ # counting generic parameters, so that when we subscript a generic,
2566
+ # the runtime doesn't try to substitute the Unpack with the subscripted type.
2567
+ if not hasattr(typing, "TypeVarTuple"):
2568
+ typing._collect_type_vars = _collect_type_vars
2569
+ typing._check_generic = _check_generic
2570
+
2571
+
2572
+ # Backport typing.NamedTuple as it exists in Python 3.12.
2573
+ # In 3.11, the ability to define generic `NamedTuple`s was supported.
2574
+ # This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
2575
+ # On 3.12, we added __orig_bases__ to call-based NamedTuples
2576
+ # On 3.13, we deprecated kwargs-based NamedTuples
2577
+ if sys.version_info >= (3, 13):
2578
+ NamedTuple = typing.NamedTuple
2579
+ else:
2580
+ def _make_nmtuple(name, types, module, defaults=()):
2581
+ fields = [n for n, t in types]
2582
+ annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
2583
+ for n, t in types}
2584
+ nm_tpl = collections.namedtuple(name, fields,
2585
+ defaults=defaults, module=module)
2586
+ nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
2587
+ # The `_field_types` attribute was removed in 3.9;
2588
+ # in earlier versions, it is the same as the `__annotations__` attribute
2589
+ if sys.version_info < (3, 9):
2590
+ nm_tpl._field_types = annotations
2591
+ return nm_tpl
2592
+
2593
+ _prohibited_namedtuple_fields = typing._prohibited
2594
+ _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
2595
+
2596
+ class _NamedTupleMeta(type):
2597
+ def __new__(cls, typename, bases, ns):
2598
+ assert _NamedTuple in bases
2599
+ for base in bases:
2600
+ if base is not _NamedTuple and base is not typing.Generic:
2601
+ raise TypeError(
2602
+ 'can only inherit from a NamedTuple type and Generic')
2603
+ bases = tuple(tuple if base is _NamedTuple else base for base in bases)
2604
+ types = ns.get('__annotations__', {})
2605
+ default_names = []
2606
+ for field_name in types:
2607
+ if field_name in ns:
2608
+ default_names.append(field_name)
2609
+ elif default_names:
2610
+ raise TypeError(f"Non-default namedtuple field {field_name} "
2611
+ f"cannot follow default field"
2612
+ f"{'s' if len(default_names) > 1 else ''} "
2613
+ f"{', '.join(default_names)}")
2614
+ nm_tpl = _make_nmtuple(
2615
+ typename, types.items(),
2616
+ defaults=[ns[n] for n in default_names],
2617
+ module=ns['__module__']
2618
+ )
2619
+ nm_tpl.__bases__ = bases
2620
+ if typing.Generic in bases:
2621
+ if hasattr(typing, '_generic_class_getitem'): # 3.12+
2622
+ nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
2623
+ else:
2624
+ class_getitem = typing.Generic.__class_getitem__.__func__
2625
+ nm_tpl.__class_getitem__ = classmethod(class_getitem)
2626
+ # update from user namespace without overriding special namedtuple attributes
2627
+ for key in ns:
2628
+ if key in _prohibited_namedtuple_fields:
2629
+ raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2630
+ elif key not in _special_namedtuple_fields and key not in nm_tpl._fields:
2631
+ setattr(nm_tpl, key, ns[key])
2632
+ if typing.Generic in bases:
2633
+ nm_tpl.__init_subclass__()
2634
+ return nm_tpl
2635
+
2636
+ def NamedTuple(__typename, __fields=_marker, **kwargs):
2637
+ """Typed version of namedtuple.
2638
+
2639
+ Usage::
2640
+
2641
+ class Employee(NamedTuple):
2642
+ name: str
2643
+ id: int
2644
+
2645
+ This is equivalent to::
2646
+
2647
+ Employee = collections.namedtuple('Employee', ['name', 'id'])
2648
+
2649
+ The resulting class has an extra __annotations__ attribute, giving a
2650
+ dict that maps field names to types. (The field names are also in
2651
+ the _fields attribute, which is part of the namedtuple API.)
2652
+ An alternative equivalent functional syntax is also accepted::
2653
+
2654
+ Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2655
+ """
2656
+ if __fields is _marker:
2657
+ if kwargs:
2658
+ deprecated_thing = "Creating NamedTuple classes using keyword arguments"
2659
+ deprecation_msg = (
2660
+ "{name} is deprecated and will be disallowed in Python {remove}. "
2661
+ "Use the class-based or functional syntax instead."
2662
+ )
2663
+ else:
2664
+ deprecated_thing = "Failing to pass a value for the 'fields' parameter"
2665
+ example = f"`{__typename} = NamedTuple({__typename!r}, [])`"
2666
+ deprecation_msg = (
2667
+ "{name} is deprecated and will be disallowed in Python {remove}. "
2668
+ "To create a NamedTuple class with 0 fields "
2669
+ "using the functional syntax, "
2670
+ "pass an empty list, e.g. "
2671
+ ) + example + "."
2672
+ elif __fields is None:
2673
+ if kwargs:
2674
+ raise TypeError(
2675
+ "Cannot pass `None` as the 'fields' parameter "
2676
+ "and also specify fields using keyword arguments"
2677
+ )
2678
+ else:
2679
+ deprecated_thing = "Passing `None` as the 'fields' parameter"
2680
+ example = f"`{__typename} = NamedTuple({__typename!r}, [])`"
2681
+ deprecation_msg = (
2682
+ "{name} is deprecated and will be disallowed in Python {remove}. "
2683
+ "To create a NamedTuple class with 0 fields "
2684
+ "using the functional syntax, "
2685
+ "pass an empty list, e.g. "
2686
+ ) + example + "."
2687
+ elif kwargs:
2688
+ raise TypeError("Either list of fields or keywords"
2689
+ " can be provided to NamedTuple, not both")
2690
+ if __fields is _marker or __fields is None:
2691
+ warnings.warn(
2692
+ deprecation_msg.format(name=deprecated_thing, remove="3.15"),
2693
+ DeprecationWarning,
2694
+ stacklevel=2,
2695
+ )
2696
+ __fields = kwargs.items()
2697
+ nt = _make_nmtuple(__typename, __fields, module=_caller())
2698
+ nt.__orig_bases__ = (NamedTuple,)
2699
+ return nt
2700
+
2701
+ _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
2702
+
2703
+ # On 3.8+, alter the signature so that it matches typing.NamedTuple.
2704
+ # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7,
2705
+ # so just leave the signature as it is on 3.7.
2706
+ if sys.version_info >= (3, 8):
2707
+ NamedTuple.__text_signature__ = '(typename, fields=None, /, **kwargs)'
2708
+
2709
+ def _namedtuple_mro_entries(bases):
2710
+ assert NamedTuple in bases
2711
+ return (_NamedTuple,)
2712
+
2713
+ NamedTuple.__mro_entries__ = _namedtuple_mro_entries
2714
+
2715
+
2716
+ if hasattr(collections.abc, "Buffer"):
2717
+ Buffer = collections.abc.Buffer
2718
+ else:
2719
+ class Buffer(abc.ABC):
2720
+ """Base class for classes that implement the buffer protocol.
2721
+
2722
+ The buffer protocol allows Python objects to expose a low-level
2723
+ memory buffer interface. Before Python 3.12, it is not possible
2724
+ to implement the buffer protocol in pure Python code, or even
2725
+ to check whether a class implements the buffer protocol. In
2726
+ Python 3.12 and higher, the ``__buffer__`` method allows access
2727
+ to the buffer protocol from Python code, and the
2728
+ ``collections.abc.Buffer`` ABC allows checking whether a class
2729
+ implements the buffer protocol.
2730
+
2731
+ To indicate support for the buffer protocol in earlier versions,
2732
+ inherit from this ABC, either in a stub file or at runtime,
2733
+ or use ABC registration. This ABC provides no methods, because
2734
+ there is no Python-accessible methods shared by pre-3.12 buffer
2735
+ classes. It is useful primarily for static checks.
2736
+
2737
+ """
2738
+
2739
+ # As a courtesy, register the most common stdlib buffer classes.
2740
+ Buffer.register(memoryview)
2741
+ Buffer.register(bytearray)
2742
+ Buffer.register(bytes)
2743
+
2744
+
2745
+ # Backport of types.get_original_bases, available on 3.12+ in CPython
2746
+ if hasattr(_types, "get_original_bases"):
2747
+ get_original_bases = _types.get_original_bases
2748
+ else:
2749
+ def get_original_bases(__cls):
2750
+ """Return the class's "original" bases prior to modification by `__mro_entries__`.
2751
+
2752
+ Examples::
2753
+
2754
+ from typing import TypeVar, Generic
2755
+ from metaflow._vendor.typing_extensions import NamedTuple, TypedDict
2756
+
2757
+ T = TypeVar("T")
2758
+ class Foo(Generic[T]): ...
2759
+ class Bar(Foo[int], float): ...
2760
+ class Baz(list[str]): ...
2761
+ Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
2762
+ Spam = TypedDict("Spam", {"a": int, "b": str})
2763
+
2764
+ assert get_original_bases(Bar) == (Foo[int], float)
2765
+ assert get_original_bases(Baz) == (list[str],)
2766
+ assert get_original_bases(Eggs) == (NamedTuple,)
2767
+ assert get_original_bases(Spam) == (TypedDict,)
2768
+ assert get_original_bases(int) == (object,)
2769
+ """
2770
+ try:
2771
+ return __cls.__orig_bases__
2772
+ except AttributeError:
2773
+ try:
2774
+ return __cls.__bases__
2775
+ except AttributeError:
2776
+ raise TypeError(
2777
+ f'Expected an instance of type, not {type(__cls).__name__!r}'
2778
+ ) from None
2779
+
2780
+
2781
+ # NewType is a class on Python 3.10+, making it pickleable
2782
+ # The error message for subclassing instances of NewType was improved on 3.11+
2783
+ if sys.version_info >= (3, 11):
2784
+ NewType = typing.NewType
2785
+ else:
2786
+ class NewType:
2787
+ """NewType creates simple unique types with almost zero
2788
+ runtime overhead. NewType(name, tp) is considered a subtype of tp
2789
+ by static type checkers. At runtime, NewType(name, tp) returns
2790
+ a dummy callable that simply returns its argument. Usage::
2791
+ UserId = NewType('UserId', int)
2792
+ def name_by_id(user_id: UserId) -> str:
2793
+ ...
2794
+ UserId('user') # Fails type check
2795
+ name_by_id(42) # Fails type check
2796
+ name_by_id(UserId(42)) # OK
2797
+ num = UserId(5) + 1 # type: int
2798
+ """
2799
+
2800
+ def __call__(self, obj):
2801
+ return obj
2802
+
2803
+ def __init__(self, name, tp):
2804
+ self.__qualname__ = name
2805
+ if '.' in name:
2806
+ name = name.rpartition('.')[-1]
2807
+ self.__name__ = name
2808
+ self.__supertype__ = tp
2809
+ def_mod = _caller()
2810
+ if def_mod != 'typing_extensions':
2811
+ self.__module__ = def_mod
2812
+
2813
+ def __mro_entries__(self, bases):
2814
+ # We defined __mro_entries__ to get a better error message
2815
+ # if a user attempts to subclass a NewType instance. bpo-46170
2816
+ supercls_name = self.__name__
2817
+
2818
+ class Dummy:
2819
+ def __init_subclass__(cls):
2820
+ subcls_name = cls.__name__
2821
+ raise TypeError(
2822
+ f"Cannot subclass an instance of NewType. "
2823
+ f"Perhaps you were looking for: "
2824
+ f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
2825
+ )
2826
+
2827
+ return (Dummy,)
2828
+
2829
+ def __repr__(self):
2830
+ return f'{self.__module__}.{self.__qualname__}'
2831
+
2832
+ def __reduce__(self):
2833
+ return self.__qualname__
2834
+
2835
+ if sys.version_info >= (3, 10):
2836
+ # PEP 604 methods
2837
+ # It doesn't make sense to have these methods on Python <3.10
2838
+
2839
+ def __or__(self, other):
2840
+ return typing.Union[self, other]
2841
+
2842
+ def __ror__(self, other):
2843
+ return typing.Union[other, self]
2844
+
2845
+
2846
+ if hasattr(typing, "TypeAliasType"):
2847
+ TypeAliasType = typing.TypeAliasType
2848
+ else:
2849
+ def _is_unionable(obj):
2850
+ """Corresponds to is_unionable() in unionobject.c in CPython."""
2851
+ return obj is None or isinstance(obj, (
2852
+ type,
2853
+ _types.GenericAlias,
2854
+ _types.UnionType,
2855
+ TypeAliasType,
2856
+ ))
2857
+
2858
+ class TypeAliasType:
2859
+ """Create named, parameterized type aliases.
2860
+
2861
+ This provides a backport of the new `type` statement in Python 3.12:
2862
+
2863
+ type ListOrSet[T] = list[T] | set[T]
2864
+
2865
+ is equivalent to:
2866
+
2867
+ T = TypeVar("T")
2868
+ ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
2869
+
2870
+ The name ListOrSet can then be used as an alias for the type it refers to.
2871
+
2872
+ The type_params argument should contain all the type parameters used
2873
+ in the value of the type alias. If the alias is not generic, this
2874
+ argument is omitted.
2875
+
2876
+ Static type checkers should only support type aliases declared using
2877
+ TypeAliasType that follow these rules:
2878
+
2879
+ - The first argument (the name) must be a string literal.
2880
+ - The TypeAliasType instance must be immediately assigned to a variable
2881
+ of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
2882
+ as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
2883
+
2884
+ """
2885
+
2886
+ def __init__(self, name: str, value, *, type_params=()):
2887
+ if not isinstance(name, str):
2888
+ raise TypeError("TypeAliasType name must be a string")
2889
+ self.__value__ = value
2890
+ self.__type_params__ = type_params
2891
+
2892
+ parameters = []
2893
+ for type_param in type_params:
2894
+ if isinstance(type_param, TypeVarTuple):
2895
+ parameters.extend(type_param)
2896
+ else:
2897
+ parameters.append(type_param)
2898
+ self.__parameters__ = tuple(parameters)
2899
+ def_mod = _caller()
2900
+ if def_mod != 'typing_extensions':
2901
+ self.__module__ = def_mod
2902
+ # Setting this attribute closes the TypeAliasType from further modification
2903
+ self.__name__ = name
2904
+
2905
+ def __setattr__(self, __name: str, __value: object) -> None:
2906
+ if hasattr(self, "__name__"):
2907
+ self._raise_attribute_error(__name)
2908
+ super().__setattr__(__name, __value)
2909
+
2910
+ def __delattr__(self, __name: str) -> Never:
2911
+ self._raise_attribute_error(__name)
2912
+
2913
+ def _raise_attribute_error(self, name: str) -> Never:
2914
+ # Match the Python 3.12 error messages exactly
2915
+ if name == "__name__":
2916
+ raise AttributeError("readonly attribute")
2917
+ elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
2918
+ raise AttributeError(
2919
+ f"attribute '{name}' of 'typing.TypeAliasType' objects "
2920
+ "is not writable"
2921
+ )
2922
+ else:
2923
+ raise AttributeError(
2924
+ f"'typing.TypeAliasType' object has no attribute '{name}'"
2925
+ )
2926
+
2927
+ def __repr__(self) -> str:
2928
+ return self.__name__
2929
+
2930
+ def __getitem__(self, parameters):
2931
+ if not isinstance(parameters, tuple):
2932
+ parameters = (parameters,)
2933
+ parameters = [
2934
+ typing._type_check(
2935
+ item, f'Subscripting {self.__name__} requires a type.'
2936
+ )
2937
+ for item in parameters
2938
+ ]
2939
+ return typing._GenericAlias(self, tuple(parameters))
2940
+
2941
+ def __reduce__(self):
2942
+ return self.__name__
2943
+
2944
+ def __init_subclass__(cls, *args, **kwargs):
2945
+ raise TypeError(
2946
+ "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
2947
+ )
2948
+
2949
+ # The presence of this method convinces typing._type_check
2950
+ # that TypeAliasTypes are types.
2951
+ def __call__(self):
2952
+ raise TypeError("Type alias is not callable")
2953
+
2954
+ if sys.version_info >= (3, 10):
2955
+ def __or__(self, right):
2956
+ # For forward compatibility with 3.12, reject Unions
2957
+ # that are not accepted by the built-in Union.
2958
+ if not _is_unionable(right):
2959
+ return NotImplemented
2960
+ return typing.Union[self, right]
2961
+
2962
+ def __ror__(self, left):
2963
+ if not _is_unionable(left):
2964
+ return NotImplemented
2965
+ return typing.Union[left, self]
2966
+
2967
+
2968
+ if hasattr(typing, "is_protocol"):
2969
+ is_protocol = typing.is_protocol
2970
+ get_protocol_members = typing.get_protocol_members
2971
+ else:
2972
+ def is_protocol(__tp: type) -> bool:
2973
+ """Return True if the given type is a Protocol.
2974
+
2975
+ Example::
2976
+
2977
+ >>> from typing_extensions import Protocol, is_protocol
2978
+ >>> class P(Protocol):
2979
+ ... def a(self) -> str: ...
2980
+ ... b: int
2981
+ >>> is_protocol(P)
2982
+ True
2983
+ >>> is_protocol(int)
2984
+ False
2985
+ """
2986
+ return (
2987
+ isinstance(__tp, type)
2988
+ and getattr(__tp, '_is_protocol', False)
2989
+ and __tp != Protocol
2990
+ )
2991
+
2992
+ def get_protocol_members(__tp: type) -> typing.FrozenSet[str]:
2993
+ """Return the set of members defined in a Protocol.
2994
+
2995
+ Example::
2996
+
2997
+ >>> from typing_extensions import Protocol, get_protocol_members
2998
+ >>> class P(Protocol):
2999
+ ... def a(self) -> str: ...
3000
+ ... b: int
3001
+ >>> get_protocol_members(P)
3002
+ frozenset({'a', 'b'})
3003
+
3004
+ Raise a TypeError for arguments that are not Protocols.
3005
+ """
3006
+ if not is_protocol(__tp):
3007
+ raise TypeError(f'{__tp!r} is not a Protocol')
3008
+ if hasattr(__tp, '__protocol_attrs__'):
3009
+ return frozenset(__tp.__protocol_attrs__)
3010
+ return frozenset(_get_protocol_attrs(__tp))
3011
+
3012
+
3013
+ # Aliases for items that have always been in typing.
3014
+ # Explicitly assign these (rather than using `from typing import *` at the top),
3015
+ # so that we get a CI error if one of these is deleted from typing.py
3016
+ # in a future version of Python
3017
+ AbstractSet = typing.AbstractSet
3018
+ AnyStr = typing.AnyStr
3019
+ BinaryIO = typing.BinaryIO
3020
+ Callable = typing.Callable
3021
+ Collection = typing.Collection
3022
+ Container = typing.Container
3023
+ Dict = typing.Dict
3024
+ ForwardRef = typing.ForwardRef
3025
+ FrozenSet = typing.FrozenSet
3026
+ Generator = typing.Generator
3027
+ Generic = typing.Generic
3028
+ Hashable = typing.Hashable
3029
+ IO = typing.IO
3030
+ ItemsView = typing.ItemsView
3031
+ Iterable = typing.Iterable
3032
+ Iterator = typing.Iterator
3033
+ KeysView = typing.KeysView
3034
+ List = typing.List
3035
+ Mapping = typing.Mapping
3036
+ MappingView = typing.MappingView
3037
+ Match = typing.Match
3038
+ MutableMapping = typing.MutableMapping
3039
+ MutableSequence = typing.MutableSequence
3040
+ MutableSet = typing.MutableSet
3041
+ Optional = typing.Optional
3042
+ Pattern = typing.Pattern
3043
+ Reversible = typing.Reversible
3044
+ Sequence = typing.Sequence
3045
+ Set = typing.Set
3046
+ Sized = typing.Sized
3047
+ TextIO = typing.TextIO
3048
+ Tuple = typing.Tuple
3049
+ Union = typing.Union
3050
+ ValuesView = typing.ValuesView
3051
+ cast = typing.cast
3052
+ no_type_check = typing.no_type_check
3053
+ no_type_check_decorator = typing.no_type_check_decorator