Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/typing_extensions.py: 42%

1134 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:35 +0000

1import abc 

2import collections 

3import collections.abc 

4import functools 

5import inspect 

6import operator 

7import sys 

8import types as _types 

9import typing 

10import 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_type_hints', 

69 'IntVar', 

70 'is_typeddict', 

71 'Literal', 

72 'NewType', 

73 'overload', 

74 'override', 

75 'Protocol', 

76 'reveal_type', 

77 'runtime', 

78 'runtime_checkable', 

79 'Text', 

80 'TypeAlias', 

81 'TypeAliasType', 

82 'TypeGuard', 

83 'TYPE_CHECKING', 

84 'Never', 

85 'NoReturn', 

86 'Required', 

87 'NotRequired', 

88] 

89 

90# for backward compatibility 

91PEP_560 = True 

92GenericMeta = type 

93 

94# The functions below are modified copies of typing internal helpers. 

95# They are needed by _ProtocolMeta and they provide support for PEP 646. 

96 

97 

98class _Sentinel: 

99 def __repr__(self): 

100 return "<sentinel>" 

101 

102 

103_marker = _Sentinel() 

104 

105 

106def _check_generic(cls, parameters, elen=_marker): 

107 """Check correct count for parameters of a generic cls (internal helper). 

108 This gives a nice error message in case of count mismatch. 

109 """ 

110 if not elen: 

111 raise TypeError(f"{cls} is not a generic class") 

112 if elen is _marker: 

113 if not hasattr(cls, "__parameters__") or not cls.__parameters__: 

114 raise TypeError(f"{cls} is not a generic class") 

115 elen = len(cls.__parameters__) 

116 alen = len(parameters) 

117 if alen != elen: 

118 if hasattr(cls, "__parameters__"): 

119 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] 

120 num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) 

121 if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): 

122 return 

123 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};" 

124 f" actual {alen}, expected {elen}") 

125 

126 

127if sys.version_info >= (3, 10): 

128 def _should_collect_from_parameters(t): 

129 return isinstance( 

130 t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) 

131 ) 

132elif sys.version_info >= (3, 9): 

133 def _should_collect_from_parameters(t): 

134 return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) 

135else: 

136 def _should_collect_from_parameters(t): 

137 return isinstance(t, typing._GenericAlias) and not t._special 

138 

139 

140def _collect_type_vars(types, typevar_types=None): 

141 """Collect all type variable contained in types in order of 

142 first appearance (lexicographic order). For example:: 

143 

144 _collect_type_vars((T, List[S, T])) == (T, S) 

145 """ 

146 if typevar_types is None: 

147 typevar_types = typing.TypeVar 

148 tvars = [] 

149 for t in types: 

150 if ( 

151 isinstance(t, typevar_types) and 

152 t not in tvars and 

153 not _is_unpack(t) 

154 ): 

155 tvars.append(t) 

156 if _should_collect_from_parameters(t): 

157 tvars.extend([t for t in t.__parameters__ if t not in tvars]) 

158 return tuple(tvars) 

159 

160 

161NoReturn = typing.NoReturn 

162 

163# Some unconstrained type variables. These are used by the container types. 

164# (These are not for export.) 

165T = typing.TypeVar('T') # Any type. 

166KT = typing.TypeVar('KT') # Key type. 

167VT = typing.TypeVar('VT') # Value type. 

168T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. 

169T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. 

170 

171 

172if sys.version_info >= (3, 11): 

173 from typing import Any 

174else: 

175 

176 class _AnyMeta(type): 

177 def __instancecheck__(self, obj): 

178 if self is Any: 

179 raise TypeError("typing_extensions.Any cannot be used with isinstance()") 

180 return super().__instancecheck__(obj) 

181 

182 def __repr__(self): 

183 if self is Any: 

184 return "typing_extensions.Any" 

185 return super().__repr__() 

186 

187 class Any(metaclass=_AnyMeta): 

188 """Special type indicating an unconstrained type. 

189 - Any is compatible with every type. 

190 - Any assumed to have all methods. 

191 - All values assumed to be instances of Any. 

192 Note that all the above statements are true from the point of view of 

193 static type checkers. At runtime, Any should not be used with instance 

194 checks. 

195 """ 

196 def __new__(cls, *args, **kwargs): 

197 if cls is Any: 

198 raise TypeError("Any cannot be instantiated") 

199 return super().__new__(cls, *args, **kwargs) 

200 

201 

202ClassVar = typing.ClassVar 

203 

204# On older versions of typing there is an internal class named "Final". 

205# 3.8+ 

206if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7): 

207 Final = typing.Final 

208# 3.7 

209else: 

210 class _FinalForm(typing._SpecialForm, _root=True): 

211 

212 def __repr__(self): 

213 return 'typing_extensions.' + self._name 

214 

215 def __getitem__(self, parameters): 

216 item = typing._type_check(parameters, 

217 f'{self._name} accepts only a single type.') 

218 return typing._GenericAlias(self, (item,)) 

219 

220 Final = _FinalForm('Final', 

221 doc="""A special typing construct to indicate that a name 

222 cannot be re-assigned or overridden in a subclass. 

223 For example: 

224 

225 MAX_SIZE: Final = 9000 

226 MAX_SIZE += 1 # Error reported by type checker 

227 

228 class Connection: 

229 TIMEOUT: Final[int] = 10 

230 class FastConnector(Connection): 

231 TIMEOUT = 1 # Error reported by type checker 

232 

233 There is no runtime checking of these properties.""") 

234 

235if sys.version_info >= (3, 11): 

236 final = typing.final 

237else: 

238 # @final exists in 3.8+, but we backport it for all versions 

239 # before 3.11 to keep support for the __final__ attribute. 

240 # See https://bugs.python.org/issue46342 

241 def final(f): 

242 """This decorator can be used to indicate to type checkers that 

243 the decorated method cannot be overridden, and decorated class 

244 cannot be subclassed. For example: 

245 

246 class Base: 

247 @final 

248 def done(self) -> None: 

249 ... 

250 class Sub(Base): 

251 def done(self) -> None: # Error reported by type checker 

252 ... 

253 @final 

254 class Leaf: 

255 ... 

256 class Other(Leaf): # Error reported by type checker 

257 ... 

258 

259 There is no runtime checking of these properties. The decorator 

260 sets the ``__final__`` attribute to ``True`` on the decorated object 

261 to allow runtime introspection. 

262 """ 

263 try: 

264 f.__final__ = True 

265 except (AttributeError, TypeError): 

266 # Skip the attribute silently if it is not writable. 

267 # AttributeError happens if the object has __slots__ or a 

268 # read-only property, TypeError if it's a builtin class. 

269 pass 

270 return f 

271 

272 

273def IntVar(name): 

274 return typing.TypeVar(name) 

275 

276 

277# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8 

278if sys.version_info >= (3, 10, 1): 

279 Literal = typing.Literal 

280else: 

281 def _flatten_literal_params(parameters): 

282 """An internal helper for Literal creation: flatten Literals among parameters""" 

283 params = [] 

284 for p in parameters: 

285 if isinstance(p, _LiteralGenericAlias): 

286 params.extend(p.__args__) 

287 else: 

288 params.append(p) 

289 return tuple(params) 

290 

291 def _value_and_type_iter(params): 

292 for p in params: 

293 yield p, type(p) 

294 

295 class _LiteralGenericAlias(typing._GenericAlias, _root=True): 

296 def __eq__(self, other): 

297 if not isinstance(other, _LiteralGenericAlias): 

298 return NotImplemented 

299 these_args_deduped = set(_value_and_type_iter(self.__args__)) 

300 other_args_deduped = set(_value_and_type_iter(other.__args__)) 

301 return these_args_deduped == other_args_deduped 

302 

303 def __hash__(self): 

304 return hash(frozenset(_value_and_type_iter(self.__args__))) 

305 

306 class _LiteralForm(typing._SpecialForm, _root=True): 

307 def __init__(self, doc: str): 

308 self._name = 'Literal' 

309 self._doc = self.__doc__ = doc 

310 

311 def __repr__(self): 

312 return 'typing_extensions.' + self._name 

313 

314 def __getitem__(self, parameters): 

315 if not isinstance(parameters, tuple): 

316 parameters = (parameters,) 

317 

318 parameters = _flatten_literal_params(parameters) 

319 

320 val_type_pairs = list(_value_and_type_iter(parameters)) 

321 try: 

322 deduped_pairs = set(val_type_pairs) 

323 except TypeError: 

324 # unhashable parameters 

325 pass 

326 else: 

327 # similar logic to typing._deduplicate on Python 3.9+ 

328 if len(deduped_pairs) < len(val_type_pairs): 

329 new_parameters = [] 

330 for pair in val_type_pairs: 

331 if pair in deduped_pairs: 

332 new_parameters.append(pair[0]) 

333 deduped_pairs.remove(pair) 

334 assert not deduped_pairs, deduped_pairs 

335 parameters = tuple(new_parameters) 

336 

337 return _LiteralGenericAlias(self, parameters) 

338 

339 Literal = _LiteralForm(doc="""\ 

340 A type that can be used to indicate to type checkers 

341 that the corresponding value has a value literally equivalent 

342 to the provided parameter. For example: 

343 

344 var: Literal[4] = 4 

345 

346 The type checker understands that 'var' is literally equal to 

347 the value 4 and no other value. 

348 

349 Literal[...] cannot be subclassed. There is no runtime 

350 checking verifying that the parameter is actually a value 

351 instead of a type.""") 

352 

353 

354_overload_dummy = typing._overload_dummy 

355 

356 

357if hasattr(typing, "get_overloads"): # 3.11+ 

358 overload = typing.overload 

359 get_overloads = typing.get_overloads 

360 clear_overloads = typing.clear_overloads 

361else: 

362 # {module: {qualname: {firstlineno: func}}} 

363 _overload_registry = collections.defaultdict( 

364 functools.partial(collections.defaultdict, dict) 

365 ) 

366 

367 def overload(func): 

368 """Decorator for overloaded functions/methods. 

369 

370 In a stub file, place two or more stub definitions for the same 

371 function in a row, each decorated with @overload. For example: 

372 

373 @overload 

374 def utf8(value: None) -> None: ... 

375 @overload 

376 def utf8(value: bytes) -> bytes: ... 

377 @overload 

378 def utf8(value: str) -> bytes: ... 

379 

380 In a non-stub file (i.e. a regular .py file), do the same but 

381 follow it with an implementation. The implementation should *not* 

382 be decorated with @overload. For example: 

383 

384 @overload 

385 def utf8(value: None) -> None: ... 

386 @overload 

387 def utf8(value: bytes) -> bytes: ... 

388 @overload 

389 def utf8(value: str) -> bytes: ... 

390 def utf8(value): 

391 # implementation goes here 

392 

393 The overloads for a function can be retrieved at runtime using the 

394 get_overloads() function. 

395 """ 

396 # classmethod and staticmethod 

397 f = getattr(func, "__func__", func) 

398 try: 

399 _overload_registry[f.__module__][f.__qualname__][ 

400 f.__code__.co_firstlineno 

401 ] = func 

402 except AttributeError: 

403 # Not a normal function; ignore. 

404 pass 

405 return _overload_dummy 

406 

407 def get_overloads(func): 

408 """Return all defined overloads for *func* as a sequence.""" 

409 # classmethod and staticmethod 

410 f = getattr(func, "__func__", func) 

411 if f.__module__ not in _overload_registry: 

412 return [] 

413 mod_dict = _overload_registry[f.__module__] 

414 if f.__qualname__ not in mod_dict: 

415 return [] 

416 return list(mod_dict[f.__qualname__].values()) 

417 

418 def clear_overloads(): 

419 """Clear all overloads in the registry.""" 

420 _overload_registry.clear() 

421 

422 

423# This is not a real generic class. Don't use outside annotations. 

424Type = typing.Type 

425 

426# Various ABCs mimicking those in collections.abc. 

427# A few are simply re-exported for completeness. 

428 

429 

430Awaitable = typing.Awaitable 

431Coroutine = typing.Coroutine 

432AsyncIterable = typing.AsyncIterable 

433AsyncIterator = typing.AsyncIterator 

434Deque = typing.Deque 

435ContextManager = typing.ContextManager 

436AsyncContextManager = typing.AsyncContextManager 

437DefaultDict = typing.DefaultDict 

438 

439# 3.7.2+ 

440if hasattr(typing, 'OrderedDict'): 

441 OrderedDict = typing.OrderedDict 

442# 3.7.0-3.7.2 

443else: 

444 OrderedDict = typing._alias(collections.OrderedDict, (KT, VT)) 

445 

446Counter = typing.Counter 

447ChainMap = typing.ChainMap 

448AsyncGenerator = typing.AsyncGenerator 

449Text = typing.Text 

450TYPE_CHECKING = typing.TYPE_CHECKING 

451 

452 

453_PROTO_ALLOWLIST = { 

454 'collections.abc': [ 

455 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', 

456 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 

457 ], 

458 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], 

459} 

460 

461 

462_EXCLUDED_ATTRS = { 

463 "__abstractmethods__", "__annotations__", "__weakref__", "_is_protocol", 

464 "_is_runtime_protocol", "__dict__", "__slots__", "__parameters__", 

465 "__orig_bases__", "__module__", "_MutableMapping__marker", "__doc__", 

466 "__subclasshook__", "__orig_class__", "__init__", "__new__", 

467 "__protocol_attrs__", "__callable_proto_members_only__", 

468} 

469 

470if sys.version_info < (3, 8): 

471 _EXCLUDED_ATTRS |= { 

472 "_gorg", "__next_in_mro__", "__extra__", "__tree_hash__", "__args__", 

473 "__origin__" 

474 } 

475 

476if sys.version_info >= (3, 9): 

477 _EXCLUDED_ATTRS.add("__class_getitem__") 

478 

479if sys.version_info >= (3, 12): 

480 _EXCLUDED_ATTRS.add("__type_params__") 

481 

482_EXCLUDED_ATTRS = frozenset(_EXCLUDED_ATTRS) 

483 

484 

485def _get_protocol_attrs(cls): 

486 attrs = set() 

487 for base in cls.__mro__[:-1]: # without object 

488 if base.__name__ in {'Protocol', 'Generic'}: 

489 continue 

490 annotations = getattr(base, '__annotations__', {}) 

491 for attr in (*base.__dict__, *annotations): 

492 if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS): 

493 attrs.add(attr) 

494 return attrs 

495 

496 

497def _maybe_adjust_parameters(cls): 

498 """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__. 

499 

500 The contents of this function are very similar 

501 to logic found in typing.Generic.__init_subclass__ 

502 on the CPython main branch. 

503 """ 

504 tvars = [] 

505 if '__orig_bases__' in cls.__dict__: 

506 tvars = _collect_type_vars(cls.__orig_bases__) 

507 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn]. 

508 # If found, tvars must be a subset of it. 

509 # If not found, tvars is it. 

510 # Also check for and reject plain Generic, 

511 # and reject multiple Generic[...] and/or Protocol[...]. 

512 gvars = None 

513 for base in cls.__orig_bases__: 

514 if (isinstance(base, typing._GenericAlias) and 

515 base.__origin__ in (typing.Generic, Protocol)): 

516 # for error messages 

517 the_base = base.__origin__.__name__ 

518 if gvars is not None: 

519 raise TypeError( 

520 "Cannot inherit from Generic[...]" 

521 " and/or Protocol[...] multiple types.") 

522 gvars = base.__parameters__ 

523 if gvars is None: 

524 gvars = tvars 

525 else: 

526 tvarset = set(tvars) 

527 gvarset = set(gvars) 

528 if not tvarset <= gvarset: 

529 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) 

530 s_args = ', '.join(str(g) for g in gvars) 

531 raise TypeError(f"Some type variables ({s_vars}) are" 

532 f" not listed in {the_base}[{s_args}]") 

533 tvars = gvars 

534 cls.__parameters__ = tuple(tvars) 

535 

536 

537def _caller(depth=2): 

538 try: 

539 return sys._getframe(depth).f_globals.get('__name__', '__main__') 

540 except (AttributeError, ValueError): # For platforms without _getframe() 

541 return None 

542 

543 

544# The performance of runtime-checkable protocols is significantly improved on Python 3.12, 

545# so we backport the 3.12 version of Protocol to Python <=3.11 

546if sys.version_info >= (3, 12): 

547 Protocol = typing.Protocol 

548 runtime_checkable = typing.runtime_checkable 

549else: 

550 def _allow_reckless_class_checks(depth=3): 

551 """Allow instance and class checks for special stdlib modules. 

552 The abc and functools modules indiscriminately call isinstance() and 

553 issubclass() on the whole MRO of a user class, which may contain protocols. 

554 """ 

555 return _caller(depth) in {'abc', 'functools', None} 

556 

557 def _no_init(self, *args, **kwargs): 

558 if type(self)._is_protocol: 

559 raise TypeError('Protocols cannot be instantiated') 

560 

561 class _ProtocolMeta(abc.ABCMeta): 

562 # This metaclass is somewhat unfortunate, 

563 # but is necessary for several reasons... 

564 def __init__(cls, *args, **kwargs): 

565 super().__init__(*args, **kwargs) 

566 if getattr(cls, "_is_protocol", False): 

567 cls.__protocol_attrs__ = _get_protocol_attrs(cls) 

568 # PEP 544 prohibits using issubclass() 

569 # with protocols that have non-method members. 

570 cls.__callable_proto_members_only__ = all( 

571 callable(getattr(cls, attr, None)) for attr in cls.__protocol_attrs__ 

572 ) 

573 

574 def __subclasscheck__(cls, other): 

575 if not isinstance(other, type): 

576 # Same error message as for issubclass(1, int). 

577 raise TypeError('issubclass() arg 1 must be a class') 

578 if ( 

579 getattr(cls, '_is_protocol', False) 

580 and not _allow_reckless_class_checks() 

581 ): 

582 if not cls.__callable_proto_members_only__: 

583 raise TypeError( 

584 "Protocols with non-method members don't support issubclass()" 

585 ) 

586 if not getattr(cls, '_is_runtime_protocol', False): 

587 raise TypeError( 

588 "Instance and class checks can only be used with " 

589 "@runtime_checkable protocols" 

590 ) 

591 return super().__subclasscheck__(other) 

592 

593 def __instancecheck__(cls, instance): 

594 # We need this method for situations where attributes are 

595 # assigned in __init__. 

596 if not getattr(cls, "_is_protocol", False): 

597 # i.e., it's a concrete subclass of a protocol 

598 return super().__instancecheck__(instance) 

599 

600 if ( 

601 not getattr(cls, '_is_runtime_protocol', False) and 

602 not _allow_reckless_class_checks() 

603 ): 

604 raise TypeError("Instance and class checks can only be used with" 

605 " @runtime_checkable protocols") 

606 

607 if super().__instancecheck__(instance): 

608 return True 

609 

610 for attr in cls.__protocol_attrs__: 

611 try: 

612 val = inspect.getattr_static(instance, attr) 

613 except AttributeError: 

614 break 

615 if val is None and callable(getattr(cls, attr, None)): 

616 break 

617 else: 

618 return True 

619 

620 return False 

621 

622 def __eq__(cls, other): 

623 # Hack so that typing.Generic.__class_getitem__ 

624 # treats typing_extensions.Protocol 

625 # as equivalent to typing.Protocol on Python 3.8+ 

626 if super().__eq__(other) is True: 

627 return True 

628 return ( 

629 cls is Protocol and other is getattr(typing, "Protocol", object()) 

630 ) 

631 

632 # This has to be defined, or the abc-module cache 

633 # complains about classes with this metaclass being unhashable, 

634 # if we define only __eq__! 

635 def __hash__(cls) -> int: 

636 return type.__hash__(cls) 

637 

638 @classmethod 

639 def _proto_hook(cls, other): 

640 if not cls.__dict__.get('_is_protocol', False): 

641 return NotImplemented 

642 

643 for attr in cls.__protocol_attrs__: 

644 for base in other.__mro__: 

645 # Check if the members appears in the class dictionary... 

646 if attr in base.__dict__: 

647 if base.__dict__[attr] is None: 

648 return NotImplemented 

649 break 

650 

651 # ...or in annotations, if it is a sub-protocol. 

652 annotations = getattr(base, '__annotations__', {}) 

653 if ( 

654 isinstance(annotations, collections.abc.Mapping) 

655 and attr in annotations 

656 and issubclass(other, (typing.Generic, _ProtocolMeta)) 

657 and getattr(other, "_is_protocol", False) 

658 ): 

659 break 

660 else: 

661 return NotImplemented 

662 return True 

663 

664 def _check_proto_bases(cls): 

665 for base in cls.__bases__: 

666 if not (base in (object, typing.Generic) or 

667 base.__module__ in _PROTO_ALLOWLIST and 

668 base.__name__ in _PROTO_ALLOWLIST[base.__module__] or 

669 isinstance(base, _ProtocolMeta) and base._is_protocol): 

670 raise TypeError('Protocols can only inherit from other' 

671 f' protocols, got {repr(base)}') 

672 

673 if sys.version_info >= (3, 8): 

674 class Protocol(typing.Generic, metaclass=_ProtocolMeta): 

675 __doc__ = typing.Protocol.__doc__ 

676 __slots__ = () 

677 _is_protocol = True 

678 _is_runtime_protocol = False 

679 

680 def __init_subclass__(cls, *args, **kwargs): 

681 super().__init_subclass__(*args, **kwargs) 

682 

683 # Determine if this is a protocol or a concrete subclass. 

684 if not cls.__dict__.get('_is_protocol', False): 

685 cls._is_protocol = any(b is Protocol for b in cls.__bases__) 

686 

687 # Set (or override) the protocol subclass hook. 

688 if '__subclasshook__' not in cls.__dict__: 

689 cls.__subclasshook__ = _proto_hook 

690 

691 # We have nothing more to do for non-protocols... 

692 if not cls._is_protocol: 

693 return 

694 

695 # ... otherwise check consistency of bases, and prohibit instantiation. 

696 _check_proto_bases(cls) 

697 if cls.__init__ is Protocol.__init__: 

698 cls.__init__ = _no_init 

699 

700 else: 

701 class Protocol(metaclass=_ProtocolMeta): 

702 # There is quite a lot of overlapping code with typing.Generic. 

703 # Unfortunately it is hard to avoid this on Python <3.8, 

704 # as the typing module on Python 3.7 doesn't let us subclass typing.Generic! 

705 """Base class for protocol classes. Protocol classes are defined as:: 

706 

707 class Proto(Protocol): 

708 def meth(self) -> int: 

709 ... 

710 

711 Such classes are primarily used with static type checkers that recognize 

712 structural subtyping (static duck-typing), for example:: 

713 

714 class C: 

715 def meth(self) -> int: 

716 return 0 

717 

718 def func(x: Proto) -> int: 

719 return x.meth() 

720 

721 func(C()) # Passes static type check 

722 

723 See PEP 544 for details. Protocol classes decorated with 

724 @typing_extensions.runtime_checkable act 

725 as simple-minded runtime-checkable protocols that check 

726 only the presence of given attributes, ignoring their type signatures. 

727 

728 Protocol classes can be generic, they are defined as:: 

729 

730 class GenProto(Protocol[T]): 

731 def meth(self) -> T: 

732 ... 

733 """ 

734 __slots__ = () 

735 _is_protocol = True 

736 _is_runtime_protocol = False 

737 

738 def __new__(cls, *args, **kwds): 

739 if cls is Protocol: 

740 raise TypeError("Type Protocol cannot be instantiated; " 

741 "it can only be used as a base class") 

742 return super().__new__(cls) 

743 

744 @typing._tp_cache 

745 def __class_getitem__(cls, params): 

746 if not isinstance(params, tuple): 

747 params = (params,) 

748 if not params and cls is not typing.Tuple: 

749 raise TypeError( 

750 f"Parameter list to {cls.__qualname__}[...] cannot be empty") 

751 msg = "Parameters to generic types must be types." 

752 params = tuple(typing._type_check(p, msg) for p in params) 

753 if cls is Protocol: 

754 # Generic can only be subscripted with unique type variables. 

755 if not all(isinstance(p, typing.TypeVar) for p in params): 

756 i = 0 

757 while isinstance(params[i], typing.TypeVar): 

758 i += 1 

759 raise TypeError( 

760 "Parameters to Protocol[...] must all be type variables." 

761 f" Parameter {i + 1} is {params[i]}") 

762 if len(set(params)) != len(params): 

763 raise TypeError( 

764 "Parameters to Protocol[...] must all be unique") 

765 else: 

766 # Subscripting a regular Generic subclass. 

767 _check_generic(cls, params, len(cls.__parameters__)) 

768 return typing._GenericAlias(cls, params) 

769 

770 def __init_subclass__(cls, *args, **kwargs): 

771 if '__orig_bases__' in cls.__dict__: 

772 error = typing.Generic in cls.__orig_bases__ 

773 else: 

774 error = typing.Generic in cls.__bases__ 

775 if error: 

776 raise TypeError("Cannot inherit from plain Generic") 

777 _maybe_adjust_parameters(cls) 

778 

779 # Determine if this is a protocol or a concrete subclass. 

780 if not cls.__dict__.get('_is_protocol', None): 

781 cls._is_protocol = any(b is Protocol for b in cls.__bases__) 

782 

783 # Set (or override) the protocol subclass hook. 

784 if '__subclasshook__' not in cls.__dict__: 

785 cls.__subclasshook__ = _proto_hook 

786 

787 # We have nothing more to do for non-protocols. 

788 if not cls._is_protocol: 

789 return 

790 

791 # Check consistency of bases. 

792 _check_proto_bases(cls) 

793 if cls.__init__ is Protocol.__init__: 

794 cls.__init__ = _no_init 

795 

796 def runtime_checkable(cls): 

797 """Mark a protocol class as a runtime protocol, so that it 

798 can be used with isinstance() and issubclass(). Raise TypeError 

799 if applied to a non-protocol class. 

800 

801 This allows a simple-minded structural check very similar to the 

802 one-offs in collections.abc such as Hashable. 

803 """ 

804 if not ( 

805 (isinstance(cls, _ProtocolMeta) or issubclass(cls, typing.Generic)) 

806 and getattr(cls, "_is_protocol", False) 

807 ): 

808 raise TypeError('@runtime_checkable can be only applied to protocol classes,' 

809 f' got {cls!r}') 

810 cls._is_runtime_protocol = True 

811 return cls 

812 

813 

814# Exists for backwards compatibility. 

815runtime = runtime_checkable 

816 

817 

818# Our version of runtime-checkable protocols is faster on Python 3.7-3.11 

819if sys.version_info >= (3, 12): 

820 SupportsInt = typing.SupportsInt 

821 SupportsFloat = typing.SupportsFloat 

822 SupportsComplex = typing.SupportsComplex 

823 SupportsBytes = typing.SupportsBytes 

824 SupportsIndex = typing.SupportsIndex 

825 SupportsAbs = typing.SupportsAbs 

826 SupportsRound = typing.SupportsRound 

827else: 

828 @runtime_checkable 

829 class SupportsInt(Protocol): 

830 """An ABC with one abstract method __int__.""" 

831 __slots__ = () 

832 

833 @abc.abstractmethod 

834 def __int__(self) -> int: 

835 pass 

836 

837 @runtime_checkable 

838 class SupportsFloat(Protocol): 

839 """An ABC with one abstract method __float__.""" 

840 __slots__ = () 

841 

842 @abc.abstractmethod 

843 def __float__(self) -> float: 

844 pass 

845 

846 @runtime_checkable 

847 class SupportsComplex(Protocol): 

848 """An ABC with one abstract method __complex__.""" 

849 __slots__ = () 

850 

851 @abc.abstractmethod 

852 def __complex__(self) -> complex: 

853 pass 

854 

855 @runtime_checkable 

856 class SupportsBytes(Protocol): 

857 """An ABC with one abstract method __bytes__.""" 

858 __slots__ = () 

859 

860 @abc.abstractmethod 

861 def __bytes__(self) -> bytes: 

862 pass 

863 

864 @runtime_checkable 

865 class SupportsIndex(Protocol): 

866 __slots__ = () 

867 

868 @abc.abstractmethod 

869 def __index__(self) -> int: 

870 pass 

871 

872 @runtime_checkable 

873 class SupportsAbs(Protocol[T_co]): 

874 """ 

875 An ABC with one abstract method __abs__ that is covariant in its return type. 

876 """ 

877 __slots__ = () 

878 

879 @abc.abstractmethod 

880 def __abs__(self) -> T_co: 

881 pass 

882 

883 @runtime_checkable 

884 class SupportsRound(Protocol[T_co]): 

885 """ 

886 An ABC with one abstract method __round__ that is covariant in its return type. 

887 """ 

888 __slots__ = () 

889 

890 @abc.abstractmethod 

891 def __round__(self, ndigits: int = 0) -> T_co: 

892 pass 

893 

894 

895if sys.version_info >= (3, 12): 

896 # The standard library TypedDict in Python 3.8 does not store runtime information 

897 # about which (if any) keys are optional. See https://bugs.python.org/issue38834 

898 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" 

899 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 

900 # The standard library TypedDict below Python 3.11 does not store runtime 

901 # information about optional and required keys when using Required or NotRequired. 

902 # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. 

903 # Aaaand on 3.12 we add __orig_bases__ to TypedDict 

904 # to enable better runtime introspection. 

905 TypedDict = typing.TypedDict 

906 _TypedDictMeta = typing._TypedDictMeta 

907 is_typeddict = typing.is_typeddict 

908else: 

909 def _check_fails(cls, other): 

910 try: 

911 if _caller() not in {'abc', 'functools', 'typing'}: 

912 # Typed dicts are only for static structural subtyping. 

913 raise TypeError('TypedDict does not support instance and class checks') 

914 except (AttributeError, ValueError): 

915 pass 

916 return False 

917 

918 def _dict_new(*args, **kwargs): 

919 if not args: 

920 raise TypeError('TypedDict.__new__(): not enough arguments') 

921 _, args = args[0], args[1:] # allow the "cls" keyword be passed 

922 return dict(*args, **kwargs) 

923 

924 _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)' 

925 

926 def _typeddict_new(*args, total=True, **kwargs): 

927 if not args: 

928 raise TypeError('TypedDict.__new__(): not enough arguments') 

929 _, args = args[0], args[1:] # allow the "cls" keyword be passed 

930 if args: 

931 typename, args = args[0], args[1:] # allow the "_typename" keyword be passed 

932 elif '_typename' in kwargs: 

933 typename = kwargs.pop('_typename') 

934 warnings.warn("Passing '_typename' as keyword argument is deprecated", 

935 DeprecationWarning, stacklevel=2) 

936 else: 

937 raise TypeError("TypedDict.__new__() missing 1 required positional " 

938 "argument: '_typename'") 

939 if args: 

940 try: 

941 fields, = args # allow the "_fields" keyword be passed 

942 except ValueError: 

943 raise TypeError('TypedDict.__new__() takes from 2 to 3 ' 

944 f'positional arguments but {len(args) + 2} ' 

945 'were given') 

946 elif '_fields' in kwargs and len(kwargs) == 1: 

947 fields = kwargs.pop('_fields') 

948 warnings.warn("Passing '_fields' as keyword argument is deprecated", 

949 DeprecationWarning, stacklevel=2) 

950 else: 

951 fields = None 

952 

953 if fields is None: 

954 fields = kwargs 

955 elif kwargs: 

956 raise TypeError("TypedDict takes either a dict or keyword arguments," 

957 " but not both") 

958 

959 if kwargs: 

960 warnings.warn( 

961 "The kwargs-based syntax for TypedDict definitions is deprecated, " 

962 "may be removed in a future version, and may not be " 

963 "understood by third-party type checkers.", 

964 DeprecationWarning, 

965 stacklevel=2, 

966 ) 

967 

968 ns = {'__annotations__': dict(fields)} 

969 module = _caller() 

970 if module is not None: 

971 # Setting correct module is necessary to make typed dict classes pickleable. 

972 ns['__module__'] = module 

973 

974 return _TypedDictMeta(typename, (), ns, total=total) 

975 

976 _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,' 

977 ' /, *, total=True, **kwargs)') 

978 

979 _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters 

980 

981 class _TypedDictMeta(type): 

982 def __init__(cls, name, bases, ns, total=True): 

983 super().__init__(name, bases, ns) 

984 

985 def __new__(cls, name, bases, ns, total=True): 

986 # Create new typed dict class object. 

987 # This method is called directly when TypedDict is subclassed, 

988 # or via _typeddict_new when TypedDict is instantiated. This way 

989 # TypedDict supports all three syntaxes described in its docstring. 

990 # Subclasses and instances of TypedDict return actual dictionaries 

991 # via _dict_new. 

992 ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new 

993 # Don't insert typing.Generic into __bases__ here, 

994 # or Generic.__init_subclass__ will raise TypeError 

995 # in the super().__new__() call. 

996 # Instead, monkey-patch __bases__ onto the class after it's been created. 

997 tp_dict = super().__new__(cls, name, (dict,), ns) 

998 

999 is_generic = any(issubclass(base, typing.Generic) for base in bases) 

1000 

1001 if is_generic: 

1002 tp_dict.__bases__ = (typing.Generic, dict) 

1003 _maybe_adjust_parameters(tp_dict) 

1004 else: 

1005 # generic TypedDicts get __orig_bases__ from Generic 

1006 tp_dict.__orig_bases__ = bases or (TypedDict,) 

1007 

1008 annotations = {} 

1009 own_annotations = ns.get('__annotations__', {}) 

1010 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" 

1011 kwds = {"module": tp_dict.__module__} if _TAKES_MODULE else {} 

1012 own_annotations = { 

1013 n: typing._type_check(tp, msg, **kwds) 

1014 for n, tp in own_annotations.items() 

1015 } 

1016 required_keys = set() 

1017 optional_keys = set() 

1018 

1019 for base in bases: 

1020 annotations.update(base.__dict__.get('__annotations__', {})) 

1021 required_keys.update(base.__dict__.get('__required_keys__', ())) 

1022 optional_keys.update(base.__dict__.get('__optional_keys__', ())) 

1023 

1024 annotations.update(own_annotations) 

1025 for annotation_key, annotation_type in own_annotations.items(): 

1026 annotation_origin = get_origin(annotation_type) 

1027 if annotation_origin is Annotated: 

1028 annotation_args = get_args(annotation_type) 

1029 if annotation_args: 

1030 annotation_type = annotation_args[0] 

1031 annotation_origin = get_origin(annotation_type) 

1032 

1033 if annotation_origin is Required: 

1034 required_keys.add(annotation_key) 

1035 elif annotation_origin is NotRequired: 

1036 optional_keys.add(annotation_key) 

1037 elif total: 

1038 required_keys.add(annotation_key) 

1039 else: 

1040 optional_keys.add(annotation_key) 

1041 

1042 tp_dict.__annotations__ = annotations 

1043 tp_dict.__required_keys__ = frozenset(required_keys) 

1044 tp_dict.__optional_keys__ = frozenset(optional_keys) 

1045 if not hasattr(tp_dict, '__total__'): 

1046 tp_dict.__total__ = total 

1047 return tp_dict 

1048 

1049 __instancecheck__ = __subclasscheck__ = _check_fails 

1050 

1051 TypedDict = _TypedDictMeta('TypedDict', (dict,), {}) 

1052 TypedDict.__module__ = __name__ 

1053 TypedDict.__doc__ = \ 

1054 """A simple typed name space. At runtime it is equivalent to a plain dict. 

1055 

1056 TypedDict creates a dictionary type that expects all of its 

1057 instances to have a certain set of keys, with each key 

1058 associated with a value of a consistent type. This expectation 

1059 is not checked at runtime but is only enforced by type checkers. 

1060 Usage:: 

1061 

1062 class Point2D(TypedDict): 

1063 x: int 

1064 y: int 

1065 label: str 

1066 

1067 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK 

1068 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check 

1069 

1070 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') 

1071 

1072 The type info can be accessed via the Point2D.__annotations__ dict, and 

1073 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. 

1074 TypedDict supports two additional equivalent forms:: 

1075 

1076 Point2D = TypedDict('Point2D', x=int, y=int, label=str) 

1077 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) 

1078 

1079 The class syntax is only supported in Python 3.6+, while two other 

1080 syntax forms work for Python 2.7 and 3.2+ 

1081 """ 

1082 

1083 if hasattr(typing, "_TypedDictMeta"): 

1084 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) 

1085 else: 

1086 _TYPEDDICT_TYPES = (_TypedDictMeta,) 

1087 

1088 def is_typeddict(tp): 

1089 """Check if an annotation is a TypedDict class 

1090 

1091 For example:: 

1092 class Film(TypedDict): 

1093 title: str 

1094 year: int 

1095 

1096 is_typeddict(Film) # => True 

1097 is_typeddict(Union[list, str]) # => False 

1098 """ 

1099 return isinstance(tp, tuple(_TYPEDDICT_TYPES)) 

1100 

1101 

1102if hasattr(typing, "assert_type"): 

1103 assert_type = typing.assert_type 

1104 

1105else: 

1106 def assert_type(__val, __typ): 

1107 """Assert (to the type checker) that the value is of the given type. 

1108 

1109 When the type checker encounters a call to assert_type(), it 

1110 emits an error if the value is not of the specified type:: 

1111 

1112 def greet(name: str) -> None: 

1113 assert_type(name, str) # ok 

1114 assert_type(name, int) # type checker error 

1115 

1116 At runtime this returns the first argument unchanged and otherwise 

1117 does nothing. 

1118 """ 

1119 return __val 

1120 

1121 

1122if hasattr(typing, "Required"): 

1123 get_type_hints = typing.get_type_hints 

1124else: 

1125 # replaces _strip_annotations() 

1126 def _strip_extras(t): 

1127 """Strips Annotated, Required and NotRequired from a given type.""" 

1128 if isinstance(t, _AnnotatedAlias): 

1129 return _strip_extras(t.__origin__) 

1130 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired): 

1131 return _strip_extras(t.__args__[0]) 

1132 if isinstance(t, typing._GenericAlias): 

1133 stripped_args = tuple(_strip_extras(a) for a in t.__args__) 

1134 if stripped_args == t.__args__: 

1135 return t 

1136 return t.copy_with(stripped_args) 

1137 if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias): 

1138 stripped_args = tuple(_strip_extras(a) for a in t.__args__) 

1139 if stripped_args == t.__args__: 

1140 return t 

1141 return _types.GenericAlias(t.__origin__, stripped_args) 

1142 if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType): 

1143 stripped_args = tuple(_strip_extras(a) for a in t.__args__) 

1144 if stripped_args == t.__args__: 

1145 return t 

1146 return functools.reduce(operator.or_, stripped_args) 

1147 

1148 return t 

1149 

1150 def get_type_hints(obj, globalns=None, localns=None, include_extras=False): 

1151 """Return type hints for an object. 

1152 

1153 This is often the same as obj.__annotations__, but it handles 

1154 forward references encoded as string literals, adds Optional[t] if a 

1155 default value equal to None is set and recursively replaces all 

1156 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' 

1157 (unless 'include_extras=True'). 

1158 

1159 The argument may be a module, class, method, or function. The annotations 

1160 are returned as a dictionary. For classes, annotations include also 

1161 inherited members. 

1162 

1163 TypeError is raised if the argument is not of a type that can contain 

1164 annotations, and an empty dictionary is returned if no annotations are 

1165 present. 

1166 

1167 BEWARE -- the behavior of globalns and localns is counterintuitive 

1168 (unless you are familiar with how eval() and exec() work). The 

1169 search order is locals first, then globals. 

1170 

1171 - If no dict arguments are passed, an attempt is made to use the 

1172 globals from obj (or the respective module's globals for classes), 

1173 and these are also used as the locals. If the object does not appear 

1174 to have globals, an empty dictionary is used. 

1175 

1176 - If one dict argument is passed, it is used for both globals and 

1177 locals. 

1178 

1179 - If two dict arguments are passed, they specify globals and 

1180 locals, respectively. 

1181 """ 

1182 if hasattr(typing, "Annotated"): 

1183 hint = typing.get_type_hints( 

1184 obj, globalns=globalns, localns=localns, include_extras=True 

1185 ) 

1186 else: 

1187 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns) 

1188 if include_extras: 

1189 return hint 

1190 return {k: _strip_extras(t) for k, t in hint.items()} 

1191 

1192 

1193# Python 3.9+ has PEP 593 (Annotated) 

1194if hasattr(typing, 'Annotated'): 

1195 Annotated = typing.Annotated 

1196 # Not exported and not a public API, but needed for get_origin() and get_args() 

1197 # to work. 

1198 _AnnotatedAlias = typing._AnnotatedAlias 

1199# 3.7-3.8 

1200else: 

1201 class _AnnotatedAlias(typing._GenericAlias, _root=True): 

1202 """Runtime representation of an annotated type. 

1203 

1204 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' 

1205 with extra annotations. The alias behaves like a normal typing alias, 

1206 instantiating is the same as instantiating the underlying type, binding 

1207 it to types is also the same. 

1208 """ 

1209 def __init__(self, origin, metadata): 

1210 if isinstance(origin, _AnnotatedAlias): 

1211 metadata = origin.__metadata__ + metadata 

1212 origin = origin.__origin__ 

1213 super().__init__(origin, origin) 

1214 self.__metadata__ = metadata 

1215 

1216 def copy_with(self, params): 

1217 assert len(params) == 1 

1218 new_type = params[0] 

1219 return _AnnotatedAlias(new_type, self.__metadata__) 

1220 

1221 def __repr__(self): 

1222 return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, " 

1223 f"{', '.join(repr(a) for a in self.__metadata__)}]") 

1224 

1225 def __reduce__(self): 

1226 return operator.getitem, ( 

1227 Annotated, (self.__origin__,) + self.__metadata__ 

1228 ) 

1229 

1230 def __eq__(self, other): 

1231 if not isinstance(other, _AnnotatedAlias): 

1232 return NotImplemented 

1233 if self.__origin__ != other.__origin__: 

1234 return False 

1235 return self.__metadata__ == other.__metadata__ 

1236 

1237 def __hash__(self): 

1238 return hash((self.__origin__, self.__metadata__)) 

1239 

1240 class Annotated: 

1241 """Add context specific metadata to a type. 

1242 

1243 Example: Annotated[int, runtime_check.Unsigned] indicates to the 

1244 hypothetical runtime_check module that this type is an unsigned int. 

1245 Every other consumer of this type can ignore this metadata and treat 

1246 this type as int. 

1247 

1248 The first argument to Annotated must be a valid type (and will be in 

1249 the __origin__ field), the remaining arguments are kept as a tuple in 

1250 the __extra__ field. 

1251 

1252 Details: 

1253 

1254 - It's an error to call `Annotated` with less than two arguments. 

1255 - Nested Annotated are flattened:: 

1256 

1257 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] 

1258 

1259 - Instantiating an annotated type is equivalent to instantiating the 

1260 underlying type:: 

1261 

1262 Annotated[C, Ann1](5) == C(5) 

1263 

1264 - Annotated can be used as a generic type alias:: 

1265 

1266 Optimized = Annotated[T, runtime.Optimize()] 

1267 Optimized[int] == Annotated[int, runtime.Optimize()] 

1268 

1269 OptimizedList = Annotated[List[T], runtime.Optimize()] 

1270 OptimizedList[int] == Annotated[List[int], runtime.Optimize()] 

1271 """ 

1272 

1273 __slots__ = () 

1274 

1275 def __new__(cls, *args, **kwargs): 

1276 raise TypeError("Type Annotated cannot be instantiated.") 

1277 

1278 @typing._tp_cache 

1279 def __class_getitem__(cls, params): 

1280 if not isinstance(params, tuple) or len(params) < 2: 

1281 raise TypeError("Annotated[...] should be used " 

1282 "with at least two arguments (a type and an " 

1283 "annotation).") 

1284 allowed_special_forms = (ClassVar, Final) 

1285 if get_origin(params[0]) in allowed_special_forms: 

1286 origin = params[0] 

1287 else: 

1288 msg = "Annotated[t, ...]: t must be a type." 

1289 origin = typing._type_check(params[0], msg) 

1290 metadata = tuple(params[1:]) 

1291 return _AnnotatedAlias(origin, metadata) 

1292 

1293 def __init_subclass__(cls, *args, **kwargs): 

1294 raise TypeError( 

1295 f"Cannot subclass {cls.__module__}.Annotated" 

1296 ) 

1297 

1298# Python 3.8 has get_origin() and get_args() but those implementations aren't 

1299# Annotated-aware, so we can't use those. Python 3.9's versions don't support 

1300# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do. 

1301if sys.version_info[:2] >= (3, 10): 

1302 get_origin = typing.get_origin 

1303 get_args = typing.get_args 

1304# 3.7-3.9 

1305else: 

1306 try: 

1307 # 3.9+ 

1308 from typing import _BaseGenericAlias 

1309 except ImportError: 

1310 _BaseGenericAlias = typing._GenericAlias 

1311 try: 

1312 # 3.9+ 

1313 from typing import GenericAlias as _typing_GenericAlias 

1314 except ImportError: 

1315 _typing_GenericAlias = typing._GenericAlias 

1316 

1317 def get_origin(tp): 

1318 """Get the unsubscripted version of a type. 

1319 

1320 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar 

1321 and Annotated. Return None for unsupported types. Examples:: 

1322 

1323 get_origin(Literal[42]) is Literal 

1324 get_origin(int) is None 

1325 get_origin(ClassVar[int]) is ClassVar 

1326 get_origin(Generic) is Generic 

1327 get_origin(Generic[T]) is Generic 

1328 get_origin(Union[T, int]) is Union 

1329 get_origin(List[Tuple[T, T]][int]) == list 

1330 get_origin(P.args) is P 

1331 """ 

1332 if isinstance(tp, _AnnotatedAlias): 

1333 return Annotated 

1334 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias, 

1335 ParamSpecArgs, ParamSpecKwargs)): 

1336 return tp.__origin__ 

1337 if tp is typing.Generic: 

1338 return typing.Generic 

1339 return None 

1340 

1341 def get_args(tp): 

1342 """Get type arguments with all substitutions performed. 

1343 

1344 For unions, basic simplifications used by Union constructor are performed. 

1345 Examples:: 

1346 get_args(Dict[str, int]) == (str, int) 

1347 get_args(int) == () 

1348 get_args(Union[int, Union[T, int], str][int]) == (int, str) 

1349 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) 

1350 get_args(Callable[[], T][int]) == ([], int) 

1351 """ 

1352 if isinstance(tp, _AnnotatedAlias): 

1353 return (tp.__origin__,) + tp.__metadata__ 

1354 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)): 

1355 if getattr(tp, "_special", False): 

1356 return () 

1357 res = tp.__args__ 

1358 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: 

1359 res = (list(res[:-1]), res[-1]) 

1360 return res 

1361 return () 

1362 

1363 

1364# 3.10+ 

1365if hasattr(typing, 'TypeAlias'): 

1366 TypeAlias = typing.TypeAlias 

1367# 3.9 

1368elif sys.version_info[:2] >= (3, 9): 

1369 class _TypeAliasForm(typing._SpecialForm, _root=True): 

1370 def __repr__(self): 

1371 return 'typing_extensions.' + self._name 

1372 

1373 @_TypeAliasForm 

1374 def TypeAlias(self, parameters): 

1375 """Special marker indicating that an assignment should 

1376 be recognized as a proper type alias definition by type 

1377 checkers. 

1378 

1379 For example:: 

1380 

1381 Predicate: TypeAlias = Callable[..., bool] 

1382 

1383 It's invalid when used anywhere except as in the example above. 

1384 """ 

1385 raise TypeError(f"{self} is not subscriptable") 

1386# 3.7-3.8 

1387else: 

1388 class _TypeAliasForm(typing._SpecialForm, _root=True): 

1389 def __repr__(self): 

1390 return 'typing_extensions.' + self._name 

1391 

1392 TypeAlias = _TypeAliasForm('TypeAlias', 

1393 doc="""Special marker indicating that an assignment should 

1394 be recognized as a proper type alias definition by type 

1395 checkers. 

1396 

1397 For example:: 

1398 

1399 Predicate: TypeAlias = Callable[..., bool] 

1400 

1401 It's invalid when used anywhere except as in the example 

1402 above.""") 

1403 

1404 

1405def _set_default(type_param, default): 

1406 if isinstance(default, (tuple, list)): 

1407 type_param.__default__ = tuple((typing._type_check(d, "Default must be a type") 

1408 for d in default)) 

1409 elif default != _marker: 

1410 type_param.__default__ = typing._type_check(default, "Default must be a type") 

1411 else: 

1412 type_param.__default__ = None 

1413 

1414 

1415def _set_module(typevarlike): 

1416 # for pickling: 

1417 def_mod = _caller(depth=3) 

1418 if def_mod != 'typing_extensions': 

1419 typevarlike.__module__ = def_mod 

1420 

1421 

1422class _DefaultMixin: 

1423 """Mixin for TypeVarLike defaults.""" 

1424 

1425 __slots__ = () 

1426 __init__ = _set_default 

1427 

1428 

1429# Classes using this metaclass must provide a _backported_typevarlike ClassVar 

1430class _TypeVarLikeMeta(type): 

1431 def __instancecheck__(cls, __instance: Any) -> bool: 

1432 return isinstance(__instance, cls._backported_typevarlike) 

1433 

1434 

1435# Add default and infer_variance parameters from PEP 696 and 695 

1436class TypeVar(metaclass=_TypeVarLikeMeta): 

1437 """Type variable.""" 

1438 

1439 _backported_typevarlike = typing.TypeVar 

1440 

1441 def __new__(cls, name, *constraints, bound=None, 

1442 covariant=False, contravariant=False, 

1443 default=_marker, infer_variance=False): 

1444 if hasattr(typing, "TypeAliasType"): 

1445 # PEP 695 implemented, can pass infer_variance to typing.TypeVar 

1446 typevar = typing.TypeVar(name, *constraints, bound=bound, 

1447 covariant=covariant, contravariant=contravariant, 

1448 infer_variance=infer_variance) 

1449 else: 

1450 typevar = typing.TypeVar(name, *constraints, bound=bound, 

1451 covariant=covariant, contravariant=contravariant) 

1452 if infer_variance and (covariant or contravariant): 

1453 raise ValueError("Variance cannot be specified with infer_variance.") 

1454 typevar.__infer_variance__ = infer_variance 

1455 _set_default(typevar, default) 

1456 _set_module(typevar) 

1457 return typevar 

1458 

1459 def __init_subclass__(cls) -> None: 

1460 raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type") 

1461 

1462 

1463# Python 3.10+ has PEP 612 

1464if hasattr(typing, 'ParamSpecArgs'): 

1465 ParamSpecArgs = typing.ParamSpecArgs 

1466 ParamSpecKwargs = typing.ParamSpecKwargs 

1467# 3.7-3.9 

1468else: 

1469 class _Immutable: 

1470 """Mixin to indicate that object should not be copied.""" 

1471 __slots__ = () 

1472 

1473 def __copy__(self): 

1474 return self 

1475 

1476 def __deepcopy__(self, memo): 

1477 return self 

1478 

1479 class ParamSpecArgs(_Immutable): 

1480 """The args for a ParamSpec object. 

1481 

1482 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. 

1483 

1484 ParamSpecArgs objects have a reference back to their ParamSpec: 

1485 

1486 P.args.__origin__ is P 

1487 

1488 This type is meant for runtime introspection and has no special meaning to 

1489 static type checkers. 

1490 """ 

1491 def __init__(self, origin): 

1492 self.__origin__ = origin 

1493 

1494 def __repr__(self): 

1495 return f"{self.__origin__.__name__}.args" 

1496 

1497 def __eq__(self, other): 

1498 if not isinstance(other, ParamSpecArgs): 

1499 return NotImplemented 

1500 return self.__origin__ == other.__origin__ 

1501 

1502 class ParamSpecKwargs(_Immutable): 

1503 """The kwargs for a ParamSpec object. 

1504 

1505 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. 

1506 

1507 ParamSpecKwargs objects have a reference back to their ParamSpec: 

1508 

1509 P.kwargs.__origin__ is P 

1510 

1511 This type is meant for runtime introspection and has no special meaning to 

1512 static type checkers. 

1513 """ 

1514 def __init__(self, origin): 

1515 self.__origin__ = origin 

1516 

1517 def __repr__(self): 

1518 return f"{self.__origin__.__name__}.kwargs" 

1519 

1520 def __eq__(self, other): 

1521 if not isinstance(other, ParamSpecKwargs): 

1522 return NotImplemented 

1523 return self.__origin__ == other.__origin__ 

1524 

1525# 3.10+ 

1526if hasattr(typing, 'ParamSpec'): 

1527 

1528 # Add default parameter - PEP 696 

1529 class ParamSpec(metaclass=_TypeVarLikeMeta): 

1530 """Parameter specification.""" 

1531 

1532 _backported_typevarlike = typing.ParamSpec 

1533 

1534 def __new__(cls, name, *, bound=None, 

1535 covariant=False, contravariant=False, 

1536 infer_variance=False, default=_marker): 

1537 if hasattr(typing, "TypeAliasType"): 

1538 # PEP 695 implemented, can pass infer_variance to typing.TypeVar 

1539 paramspec = typing.ParamSpec(name, bound=bound, 

1540 covariant=covariant, 

1541 contravariant=contravariant, 

1542 infer_variance=infer_variance) 

1543 else: 

1544 paramspec = typing.ParamSpec(name, bound=bound, 

1545 covariant=covariant, 

1546 contravariant=contravariant) 

1547 paramspec.__infer_variance__ = infer_variance 

1548 

1549 _set_default(paramspec, default) 

1550 _set_module(paramspec) 

1551 return paramspec 

1552 

1553 def __init_subclass__(cls) -> None: 

1554 raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") 

1555 

1556# 3.7-3.9 

1557else: 

1558 

1559 # Inherits from list as a workaround for Callable checks in Python < 3.9.2. 

1560 class ParamSpec(list, _DefaultMixin): 

1561 """Parameter specification variable. 

1562 

1563 Usage:: 

1564 

1565 P = ParamSpec('P') 

1566 

1567 Parameter specification variables exist primarily for the benefit of static 

1568 type checkers. They are used to forward the parameter types of one 

1569 callable to another callable, a pattern commonly found in higher order 

1570 functions and decorators. They are only valid when used in ``Concatenate``, 

1571 or s the first argument to ``Callable``. In Python 3.10 and higher, 

1572 they are also supported in user-defined Generics at runtime. 

1573 See class Generic for more information on generic types. An 

1574 example for annotating a decorator:: 

1575 

1576 T = TypeVar('T') 

1577 P = ParamSpec('P') 

1578 

1579 def add_logging(f: Callable[P, T]) -> Callable[P, T]: 

1580 '''A type-safe decorator to add logging to a function.''' 

1581 def inner(*args: P.args, **kwargs: P.kwargs) -> T: 

1582 logging.info(f'{f.__name__} was called') 

1583 return f(*args, **kwargs) 

1584 return inner 

1585 

1586 @add_logging 

1587 def add_two(x: float, y: float) -> float: 

1588 '''Add two numbers together.''' 

1589 return x + y 

1590 

1591 Parameter specification variables defined with covariant=True or 

1592 contravariant=True can be used to declare covariant or contravariant 

1593 generic types. These keyword arguments are valid, but their actual semantics 

1594 are yet to be decided. See PEP 612 for details. 

1595 

1596 Parameter specification variables can be introspected. e.g.: 

1597 

1598 P.__name__ == 'T' 

1599 P.__bound__ == None 

1600 P.__covariant__ == False 

1601 P.__contravariant__ == False 

1602 

1603 Note that only parameter specification variables defined in global scope can 

1604 be pickled. 

1605 """ 

1606 

1607 # Trick Generic __parameters__. 

1608 __class__ = typing.TypeVar 

1609 

1610 @property 

1611 def args(self): 

1612 return ParamSpecArgs(self) 

1613 

1614 @property 

1615 def kwargs(self): 

1616 return ParamSpecKwargs(self) 

1617 

1618 def __init__(self, name, *, bound=None, covariant=False, contravariant=False, 

1619 infer_variance=False, default=_marker): 

1620 super().__init__([self]) 

1621 self.__name__ = name 

1622 self.__covariant__ = bool(covariant) 

1623 self.__contravariant__ = bool(contravariant) 

1624 self.__infer_variance__ = bool(infer_variance) 

1625 if bound: 

1626 self.__bound__ = typing._type_check(bound, 'Bound must be a type.') 

1627 else: 

1628 self.__bound__ = None 

1629 _DefaultMixin.__init__(self, default) 

1630 

1631 # for pickling: 

1632 def_mod = _caller() 

1633 if def_mod != 'typing_extensions': 

1634 self.__module__ = def_mod 

1635 

1636 def __repr__(self): 

1637 if self.__infer_variance__: 

1638 prefix = '' 

1639 elif self.__covariant__: 

1640 prefix = '+' 

1641 elif self.__contravariant__: 

1642 prefix = '-' 

1643 else: 

1644 prefix = '~' 

1645 return prefix + self.__name__ 

1646 

1647 def __hash__(self): 

1648 return object.__hash__(self) 

1649 

1650 def __eq__(self, other): 

1651 return self is other 

1652 

1653 def __reduce__(self): 

1654 return self.__name__ 

1655 

1656 # Hack to get typing._type_check to pass. 

1657 def __call__(self, *args, **kwargs): 

1658 pass 

1659 

1660 

1661# 3.7-3.9 

1662if not hasattr(typing, 'Concatenate'): 

1663 # Inherits from list as a workaround for Callable checks in Python < 3.9.2. 

1664 class _ConcatenateGenericAlias(list): 

1665 

1666 # Trick Generic into looking into this for __parameters__. 

1667 __class__ = typing._GenericAlias 

1668 

1669 # Flag in 3.8. 

1670 _special = False 

1671 

1672 def __init__(self, origin, args): 

1673 super().__init__(args) 

1674 self.__origin__ = origin 

1675 self.__args__ = args 

1676 

1677 def __repr__(self): 

1678 _type_repr = typing._type_repr 

1679 return (f'{_type_repr(self.__origin__)}' 

1680 f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]') 

1681 

1682 def __hash__(self): 

1683 return hash((self.__origin__, self.__args__)) 

1684 

1685 # Hack to get typing._type_check to pass in Generic. 

1686 def __call__(self, *args, **kwargs): 

1687 pass 

1688 

1689 @property 

1690 def __parameters__(self): 

1691 return tuple( 

1692 tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec)) 

1693 ) 

1694 

1695 

1696# 3.7-3.9 

1697@typing._tp_cache 

1698def _concatenate_getitem(self, parameters): 

1699 if parameters == (): 

1700 raise TypeError("Cannot take a Concatenate of no types.") 

1701 if not isinstance(parameters, tuple): 

1702 parameters = (parameters,) 

1703 if not isinstance(parameters[-1], ParamSpec): 

1704 raise TypeError("The last parameter to Concatenate should be a " 

1705 "ParamSpec variable.") 

1706 msg = "Concatenate[arg, ...]: each arg must be a type." 

1707 parameters = tuple(typing._type_check(p, msg) for p in parameters) 

1708 return _ConcatenateGenericAlias(self, parameters) 

1709 

1710 

1711# 3.10+ 

1712if hasattr(typing, 'Concatenate'): 

1713 Concatenate = typing.Concatenate 

1714 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811 

1715# 3.9 

1716elif sys.version_info[:2] >= (3, 9): 

1717 @_TypeAliasForm 

1718 def Concatenate(self, parameters): 

1719 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a 

1720 higher order function which adds, removes or transforms parameters of a 

1721 callable. 

1722 

1723 For example:: 

1724 

1725 Callable[Concatenate[int, P], int] 

1726 

1727 See PEP 612 for detailed information. 

1728 """ 

1729 return _concatenate_getitem(self, parameters) 

1730# 3.7-8 

1731else: 

1732 class _ConcatenateForm(typing._SpecialForm, _root=True): 

1733 def __repr__(self): 

1734 return 'typing_extensions.' + self._name 

1735 

1736 def __getitem__(self, parameters): 

1737 return _concatenate_getitem(self, parameters) 

1738 

1739 Concatenate = _ConcatenateForm( 

1740 'Concatenate', 

1741 doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a 

1742 higher order function which adds, removes or transforms parameters of a 

1743 callable. 

1744 

1745 For example:: 

1746 

1747 Callable[Concatenate[int, P], int] 

1748 

1749 See PEP 612 for detailed information. 

1750 """) 

1751 

1752# 3.10+ 

1753if hasattr(typing, 'TypeGuard'): 

1754 TypeGuard = typing.TypeGuard 

1755# 3.9 

1756elif sys.version_info[:2] >= (3, 9): 

1757 class _TypeGuardForm(typing._SpecialForm, _root=True): 

1758 def __repr__(self): 

1759 return 'typing_extensions.' + self._name 

1760 

1761 @_TypeGuardForm 

1762 def TypeGuard(self, parameters): 

1763 """Special typing form used to annotate the return type of a user-defined 

1764 type guard function. ``TypeGuard`` only accepts a single type argument. 

1765 At runtime, functions marked this way should return a boolean. 

1766 

1767 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static 

1768 type checkers to determine a more precise type of an expression within a 

1769 program's code flow. Usually type narrowing is done by analyzing 

1770 conditional code flow and applying the narrowing to a block of code. The 

1771 conditional expression here is sometimes referred to as a "type guard". 

1772 

1773 Sometimes it would be convenient to use a user-defined boolean function 

1774 as a type guard. Such a function should use ``TypeGuard[...]`` as its 

1775 return type to alert static type checkers to this intention. 

1776 

1777 Using ``-> TypeGuard`` tells the static type checker that for a given 

1778 function: 

1779 

1780 1. The return value is a boolean. 

1781 2. If the return value is ``True``, the type of its argument 

1782 is the type inside ``TypeGuard``. 

1783 

1784 For example:: 

1785 

1786 def is_str(val: Union[str, float]): 

1787 # "isinstance" type guard 

1788 if isinstance(val, str): 

1789 # Type of ``val`` is narrowed to ``str`` 

1790 ... 

1791 else: 

1792 # Else, type of ``val`` is narrowed to ``float``. 

1793 ... 

1794 

1795 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower 

1796 form of ``TypeA`` (it can even be a wider form) and this may lead to 

1797 type-unsafe results. The main reason is to allow for things like 

1798 narrowing ``List[object]`` to ``List[str]`` even though the latter is not 

1799 a subtype of the former, since ``List`` is invariant. The responsibility of 

1800 writing type-safe type guards is left to the user. 

1801 

1802 ``TypeGuard`` also works with type variables. For more information, see 

1803 PEP 647 (User-Defined Type Guards). 

1804 """ 

1805 item = typing._type_check(parameters, f'{self} accepts only a single type.') 

1806 return typing._GenericAlias(self, (item,)) 

1807# 3.7-3.8 

1808else: 

1809 class _TypeGuardForm(typing._SpecialForm, _root=True): 

1810 

1811 def __repr__(self): 

1812 return 'typing_extensions.' + self._name 

1813 

1814 def __getitem__(self, parameters): 

1815 item = typing._type_check(parameters, 

1816 f'{self._name} accepts only a single type') 

1817 return typing._GenericAlias(self, (item,)) 

1818 

1819 TypeGuard = _TypeGuardForm( 

1820 'TypeGuard', 

1821 doc="""Special typing form used to annotate the return type of a user-defined 

1822 type guard function. ``TypeGuard`` only accepts a single type argument. 

1823 At runtime, functions marked this way should return a boolean. 

1824 

1825 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static 

1826 type checkers to determine a more precise type of an expression within a 

1827 program's code flow. Usually type narrowing is done by analyzing 

1828 conditional code flow and applying the narrowing to a block of code. The 

1829 conditional expression here is sometimes referred to as a "type guard". 

1830 

1831 Sometimes it would be convenient to use a user-defined boolean function 

1832 as a type guard. Such a function should use ``TypeGuard[...]`` as its 

1833 return type to alert static type checkers to this intention. 

1834 

1835 Using ``-> TypeGuard`` tells the static type checker that for a given 

1836 function: 

1837 

1838 1. The return value is a boolean. 

1839 2. If the return value is ``True``, the type of its argument 

1840 is the type inside ``TypeGuard``. 

1841 

1842 For example:: 

1843 

1844 def is_str(val: Union[str, float]): 

1845 # "isinstance" type guard 

1846 if isinstance(val, str): 

1847 # Type of ``val`` is narrowed to ``str`` 

1848 ... 

1849 else: 

1850 # Else, type of ``val`` is narrowed to ``float``. 

1851 ... 

1852 

1853 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower 

1854 form of ``TypeA`` (it can even be a wider form) and this may lead to 

1855 type-unsafe results. The main reason is to allow for things like 

1856 narrowing ``List[object]`` to ``List[str]`` even though the latter is not 

1857 a subtype of the former, since ``List`` is invariant. The responsibility of 

1858 writing type-safe type guards is left to the user. 

1859 

1860 ``TypeGuard`` also works with type variables. For more information, see 

1861 PEP 647 (User-Defined Type Guards). 

1862 """) 

1863 

1864 

1865# Vendored from cpython typing._SpecialFrom 

1866class _SpecialForm(typing._Final, _root=True): 

1867 __slots__ = ('_name', '__doc__', '_getitem') 

1868 

1869 def __init__(self, getitem): 

1870 self._getitem = getitem 

1871 self._name = getitem.__name__ 

1872 self.__doc__ = getitem.__doc__ 

1873 

1874 def __getattr__(self, item): 

1875 if item in {'__name__', '__qualname__'}: 

1876 return self._name 

1877 

1878 raise AttributeError(item) 

1879 

1880 def __mro_entries__(self, bases): 

1881 raise TypeError(f"Cannot subclass {self!r}") 

1882 

1883 def __repr__(self): 

1884 return f'typing_extensions.{self._name}' 

1885 

1886 def __reduce__(self): 

1887 return self._name 

1888 

1889 def __call__(self, *args, **kwds): 

1890 raise TypeError(f"Cannot instantiate {self!r}") 

1891 

1892 def __or__(self, other): 

1893 return typing.Union[self, other] 

1894 

1895 def __ror__(self, other): 

1896 return typing.Union[other, self] 

1897 

1898 def __instancecheck__(self, obj): 

1899 raise TypeError(f"{self} cannot be used with isinstance()") 

1900 

1901 def __subclasscheck__(self, cls): 

1902 raise TypeError(f"{self} cannot be used with issubclass()") 

1903 

1904 @typing._tp_cache 

1905 def __getitem__(self, parameters): 

1906 return self._getitem(self, parameters) 

1907 

1908 

1909if hasattr(typing, "LiteralString"): 

1910 LiteralString = typing.LiteralString 

1911else: 

1912 @_SpecialForm 

1913 def LiteralString(self, params): 

1914 """Represents an arbitrary literal string. 

1915 

1916 Example:: 

1917 

1918 from typing_extensions import LiteralString 

1919 

1920 def query(sql: LiteralString) -> ...: 

1921 ... 

1922 

1923 query("SELECT * FROM table") # ok 

1924 query(f"SELECT * FROM {input()}") # not ok 

1925 

1926 See PEP 675 for details. 

1927 

1928 """ 

1929 raise TypeError(f"{self} is not subscriptable") 

1930 

1931 

1932if hasattr(typing, "Self"): 

1933 Self = typing.Self 

1934else: 

1935 @_SpecialForm 

1936 def Self(self, params): 

1937 """Used to spell the type of "self" in classes. 

1938 

1939 Example:: 

1940 

1941 from typing import Self 

1942 

1943 class ReturnsSelf: 

1944 def parse(self, data: bytes) -> Self: 

1945 ... 

1946 return self 

1947 

1948 """ 

1949 

1950 raise TypeError(f"{self} is not subscriptable") 

1951 

1952 

1953if hasattr(typing, "Never"): 

1954 Never = typing.Never 

1955else: 

1956 @_SpecialForm 

1957 def Never(self, params): 

1958 """The bottom type, a type that has no members. 

1959 

1960 This can be used to define a function that should never be 

1961 called, or a function that never returns:: 

1962 

1963 from typing_extensions import Never 

1964 

1965 def never_call_me(arg: Never) -> None: 

1966 pass 

1967 

1968 def int_or_str(arg: int | str) -> None: 

1969 never_call_me(arg) # type checker error 

1970 match arg: 

1971 case int(): 

1972 print("It's an int") 

1973 case str(): 

1974 print("It's a str") 

1975 case _: 

1976 never_call_me(arg) # ok, arg is of type Never 

1977 

1978 """ 

1979 

1980 raise TypeError(f"{self} is not subscriptable") 

1981 

1982 

1983if hasattr(typing, 'Required'): 

1984 Required = typing.Required 

1985 NotRequired = typing.NotRequired 

1986elif sys.version_info[:2] >= (3, 9): 

1987 class _ExtensionsSpecialForm(typing._SpecialForm, _root=True): 

1988 def __repr__(self): 

1989 return 'typing_extensions.' + self._name 

1990 

1991 @_ExtensionsSpecialForm 

1992 def Required(self, parameters): 

1993 """A special typing construct to mark a key of a total=False TypedDict 

1994 as required. For example: 

1995 

1996 class Movie(TypedDict, total=False): 

1997 title: Required[str] 

1998 year: int 

1999 

2000 m = Movie( 

2001 title='The Matrix', # typechecker error if key is omitted 

2002 year=1999, 

2003 ) 

2004 

2005 There is no runtime checking that a required key is actually provided 

2006 when instantiating a related TypedDict. 

2007 """ 

2008 item = typing._type_check(parameters, f'{self._name} accepts only a single type.') 

2009 return typing._GenericAlias(self, (item,)) 

2010 

2011 @_ExtensionsSpecialForm 

2012 def NotRequired(self, parameters): 

2013 """A special typing construct to mark a key of a TypedDict as 

2014 potentially missing. For example: 

2015 

2016 class Movie(TypedDict): 

2017 title: str 

2018 year: NotRequired[int] 

2019 

2020 m = Movie( 

2021 title='The Matrix', # typechecker error if key is omitted 

2022 year=1999, 

2023 ) 

2024 """ 

2025 item = typing._type_check(parameters, f'{self._name} accepts only a single type.') 

2026 return typing._GenericAlias(self, (item,)) 

2027 

2028else: 

2029 class _RequiredForm(typing._SpecialForm, _root=True): 

2030 def __repr__(self): 

2031 return 'typing_extensions.' + self._name 

2032 

2033 def __getitem__(self, parameters): 

2034 item = typing._type_check(parameters, 

2035 f'{self._name} accepts only a single type.') 

2036 return typing._GenericAlias(self, (item,)) 

2037 

2038 Required = _RequiredForm( 

2039 'Required', 

2040 doc="""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 NotRequired = _RequiredForm( 

2056 'NotRequired', 

2057 doc="""A special typing construct to mark a key of a TypedDict as 

2058 potentially missing. For example: 

2059 

2060 class Movie(TypedDict): 

2061 title: str 

2062 year: NotRequired[int] 

2063 

2064 m = Movie( 

2065 title='The Matrix', # typechecker error if key is omitted 

2066 year=1999, 

2067 ) 

2068 """) 

2069 

2070 

2071_UNPACK_DOC = """\ 

2072Type unpack operator. 

2073 

2074The type unpack operator takes the child types from some container type, 

2075such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For 

2076example: 

2077 

2078 # For some generic class `Foo`: 

2079 Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] 

2080 

2081 Ts = TypeVarTuple('Ts') 

2082 # Specifies that `Bar` is generic in an arbitrary number of types. 

2083 # (Think of `Ts` as a tuple of an arbitrary number of individual 

2084 # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the 

2085 # `Generic[]`.) 

2086 class Bar(Generic[Unpack[Ts]]): ... 

2087 Bar[int] # Valid 

2088 Bar[int, str] # Also valid 

2089 

2090From Python 3.11, this can also be done using the `*` operator: 

2091 

2092 Foo[*tuple[int, str]] 

2093 class Bar(Generic[*Ts]): ... 

2094 

2095The operator can also be used along with a `TypedDict` to annotate 

2096`**kwargs` in a function signature. For instance: 

2097 

2098 class Movie(TypedDict): 

2099 name: str 

2100 year: int 

2101 

2102 # This function expects two keyword arguments - *name* of type `str` and 

2103 # *year* of type `int`. 

2104 def foo(**kwargs: Unpack[Movie]): ... 

2105 

2106Note that there is only some runtime checking of this operator. Not 

2107everything the runtime allows may be accepted by static type checkers. 

2108 

2109For more information, see PEP 646 and PEP 692. 

2110""" 

2111 

2112 

2113if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[] 

2114 Unpack = typing.Unpack 

2115 

2116 def _is_unpack(obj): 

2117 return get_origin(obj) is Unpack 

2118 

2119elif sys.version_info[:2] >= (3, 9): 

2120 class _UnpackSpecialForm(typing._SpecialForm, _root=True): 

2121 def __init__(self, getitem): 

2122 super().__init__(getitem) 

2123 self.__doc__ = _UNPACK_DOC 

2124 

2125 def __repr__(self): 

2126 return 'typing_extensions.' + self._name 

2127 

2128 class _UnpackAlias(typing._GenericAlias, _root=True): 

2129 __class__ = typing.TypeVar 

2130 

2131 @_UnpackSpecialForm 

2132 def Unpack(self, parameters): 

2133 item = typing._type_check(parameters, f'{self._name} accepts only a single type.') 

2134 return _UnpackAlias(self, (item,)) 

2135 

2136 def _is_unpack(obj): 

2137 return isinstance(obj, _UnpackAlias) 

2138 

2139else: 

2140 class _UnpackAlias(typing._GenericAlias, _root=True): 

2141 __class__ = typing.TypeVar 

2142 

2143 class _UnpackForm(typing._SpecialForm, _root=True): 

2144 def __repr__(self): 

2145 return 'typing_extensions.' + self._name 

2146 

2147 def __getitem__(self, parameters): 

2148 item = typing._type_check(parameters, 

2149 f'{self._name} accepts only a single type.') 

2150 return _UnpackAlias(self, (item,)) 

2151 

2152 Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC) 

2153 

2154 def _is_unpack(obj): 

2155 return isinstance(obj, _UnpackAlias) 

2156 

2157 

2158if hasattr(typing, "TypeVarTuple"): # 3.11+ 

2159 

2160 # Add default parameter - PEP 696 

2161 class TypeVarTuple(metaclass=_TypeVarLikeMeta): 

2162 """Type variable tuple.""" 

2163 

2164 _backported_typevarlike = typing.TypeVarTuple 

2165 

2166 def __new__(cls, name, *, default=_marker): 

2167 tvt = typing.TypeVarTuple(name) 

2168 _set_default(tvt, default) 

2169 _set_module(tvt) 

2170 return tvt 

2171 

2172 def __init_subclass__(self, *args, **kwds): 

2173 raise TypeError("Cannot subclass special typing classes") 

2174 

2175else: 

2176 class TypeVarTuple(_DefaultMixin): 

2177 """Type variable tuple. 

2178 

2179 Usage:: 

2180 

2181 Ts = TypeVarTuple('Ts') 

2182 

2183 In the same way that a normal type variable is a stand-in for a single 

2184 type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* 

2185 type such as ``Tuple[int, str]``. 

2186 

2187 Type variable tuples can be used in ``Generic`` declarations. 

2188 Consider the following example:: 

2189 

2190 class Array(Generic[*Ts]): ... 

2191 

2192 The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``, 

2193 where ``T1`` and ``T2`` are type variables. To use these type variables 

2194 as type parameters of ``Array``, we must *unpack* the type variable tuple using 

2195 the star operator: ``*Ts``. The signature of ``Array`` then behaves 

2196 as if we had simply written ``class Array(Generic[T1, T2]): ...``. 

2197 In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows 

2198 us to parameterise the class with an *arbitrary* number of type parameters. 

2199 

2200 Type variable tuples can be used anywhere a normal ``TypeVar`` can. 

2201 This includes class definitions, as shown above, as well as function 

2202 signatures and variable annotations:: 

2203 

2204 class Array(Generic[*Ts]): 

2205 

2206 def __init__(self, shape: Tuple[*Ts]): 

2207 self._shape: Tuple[*Ts] = shape 

2208 

2209 def get_shape(self) -> Tuple[*Ts]: 

2210 return self._shape 

2211 

2212 shape = (Height(480), Width(640)) 

2213 x: Array[Height, Width] = Array(shape) 

2214 y = abs(x) # Inferred type is Array[Height, Width] 

2215 z = x + x # ... is Array[Height, Width] 

2216 x.get_shape() # ... is tuple[Height, Width] 

2217 

2218 """ 

2219 

2220 # Trick Generic __parameters__. 

2221 __class__ = typing.TypeVar 

2222 

2223 def __iter__(self): 

2224 yield self.__unpacked__ 

2225 

2226 def __init__(self, name, *, default=_marker): 

2227 self.__name__ = name 

2228 _DefaultMixin.__init__(self, default) 

2229 

2230 # for pickling: 

2231 def_mod = _caller() 

2232 if def_mod != 'typing_extensions': 

2233 self.__module__ = def_mod 

2234 

2235 self.__unpacked__ = Unpack[self] 

2236 

2237 def __repr__(self): 

2238 return self.__name__ 

2239 

2240 def __hash__(self): 

2241 return object.__hash__(self) 

2242 

2243 def __eq__(self, other): 

2244 return self is other 

2245 

2246 def __reduce__(self): 

2247 return self.__name__ 

2248 

2249 def __init_subclass__(self, *args, **kwds): 

2250 if '_root' not in kwds: 

2251 raise TypeError("Cannot subclass special typing classes") 

2252 

2253 

2254if hasattr(typing, "reveal_type"): 

2255 reveal_type = typing.reveal_type 

2256else: 

2257 def reveal_type(__obj: T) -> T: 

2258 """Reveal the inferred type of a variable. 

2259 

2260 When a static type checker encounters a call to ``reveal_type()``, 

2261 it will emit the inferred type of the argument:: 

2262 

2263 x: int = 1 

2264 reveal_type(x) 

2265 

2266 Running a static type checker (e.g., ``mypy``) on this example 

2267 will produce output similar to 'Revealed type is "builtins.int"'. 

2268 

2269 At runtime, the function prints the runtime type of the 

2270 argument and returns it unchanged. 

2271 

2272 """ 

2273 print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr) 

2274 return __obj 

2275 

2276 

2277if hasattr(typing, "assert_never"): 

2278 assert_never = typing.assert_never 

2279else: 

2280 def assert_never(__arg: Never) -> Never: 

2281 """Assert to the type checker that a line of code is unreachable. 

2282 

2283 Example:: 

2284 

2285 def int_or_str(arg: int | str) -> None: 

2286 match arg: 

2287 case int(): 

2288 print("It's an int") 

2289 case str(): 

2290 print("It's a str") 

2291 case _: 

2292 assert_never(arg) 

2293 

2294 If a type checker finds that a call to assert_never() is 

2295 reachable, it will emit an error. 

2296 

2297 At runtime, this throws an exception when called. 

2298 

2299 """ 

2300 raise AssertionError("Expected code to be unreachable") 

2301 

2302 

2303if sys.version_info >= (3, 12): 

2304 # dataclass_transform exists in 3.11 but lacks the frozen_default parameter 

2305 dataclass_transform = typing.dataclass_transform 

2306else: 

2307 def dataclass_transform( 

2308 *, 

2309 eq_default: bool = True, 

2310 order_default: bool = False, 

2311 kw_only_default: bool = False, 

2312 frozen_default: bool = False, 

2313 field_specifiers: typing.Tuple[ 

2314 typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]], 

2315 ... 

2316 ] = (), 

2317 **kwargs: typing.Any, 

2318 ) -> typing.Callable[[T], T]: 

2319 """Decorator that marks a function, class, or metaclass as providing 

2320 dataclass-like behavior. 

2321 

2322 Example: 

2323 

2324 from typing_extensions import dataclass_transform 

2325 

2326 _T = TypeVar("_T") 

2327 

2328 # Used on a decorator function 

2329 @dataclass_transform() 

2330 def create_model(cls: type[_T]) -> type[_T]: 

2331 ... 

2332 return cls 

2333 

2334 @create_model 

2335 class CustomerModel: 

2336 id: int 

2337 name: str 

2338 

2339 # Used on a base class 

2340 @dataclass_transform() 

2341 class ModelBase: ... 

2342 

2343 class CustomerModel(ModelBase): 

2344 id: int 

2345 name: str 

2346 

2347 # Used on a metaclass 

2348 @dataclass_transform() 

2349 class ModelMeta(type): ... 

2350 

2351 class ModelBase(metaclass=ModelMeta): ... 

2352 

2353 class CustomerModel(ModelBase): 

2354 id: int 

2355 name: str 

2356 

2357 Each of the ``CustomerModel`` classes defined in this example will now 

2358 behave similarly to a dataclass created with the ``@dataclasses.dataclass`` 

2359 decorator. For example, the type checker will synthesize an ``__init__`` 

2360 method. 

2361 

2362 The arguments to this decorator can be used to customize this behavior: 

2363 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be 

2364 True or False if it is omitted by the caller. 

2365 - ``order_default`` indicates whether the ``order`` parameter is 

2366 assumed to be True or False if it is omitted by the caller. 

2367 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is 

2368 assumed to be True or False if it is omitted by the caller. 

2369 - ``frozen_default`` indicates whether the ``frozen`` parameter is 

2370 assumed to be True or False if it is omitted by the caller. 

2371 - ``field_specifiers`` specifies a static list of supported classes 

2372 or functions that describe fields, similar to ``dataclasses.field()``. 

2373 

2374 At runtime, this decorator records its arguments in the 

2375 ``__dataclass_transform__`` attribute on the decorated object. 

2376 

2377 See PEP 681 for details. 

2378 

2379 """ 

2380 def decorator(cls_or_fn): 

2381 cls_or_fn.__dataclass_transform__ = { 

2382 "eq_default": eq_default, 

2383 "order_default": order_default, 

2384 "kw_only_default": kw_only_default, 

2385 "frozen_default": frozen_default, 

2386 "field_specifiers": field_specifiers, 

2387 "kwargs": kwargs, 

2388 } 

2389 return cls_or_fn 

2390 return decorator 

2391 

2392 

2393if hasattr(typing, "override"): 

2394 override = typing.override 

2395else: 

2396 _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any]) 

2397 

2398 def override(__arg: _F) -> _F: 

2399 """Indicate that a method is intended to override a method in a base class. 

2400 

2401 Usage: 

2402 

2403 class Base: 

2404 def method(self) -> None: ... 

2405 pass 

2406 

2407 class Child(Base): 

2408 @override 

2409 def method(self) -> None: 

2410 super().method() 

2411 

2412 When this decorator is applied to a method, the type checker will 

2413 validate that it overrides a method with the same name on a base class. 

2414 This helps prevent bugs that may occur when a base class is changed 

2415 without an equivalent change to a child class. 

2416 

2417 There is no runtime checking of these properties. The decorator 

2418 sets the ``__override__`` attribute to ``True`` on the decorated object 

2419 to allow runtime introspection. 

2420 

2421 See PEP 698 for details. 

2422 

2423 """ 

2424 try: 

2425 __arg.__override__ = True 

2426 except (AttributeError, TypeError): 

2427 # Skip the attribute silently if it is not writable. 

2428 # AttributeError happens if the object has __slots__ or a 

2429 # read-only property, TypeError if it's a builtin class. 

2430 pass 

2431 return __arg 

2432 

2433 

2434if hasattr(typing, "deprecated"): 

2435 deprecated = typing.deprecated 

2436else: 

2437 _T = typing.TypeVar("_T") 

2438 

2439 def deprecated( 

2440 __msg: str, 

2441 *, 

2442 category: typing.Optional[typing.Type[Warning]] = DeprecationWarning, 

2443 stacklevel: int = 1, 

2444 ) -> typing.Callable[[_T], _T]: 

2445 """Indicate that a class, function or overload is deprecated. 

2446 

2447 Usage: 

2448 

2449 @deprecated("Use B instead") 

2450 class A: 

2451 pass 

2452 

2453 @deprecated("Use g instead") 

2454 def f(): 

2455 pass 

2456 

2457 @overload 

2458 @deprecated("int support is deprecated") 

2459 def g(x: int) -> int: ... 

2460 @overload 

2461 def g(x: str) -> int: ... 

2462 

2463 When this decorator is applied to an object, the type checker 

2464 will generate a diagnostic on usage of the deprecated object. 

2465 

2466 The warning specified by ``category`` will be emitted on use 

2467 of deprecated objects. For functions, that happens on calls; 

2468 for classes, on instantiation. If the ``category`` is ``None``, 

2469 no warning is emitted. The ``stacklevel`` determines where the 

2470 warning is emitted. If it is ``1`` (the default), the warning 

2471 is emitted at the direct caller of the deprecated object; if it 

2472 is higher, it is emitted further up the stack. 

2473 

2474 The decorator sets the ``__deprecated__`` 

2475 attribute on the decorated object to the deprecation message 

2476 passed to the decorator. If applied to an overload, the decorator 

2477 must be after the ``@overload`` decorator for the attribute to 

2478 exist on the overload as returned by ``get_overloads()``. 

2479 

2480 See PEP 702 for details. 

2481 

2482 """ 

2483 def decorator(__arg: _T) -> _T: 

2484 if category is None: 

2485 __arg.__deprecated__ = __msg 

2486 return __arg 

2487 elif isinstance(__arg, type): 

2488 original_new = __arg.__new__ 

2489 has_init = __arg.__init__ is not object.__init__ 

2490 

2491 @functools.wraps(original_new) 

2492 def __new__(cls, *args, **kwargs): 

2493 warnings.warn(__msg, category=category, stacklevel=stacklevel + 1) 

2494 if original_new is not object.__new__: 

2495 return original_new(cls, *args, **kwargs) 

2496 # Mirrors a similar check in object.__new__. 

2497 elif not has_init and (args or kwargs): 

2498 raise TypeError(f"{cls.__name__}() takes no arguments") 

2499 else: 

2500 return original_new(cls) 

2501 

2502 __arg.__new__ = staticmethod(__new__) 

2503 __arg.__deprecated__ = __new__.__deprecated__ = __msg 

2504 return __arg 

2505 elif callable(__arg): 

2506 @functools.wraps(__arg) 

2507 def wrapper(*args, **kwargs): 

2508 warnings.warn(__msg, category=category, stacklevel=stacklevel + 1) 

2509 return __arg(*args, **kwargs) 

2510 

2511 __arg.__deprecated__ = wrapper.__deprecated__ = __msg 

2512 return wrapper 

2513 else: 

2514 raise TypeError( 

2515 "@deprecated decorator with non-None category must be applied to " 

2516 f"a class or callable, not {__arg!r}" 

2517 ) 

2518 

2519 return decorator 

2520 

2521 

2522# We have to do some monkey patching to deal with the dual nature of 

2523# Unpack/TypeVarTuple: 

2524# - We want Unpack to be a kind of TypeVar so it gets accepted in 

2525# Generic[Unpack[Ts]] 

2526# - We want it to *not* be treated as a TypeVar for the purposes of 

2527# counting generic parameters, so that when we subscript a generic, 

2528# the runtime doesn't try to substitute the Unpack with the subscripted type. 

2529if not hasattr(typing, "TypeVarTuple"): 

2530 typing._collect_type_vars = _collect_type_vars 

2531 typing._check_generic = _check_generic 

2532 

2533 

2534# Backport typing.NamedTuple as it exists in Python 3.12. 

2535# In 3.11, the ability to define generic `NamedTuple`s was supported. 

2536# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8. 

2537# On 3.12, we added __orig_bases__ to call-based NamedTuples 

2538if sys.version_info >= (3, 12): 

2539 NamedTuple = typing.NamedTuple 

2540else: 

2541 def _make_nmtuple(name, types, module, defaults=()): 

2542 fields = [n for n, t in types] 

2543 annotations = {n: typing._type_check(t, f"field {n} annotation must be a type") 

2544 for n, t in types} 

2545 nm_tpl = collections.namedtuple(name, fields, 

2546 defaults=defaults, module=module) 

2547 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations 

2548 # The `_field_types` attribute was removed in 3.9; 

2549 # in earlier versions, it is the same as the `__annotations__` attribute 

2550 if sys.version_info < (3, 9): 

2551 nm_tpl._field_types = annotations 

2552 return nm_tpl 

2553 

2554 _prohibited_namedtuple_fields = typing._prohibited 

2555 _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'}) 

2556 

2557 class _NamedTupleMeta(type): 

2558 def __new__(cls, typename, bases, ns): 

2559 assert _NamedTuple in bases 

2560 for base in bases: 

2561 if base is not _NamedTuple and base is not typing.Generic: 

2562 raise TypeError( 

2563 'can only inherit from a NamedTuple type and Generic') 

2564 bases = tuple(tuple if base is _NamedTuple else base for base in bases) 

2565 types = ns.get('__annotations__', {}) 

2566 default_names = [] 

2567 for field_name in types: 

2568 if field_name in ns: 

2569 default_names.append(field_name) 

2570 elif default_names: 

2571 raise TypeError(f"Non-default namedtuple field {field_name} " 

2572 f"cannot follow default field" 

2573 f"{'s' if len(default_names) > 1 else ''} " 

2574 f"{', '.join(default_names)}") 

2575 nm_tpl = _make_nmtuple( 

2576 typename, types.items(), 

2577 defaults=[ns[n] for n in default_names], 

2578 module=ns['__module__'] 

2579 ) 

2580 nm_tpl.__bases__ = bases 

2581 if typing.Generic in bases: 

2582 class_getitem = typing.Generic.__class_getitem__.__func__ 

2583 nm_tpl.__class_getitem__ = classmethod(class_getitem) 

2584 # update from user namespace without overriding special namedtuple attributes 

2585 for key in ns: 

2586 if key in _prohibited_namedtuple_fields: 

2587 raise AttributeError("Cannot overwrite NamedTuple attribute " + key) 

2588 elif key not in _special_namedtuple_fields and key not in nm_tpl._fields: 

2589 setattr(nm_tpl, key, ns[key]) 

2590 if typing.Generic in bases: 

2591 nm_tpl.__init_subclass__() 

2592 return nm_tpl 

2593 

2594 def NamedTuple(__typename, __fields=None, **kwargs): 

2595 if __fields is None: 

2596 __fields = kwargs.items() 

2597 elif kwargs: 

2598 raise TypeError("Either list of fields or keywords" 

2599 " can be provided to NamedTuple, not both") 

2600 nt = _make_nmtuple(__typename, __fields, module=_caller()) 

2601 nt.__orig_bases__ = (NamedTuple,) 

2602 return nt 

2603 

2604 NamedTuple.__doc__ = typing.NamedTuple.__doc__ 

2605 _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {}) 

2606 

2607 # On 3.8+, alter the signature so that it matches typing.NamedTuple. 

2608 # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7, 

2609 # so just leave the signature as it is on 3.7. 

2610 if sys.version_info >= (3, 8): 

2611 NamedTuple.__text_signature__ = '(typename, fields=None, /, **kwargs)' 

2612 

2613 def _namedtuple_mro_entries(bases): 

2614 assert NamedTuple in bases 

2615 return (_NamedTuple,) 

2616 

2617 NamedTuple.__mro_entries__ = _namedtuple_mro_entries 

2618 

2619 

2620if hasattr(collections.abc, "Buffer"): 

2621 Buffer = collections.abc.Buffer 

2622else: 

2623 class Buffer(abc.ABC): 

2624 """Base class for classes that implement the buffer protocol. 

2625 

2626 The buffer protocol allows Python objects to expose a low-level 

2627 memory buffer interface. Before Python 3.12, it is not possible 

2628 to implement the buffer protocol in pure Python code, or even 

2629 to check whether a class implements the buffer protocol. In 

2630 Python 3.12 and higher, the ``__buffer__`` method allows access 

2631 to the buffer protocol from Python code, and the 

2632 ``collections.abc.Buffer`` ABC allows checking whether a class 

2633 implements the buffer protocol. 

2634 

2635 To indicate support for the buffer protocol in earlier versions, 

2636 inherit from this ABC, either in a stub file or at runtime, 

2637 or use ABC registration. This ABC provides no methods, because 

2638 there is no Python-accessible methods shared by pre-3.12 buffer 

2639 classes. It is useful primarily for static checks. 

2640 

2641 """ 

2642 

2643 # As a courtesy, register the most common stdlib buffer classes. 

2644 Buffer.register(memoryview) 

2645 Buffer.register(bytearray) 

2646 Buffer.register(bytes) 

2647 

2648 

2649# Backport of types.get_original_bases, available on 3.12+ in CPython 

2650if hasattr(_types, "get_original_bases"): 

2651 get_original_bases = _types.get_original_bases 

2652else: 

2653 def get_original_bases(__cls): 

2654 """Return the class's "original" bases prior to modification by `__mro_entries__`. 

2655 

2656 Examples:: 

2657 

2658 from typing import TypeVar, Generic 

2659 from typing_extensions import NamedTuple, TypedDict 

2660 

2661 T = TypeVar("T") 

2662 class Foo(Generic[T]): ... 

2663 class Bar(Foo[int], float): ... 

2664 class Baz(list[str]): ... 

2665 Eggs = NamedTuple("Eggs", [("a", int), ("b", str)]) 

2666 Spam = TypedDict("Spam", {"a": int, "b": str}) 

2667 

2668 assert get_original_bases(Bar) == (Foo[int], float) 

2669 assert get_original_bases(Baz) == (list[str],) 

2670 assert get_original_bases(Eggs) == (NamedTuple,) 

2671 assert get_original_bases(Spam) == (TypedDict,) 

2672 assert get_original_bases(int) == (object,) 

2673 """ 

2674 try: 

2675 return __cls.__orig_bases__ 

2676 except AttributeError: 

2677 try: 

2678 return __cls.__bases__ 

2679 except AttributeError: 

2680 raise TypeError( 

2681 f'Expected an instance of type, not {type(__cls).__name__!r}' 

2682 ) from None 

2683 

2684 

2685# NewType is a class on Python 3.10+, making it pickleable 

2686# The error message for subclassing instances of NewType was improved on 3.11+ 

2687if sys.version_info >= (3, 11): 

2688 NewType = typing.NewType 

2689else: 

2690 class NewType: 

2691 """NewType creates simple unique types with almost zero 

2692 runtime overhead. NewType(name, tp) is considered a subtype of tp 

2693 by static type checkers. At runtime, NewType(name, tp) returns 

2694 a dummy callable that simply returns its argument. Usage:: 

2695 UserId = NewType('UserId', int) 

2696 def name_by_id(user_id: UserId) -> str: 

2697 ... 

2698 UserId('user') # Fails type check 

2699 name_by_id(42) # Fails type check 

2700 name_by_id(UserId(42)) # OK 

2701 num = UserId(5) + 1 # type: int 

2702 """ 

2703 

2704 def __call__(self, obj): 

2705 return obj 

2706 

2707 def __init__(self, name, tp): 

2708 self.__qualname__ = name 

2709 if '.' in name: 

2710 name = name.rpartition('.')[-1] 

2711 self.__name__ = name 

2712 self.__supertype__ = tp 

2713 def_mod = _caller() 

2714 if def_mod != 'typing_extensions': 

2715 self.__module__ = def_mod 

2716 

2717 def __mro_entries__(self, bases): 

2718 # We defined __mro_entries__ to get a better error message 

2719 # if a user attempts to subclass a NewType instance. bpo-46170 

2720 supercls_name = self.__name__ 

2721 

2722 class Dummy: 

2723 def __init_subclass__(cls): 

2724 subcls_name = cls.__name__ 

2725 raise TypeError( 

2726 f"Cannot subclass an instance of NewType. " 

2727 f"Perhaps you were looking for: " 

2728 f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`" 

2729 ) 

2730 

2731 return (Dummy,) 

2732 

2733 def __repr__(self): 

2734 return f'{self.__module__}.{self.__qualname__}' 

2735 

2736 def __reduce__(self): 

2737 return self.__qualname__ 

2738 

2739 if sys.version_info >= (3, 10): 

2740 # PEP 604 methods 

2741 # It doesn't make sense to have these methods on Python <3.10 

2742 

2743 def __or__(self, other): 

2744 return typing.Union[self, other] 

2745 

2746 def __ror__(self, other): 

2747 return typing.Union[other, self] 

2748 

2749 

2750if hasattr(typing, "TypeAliasType"): 

2751 TypeAliasType = typing.TypeAliasType 

2752else: 

2753 def _is_unionable(obj): 

2754 """Corresponds to is_unionable() in unionobject.c in CPython.""" 

2755 return obj is None or isinstance(obj, ( 

2756 type, 

2757 _types.GenericAlias, 

2758 _types.UnionType, 

2759 TypeAliasType, 

2760 )) 

2761 

2762 class TypeAliasType: 

2763 """Create named, parameterized type aliases. 

2764 

2765 This provides a backport of the new `type` statement in Python 3.12: 

2766 

2767 type ListOrSet[T] = list[T] | set[T] 

2768 

2769 is equivalent to: 

2770 

2771 T = TypeVar("T") 

2772 ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,)) 

2773 

2774 The name ListOrSet can then be used as an alias for the type it refers to. 

2775 

2776 The type_params argument should contain all the type parameters used 

2777 in the value of the type alias. If the alias is not generic, this 

2778 argument is omitted. 

2779 

2780 Static type checkers should only support type aliases declared using 

2781 TypeAliasType that follow these rules: 

2782 

2783 - The first argument (the name) must be a string literal. 

2784 - The TypeAliasType instance must be immediately assigned to a variable 

2785 of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid, 

2786 as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)'). 

2787 

2788 """ 

2789 

2790 def __init__(self, name: str, value, *, type_params=()): 

2791 if not isinstance(name, str): 

2792 raise TypeError("TypeAliasType name must be a string") 

2793 self.__value__ = value 

2794 self.__type_params__ = type_params 

2795 

2796 parameters = [] 

2797 for type_param in type_params: 

2798 if isinstance(type_param, TypeVarTuple): 

2799 parameters.extend(type_param) 

2800 else: 

2801 parameters.append(type_param) 

2802 self.__parameters__ = tuple(parameters) 

2803 def_mod = _caller() 

2804 if def_mod != 'typing_extensions': 

2805 self.__module__ = def_mod 

2806 # Setting this attribute closes the TypeAliasType from further modification 

2807 self.__name__ = name 

2808 

2809 def __setattr__(self, __name: str, __value: object) -> None: 

2810 if hasattr(self, "__name__"): 

2811 self._raise_attribute_error(__name) 

2812 super().__setattr__(__name, __value) 

2813 

2814 def __delattr__(self, __name: str) -> Never: 

2815 self._raise_attribute_error(__name) 

2816 

2817 def _raise_attribute_error(self, name: str) -> Never: 

2818 # Match the Python 3.12 error messages exactly 

2819 if name == "__name__": 

2820 raise AttributeError("readonly attribute") 

2821 elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}: 

2822 raise AttributeError( 

2823 f"attribute '{name}' of 'typing.TypeAliasType' objects " 

2824 "is not writable" 

2825 ) 

2826 else: 

2827 raise AttributeError( 

2828 f"'typing.TypeAliasType' object has no attribute '{name}'" 

2829 ) 

2830 

2831 def __repr__(self) -> str: 

2832 return self.__name__ 

2833 

2834 def __getitem__(self, parameters): 

2835 if not isinstance(parameters, tuple): 

2836 parameters = (parameters,) 

2837 parameters = [ 

2838 typing._type_check( 

2839 item, f'Subscripting {self.__name__} requires a type.' 

2840 ) 

2841 for item in parameters 

2842 ] 

2843 return typing._GenericAlias(self, tuple(parameters)) 

2844 

2845 def __reduce__(self): 

2846 return self.__name__ 

2847 

2848 def __init_subclass__(cls, *args, **kwargs): 

2849 raise TypeError( 

2850 "type 'typing_extensions.TypeAliasType' is not an acceptable base type" 

2851 ) 

2852 

2853 # The presence of this method convinces typing._type_check 

2854 # that TypeAliasTypes are types. 

2855 def __call__(self): 

2856 raise TypeError("Type alias is not callable") 

2857 

2858 if sys.version_info >= (3, 10): 

2859 def __or__(self, right): 

2860 # For forward compatibility with 3.12, reject Unions 

2861 # that are not accepted by the built-in Union. 

2862 if not _is_unionable(right): 

2863 return NotImplemented 

2864 return typing.Union[self, right] 

2865 

2866 def __ror__(self, left): 

2867 if not _is_unionable(left): 

2868 return NotImplemented 

2869 return typing.Union[left, self]