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

1102 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-25 06:43 +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 'Doc', 

64 'get_overloads', 

65 'final', 

66 'get_args', 

67 'get_origin', 

68 'get_original_bases', 

69 'get_protocol_members', 

70 'get_type_hints', 

71 'IntVar', 

72 'is_protocol', 

73 'is_typeddict', 

74 'Literal', 

75 'NewType', 

76 'overload', 

77 'override', 

78 'Protocol', 

79 'reveal_type', 

80 'runtime', 

81 'runtime_checkable', 

82 'Text', 

83 'TypeAlias', 

84 'TypeAliasType', 

85 'TypeGuard', 

86 'TYPE_CHECKING', 

87 'Never', 

88 'NoReturn', 

89 'Required', 

90 'NotRequired', 

91 

92 # Pure aliases, have always been in typing 

93 'AbstractSet', 

94 'AnyStr', 

95 'BinaryIO', 

96 'Callable', 

97 'Collection', 

98 'Container', 

99 'Dict', 

100 'ForwardRef', 

101 'FrozenSet', 

102 'Generator', 

103 'Generic', 

104 'Hashable', 

105 'IO', 

106 'ItemsView', 

107 'Iterable', 

108 'Iterator', 

109 'KeysView', 

110 'List', 

111 'Mapping', 

112 'MappingView', 

113 'Match', 

114 'MutableMapping', 

115 'MutableSequence', 

116 'MutableSet', 

117 'Optional', 

118 'Pattern', 

119 'Reversible', 

120 'Sequence', 

121 'Set', 

122 'Sized', 

123 'TextIO', 

124 'Tuple', 

125 'Union', 

126 'ValuesView', 

127 'cast', 

128 'no_type_check', 

129 'no_type_check_decorator', 

130] 

131 

132# for backward compatibility 

133PEP_560 = True 

134GenericMeta = type 

135 

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

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

138 

139 

140class _Sentinel: 

141 def __repr__(self): 

142 return "<sentinel>" 

143 

144 

145_marker = _Sentinel() 

146 

147 

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

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

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

151 """ 

152 if not elen: 

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

154 if elen is _marker: 

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

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

157 elen = len(cls.__parameters__) 

158 alen = len(parameters) 

159 if alen != elen: 

160 if hasattr(cls, "__parameters__"): 

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

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

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

164 return 

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

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

167 

168 

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

170 def _should_collect_from_parameters(t): 

171 return isinstance( 

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

173 ) 

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

175 def _should_collect_from_parameters(t): 

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

177else: 

178 def _should_collect_from_parameters(t): 

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

180 

181 

182def _collect_type_vars(types, typevar_types=None): 

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

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

185 

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

187 """ 

188 if typevar_types is None: 

189 typevar_types = typing.TypeVar 

190 tvars = [] 

191 for t in types: 

192 if ( 

193 isinstance(t, typevar_types) and 

194 t not in tvars and 

195 not _is_unpack(t) 

196 ): 

197 tvars.append(t) 

198 if _should_collect_from_parameters(t): 

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

200 return tuple(tvars) 

201 

202 

203NoReturn = typing.NoReturn 

204 

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

206# (These are not for export.) 

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

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

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

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

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

212 

213 

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

215 from typing import Any 

216else: 

217 

218 class _AnyMeta(type): 

219 def __instancecheck__(self, obj): 

220 if self is Any: 

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

222 return super().__instancecheck__(obj) 

223 

224 def __repr__(self): 

225 if self is Any: 

226 return "typing_extensions.Any" 

227 return super().__repr__() 

228 

229 class Any(metaclass=_AnyMeta): 

230 """Special type indicating an unconstrained type. 

231 - Any is compatible with every type. 

232 - Any assumed to have all methods. 

233 - All values assumed to be instances of Any. 

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

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

236 checks. 

237 """ 

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

239 if cls is Any: 

240 raise TypeError("Any cannot be instantiated") 

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

242 

243 

244ClassVar = typing.ClassVar 

245 

246 

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

248 def __repr__(self): 

249 return 'typing_extensions.' + self._name 

250 

251 

252Final = typing.Final 

253 

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

255 final = typing.final 

256else: 

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

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

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

260 def final(f): 

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

262 the decorated method cannot be overridden, and decorated class 

263 cannot be subclassed. For example: 

264 

265 class Base: 

266 @final 

267 def done(self) -> None: 

268 ... 

269 class Sub(Base): 

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

271 ... 

272 @final 

273 class Leaf: 

274 ... 

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

276 ... 

277 

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

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

280 to allow runtime introspection. 

281 """ 

282 try: 

283 f.__final__ = True 

284 except (AttributeError, TypeError): 

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

286 # AttributeError happens if the object has __slots__ or a 

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

288 pass 

289 return f 

290 

291 

292def IntVar(name): 

293 return typing.TypeVar(name) 

294 

295 

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

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

298 Literal = typing.Literal 

299else: 

300 def _flatten_literal_params(parameters): 

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

302 params = [] 

303 for p in parameters: 

304 if isinstance(p, _LiteralGenericAlias): 

305 params.extend(p.__args__) 

306 else: 

307 params.append(p) 

308 return tuple(params) 

309 

310 def _value_and_type_iter(params): 

311 for p in params: 

312 yield p, type(p) 

313 

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

315 def __eq__(self, other): 

316 if not isinstance(other, _LiteralGenericAlias): 

317 return NotImplemented 

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

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

320 return these_args_deduped == other_args_deduped 

321 

322 def __hash__(self): 

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

324 

325 class _LiteralForm(_ExtensionsSpecialForm, _root=True): 

326 def __init__(self, doc: str): 

327 self._name = 'Literal' 

328 self._doc = self.__doc__ = doc 

329 

330 def __getitem__(self, parameters): 

331 if not isinstance(parameters, tuple): 

332 parameters = (parameters,) 

333 

334 parameters = _flatten_literal_params(parameters) 

335 

336 val_type_pairs = list(_value_and_type_iter(parameters)) 

337 try: 

338 deduped_pairs = set(val_type_pairs) 

339 except TypeError: 

340 # unhashable parameters 

341 pass 

342 else: 

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

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

345 new_parameters = [] 

346 for pair in val_type_pairs: 

347 if pair in deduped_pairs: 

348 new_parameters.append(pair[0]) 

349 deduped_pairs.remove(pair) 

350 assert not deduped_pairs, deduped_pairs 

351 parameters = tuple(new_parameters) 

352 

353 return _LiteralGenericAlias(self, parameters) 

354 

355 Literal = _LiteralForm(doc="""\ 

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

357 that the corresponding value has a value literally equivalent 

358 to the provided parameter. For example: 

359 

360 var: Literal[4] = 4 

361 

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

363 the value 4 and no other value. 

364 

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

366 checking verifying that the parameter is actually a value 

367 instead of a type.""") 

368 

369 

370_overload_dummy = typing._overload_dummy 

371 

372 

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

374 overload = typing.overload 

375 get_overloads = typing.get_overloads 

376 clear_overloads = typing.clear_overloads 

377else: 

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

379 _overload_registry = collections.defaultdict( 

380 functools.partial(collections.defaultdict, dict) 

381 ) 

382 

383 def overload(func): 

384 """Decorator for overloaded functions/methods. 

385 

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

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

388 

389 @overload 

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

391 @overload 

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

393 @overload 

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

395 

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

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

398 be decorated with @overload. For example: 

399 

400 @overload 

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

402 @overload 

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

404 @overload 

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

406 def utf8(value): 

407 # implementation goes here 

408 

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

410 get_overloads() function. 

411 """ 

412 # classmethod and staticmethod 

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

414 try: 

415 _overload_registry[f.__module__][f.__qualname__][ 

416 f.__code__.co_firstlineno 

417 ] = func 

418 except AttributeError: 

419 # Not a normal function; ignore. 

420 pass 

421 return _overload_dummy 

422 

423 def get_overloads(func): 

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

425 # classmethod and staticmethod 

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

427 if f.__module__ not in _overload_registry: 

428 return [] 

429 mod_dict = _overload_registry[f.__module__] 

430 if f.__qualname__ not in mod_dict: 

431 return [] 

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

433 

434 def clear_overloads(): 

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

436 _overload_registry.clear() 

437 

438 

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

440Type = typing.Type 

441 

442# Various ABCs mimicking those in collections.abc. 

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

444Awaitable = typing.Awaitable 

445Coroutine = typing.Coroutine 

446AsyncIterable = typing.AsyncIterable 

447AsyncIterator = typing.AsyncIterator 

448Deque = typing.Deque 

449ContextManager = typing.ContextManager 

450AsyncContextManager = typing.AsyncContextManager 

451DefaultDict = typing.DefaultDict 

452OrderedDict = typing.OrderedDict 

453Counter = typing.Counter 

454ChainMap = typing.ChainMap 

455AsyncGenerator = typing.AsyncGenerator 

456Text = typing.Text 

457TYPE_CHECKING = typing.TYPE_CHECKING 

458 

459 

460_PROTO_ALLOWLIST = { 

461 'collections.abc': [ 

462 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', 

463 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer', 

464 ], 

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

466 'typing_extensions': ['Buffer'], 

467} 

468 

469 

470_EXCLUDED_ATTRS = { 

471 "__abstractmethods__", "__annotations__", "__weakref__", "_is_protocol", 

472 "_is_runtime_protocol", "__dict__", "__slots__", "__parameters__", 

473 "__orig_bases__", "__module__", "_MutableMapping__marker", "__doc__", 

474 "__subclasshook__", "__orig_class__", "__init__", "__new__", 

475 "__protocol_attrs__", "__callable_proto_members_only__", 

476} 

477 

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

479 _EXCLUDED_ATTRS.add("__class_getitem__") 

480 

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

482 _EXCLUDED_ATTRS.add("__type_params__") 

483 

484_EXCLUDED_ATTRS = frozenset(_EXCLUDED_ATTRS) 

485 

486 

487def _get_protocol_attrs(cls): 

488 attrs = set() 

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

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

491 continue 

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

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

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

495 attrs.add(attr) 

496 return attrs 

497 

498 

499def _caller(depth=2): 

500 try: 

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

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

503 return None 

504 

505 

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

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

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

509 Protocol = typing.Protocol 

510else: 

511 def _allow_reckless_class_checks(depth=3): 

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

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

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

515 """ 

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

517 

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

519 if type(self)._is_protocol: 

520 raise TypeError('Protocols cannot be instantiated') 

521 

522 # Inheriting from typing._ProtocolMeta isn't actually desirable, 

523 # but is necessary to allow typing.Protocol and typing_extensions.Protocol 

524 # to mix without getting TypeErrors about "metaclass conflict" 

525 class _ProtocolMeta(type(typing.Protocol)): 

526 # This metaclass is somewhat unfortunate, 

527 # but is necessary for several reasons... 

528 # 

529 # NOTE: DO NOT call super() in any methods in this class 

530 # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11 

531 # and those are slow 

532 def __new__(mcls, name, bases, namespace, **kwargs): 

533 if name == "Protocol" and len(bases) < 2: 

534 pass 

535 elif {Protocol, typing.Protocol} & set(bases): 

536 for base in bases: 

537 if not ( 

538 base in {object, typing.Generic, Protocol, typing.Protocol} 

539 or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, []) 

540 or is_protocol(base) 

541 ): 

542 raise TypeError( 

543 f"Protocols can only inherit from other protocols, " 

544 f"got {base!r}" 

545 ) 

546 return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs) 

547 

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

549 abc.ABCMeta.__init__(cls, *args, **kwargs) 

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

551 cls.__protocol_attrs__ = _get_protocol_attrs(cls) 

552 # PEP 544 prohibits using issubclass() 

553 # with protocols that have non-method members. 

554 cls.__callable_proto_members_only__ = all( 

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

556 ) 

557 

558 def __subclasscheck__(cls, other): 

559 if cls is Protocol: 

560 return type.__subclasscheck__(cls, other) 

561 if ( 

562 getattr(cls, '_is_protocol', False) 

563 and not _allow_reckless_class_checks() 

564 ): 

565 if not isinstance(other, type): 

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

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

568 if ( 

569 not cls.__callable_proto_members_only__ 

570 and cls.__dict__.get("__subclasshook__") is _proto_hook 

571 ): 

572 raise TypeError( 

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

574 ) 

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

576 raise TypeError( 

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

578 "@runtime_checkable protocols" 

579 ) 

580 return abc.ABCMeta.__subclasscheck__(cls, other) 

581 

582 def __instancecheck__(cls, instance): 

583 # We need this method for situations where attributes are 

584 # assigned in __init__. 

585 if cls is Protocol: 

586 return type.__instancecheck__(cls, instance) 

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

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

589 return abc.ABCMeta.__instancecheck__(cls, instance) 

590 

591 if ( 

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

593 not _allow_reckless_class_checks() 

594 ): 

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

596 " @runtime_checkable protocols") 

597 

598 if abc.ABCMeta.__instancecheck__(cls, instance): 

599 return True 

600 

601 for attr in cls.__protocol_attrs__: 

602 try: 

603 val = inspect.getattr_static(instance, attr) 

604 except AttributeError: 

605 break 

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

607 break 

608 else: 

609 return True 

610 

611 return False 

612 

613 def __eq__(cls, other): 

614 # Hack so that typing.Generic.__class_getitem__ 

615 # treats typing_extensions.Protocol 

616 # as equivalent to typing.Protocol 

617 if abc.ABCMeta.__eq__(cls, other) is True: 

618 return True 

619 return cls is Protocol and other is typing.Protocol 

620 

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

622 # complains about classes with this metaclass being unhashable, 

623 # if we define only __eq__! 

624 def __hash__(cls) -> int: 

625 return type.__hash__(cls) 

626 

627 @classmethod 

628 def _proto_hook(cls, other): 

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

630 return NotImplemented 

631 

632 for attr in cls.__protocol_attrs__: 

633 for base in other.__mro__: 

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

635 if attr in base.__dict__: 

636 if base.__dict__[attr] is None: 

637 return NotImplemented 

638 break 

639 

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

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

642 if ( 

643 isinstance(annotations, collections.abc.Mapping) 

644 and attr in annotations 

645 and is_protocol(other) 

646 ): 

647 break 

648 else: 

649 return NotImplemented 

650 return True 

651 

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

653 __doc__ = typing.Protocol.__doc__ 

654 __slots__ = () 

655 _is_protocol = True 

656 _is_runtime_protocol = False 

657 

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

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

660 

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

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

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

664 

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

666 if '__subclasshook__' not in cls.__dict__: 

667 cls.__subclasshook__ = _proto_hook 

668 

669 # Prohibit instantiation for protocol classes 

670 if cls._is_protocol and cls.__init__ is Protocol.__init__: 

671 cls.__init__ = _no_init 

672 

673 

674# The "runtime" alias exists for backwards compatibility. 

675runtime = runtime_checkable = typing.runtime_checkable 

676 

677 

678# Our version of runtime-checkable protocols is faster on Python 3.8-3.11 

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

680 SupportsInt = typing.SupportsInt 

681 SupportsFloat = typing.SupportsFloat 

682 SupportsComplex = typing.SupportsComplex 

683 SupportsBytes = typing.SupportsBytes 

684 SupportsIndex = typing.SupportsIndex 

685 SupportsAbs = typing.SupportsAbs 

686 SupportsRound = typing.SupportsRound 

687else: 

688 @runtime_checkable 

689 class SupportsInt(Protocol): 

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

691 __slots__ = () 

692 

693 @abc.abstractmethod 

694 def __int__(self) -> int: 

695 pass 

696 

697 @runtime_checkable 

698 class SupportsFloat(Protocol): 

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

700 __slots__ = () 

701 

702 @abc.abstractmethod 

703 def __float__(self) -> float: 

704 pass 

705 

706 @runtime_checkable 

707 class SupportsComplex(Protocol): 

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

709 __slots__ = () 

710 

711 @abc.abstractmethod 

712 def __complex__(self) -> complex: 

713 pass 

714 

715 @runtime_checkable 

716 class SupportsBytes(Protocol): 

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

718 __slots__ = () 

719 

720 @abc.abstractmethod 

721 def __bytes__(self) -> bytes: 

722 pass 

723 

724 @runtime_checkable 

725 class SupportsIndex(Protocol): 

726 __slots__ = () 

727 

728 @abc.abstractmethod 

729 def __index__(self) -> int: 

730 pass 

731 

732 @runtime_checkable 

733 class SupportsAbs(Protocol[T_co]): 

734 """ 

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

736 """ 

737 __slots__ = () 

738 

739 @abc.abstractmethod 

740 def __abs__(self) -> T_co: 

741 pass 

742 

743 @runtime_checkable 

744 class SupportsRound(Protocol[T_co]): 

745 """ 

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

747 """ 

748 __slots__ = () 

749 

750 @abc.abstractmethod 

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

752 pass 

753 

754 

755def _ensure_subclassable(mro_entries): 

756 def inner(func): 

757 if sys.implementation.name == "pypy" and sys.version_info < (3, 9): 

758 cls_dict = { 

759 "__call__": staticmethod(func), 

760 "__mro_entries__": staticmethod(mro_entries) 

761 } 

762 t = type(func.__name__, (), cls_dict) 

763 return functools.update_wrapper(t(), func) 

764 else: 

765 func.__mro_entries__ = mro_entries 

766 return func 

767 return inner 

768 

769 

770if sys.version_info >= (3, 13): 

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

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

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

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

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

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

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

778 # Aaaand on 3.12 we add __orig_bases__ to TypedDict 

779 # to enable better runtime introspection. 

780 # On 3.13 we deprecate some odd ways of creating TypedDicts. 

781 TypedDict = typing.TypedDict 

782 _TypedDictMeta = typing._TypedDictMeta 

783 is_typeddict = typing.is_typeddict 

784else: 

785 # 3.10.0 and later 

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

787 

788 class _TypedDictMeta(type): 

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

790 """Create new typed dict class object. 

791 

792 This method is called when TypedDict is subclassed, 

793 or when TypedDict is instantiated. This way 

794 TypedDict supports all three syntax forms described in its docstring. 

795 Subclasses and instances of TypedDict return actual dictionaries. 

796 """ 

797 for base in bases: 

798 if type(base) is not _TypedDictMeta and base is not typing.Generic: 

799 raise TypeError('cannot inherit from both a TypedDict type ' 

800 'and a non-TypedDict base class') 

801 

802 if any(issubclass(b, typing.Generic) for b in bases): 

803 generic_base = (typing.Generic,) 

804 else: 

805 generic_base = () 

806 

807 # typing.py generally doesn't let you inherit from plain Generic, unless 

808 # the name of the class happens to be "Protocol" 

809 tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns) 

810 tp_dict.__name__ = name 

811 if tp_dict.__qualname__ == "Protocol": 

812 tp_dict.__qualname__ = name 

813 

814 if not hasattr(tp_dict, '__orig_bases__'): 

815 tp_dict.__orig_bases__ = bases 

816 

817 annotations = {} 

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

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

820 if _TAKES_MODULE: 

821 own_annotations = { 

822 n: typing._type_check(tp, msg, module=tp_dict.__module__) 

823 for n, tp in own_annotations.items() 

824 } 

825 else: 

826 own_annotations = { 

827 n: typing._type_check(tp, msg) 

828 for n, tp in own_annotations.items() 

829 } 

830 required_keys = set() 

831 optional_keys = set() 

832 

833 for base in bases: 

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

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

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

837 

838 annotations.update(own_annotations) 

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

840 annotation_origin = get_origin(annotation_type) 

841 if annotation_origin is Annotated: 

842 annotation_args = get_args(annotation_type) 

843 if annotation_args: 

844 annotation_type = annotation_args[0] 

845 annotation_origin = get_origin(annotation_type) 

846 

847 if annotation_origin is Required: 

848 required_keys.add(annotation_key) 

849 elif annotation_origin is NotRequired: 

850 optional_keys.add(annotation_key) 

851 elif total: 

852 required_keys.add(annotation_key) 

853 else: 

854 optional_keys.add(annotation_key) 

855 

856 tp_dict.__annotations__ = annotations 

857 tp_dict.__required_keys__ = frozenset(required_keys) 

858 tp_dict.__optional_keys__ = frozenset(optional_keys) 

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

860 tp_dict.__total__ = total 

861 return tp_dict 

862 

863 __call__ = dict # static method 

864 

865 def __subclasscheck__(cls, other): 

866 # Typed dicts are only for static structural subtyping. 

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

868 

869 __instancecheck__ = __subclasscheck__ 

870 

871 _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) 

872 

873 @_ensure_subclassable(lambda bases: (_TypedDict,)) 

874 def TypedDict(typename, fields=_marker, /, *, total=True, **kwargs): 

875 """A simple typed namespace. At runtime it is equivalent to a plain dict. 

876 

877 TypedDict creates a dictionary type such that a type checker will expect all 

878 instances to have a certain set of keys, where each key is 

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

880 is not checked at runtime. 

881 

882 Usage:: 

883 

884 class Point2D(TypedDict): 

885 x: int 

886 y: int 

887 label: str 

888 

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

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

891 

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

893 

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

895 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. 

896 TypedDict supports an additional equivalent form:: 

897 

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

899 

900 By default, all keys must be present in a TypedDict. It is possible 

901 to override this by specifying totality:: 

902 

903 class Point2D(TypedDict, total=False): 

904 x: int 

905 y: int 

906 

907 This means that a Point2D TypedDict can have any of the keys omitted. A type 

908 checker is only expected to support a literal False or True as the value of 

909 the total argument. True is the default, and makes all items defined in the 

910 class body be required. 

911 

912 The Required and NotRequired special forms can also be used to mark 

913 individual keys as being required or not required:: 

914 

915 class Point2D(TypedDict): 

916 x: int # the "x" key must always be present (Required is the default) 

917 y: NotRequired[int] # the "y" key can be omitted 

918 

919 See PEP 655 for more details on Required and NotRequired. 

920 """ 

921 if fields is _marker or fields is None: 

922 if fields is _marker: 

923 deprecated_thing = "Failing to pass a value for the 'fields' parameter" 

924 else: 

925 deprecated_thing = "Passing `None` as the 'fields' parameter" 

926 

927 example = f"`{typename} = TypedDict({typename!r}, {{}})`" 

928 deprecation_msg = ( 

929 f"{deprecated_thing} is deprecated and will be disallowed in " 

930 "Python 3.15. To create a TypedDict class with 0 fields " 

931 "using the functional syntax, pass an empty dictionary, e.g. " 

932 ) + example + "." 

933 warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) 

934 fields = kwargs 

935 elif kwargs: 

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

937 " but not both") 

938 if kwargs: 

939 warnings.warn( 

940 "The kwargs-based syntax for TypedDict definitions is deprecated " 

941 "in Python 3.11, will be removed in Python 3.13, and may not be " 

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

943 DeprecationWarning, 

944 stacklevel=2, 

945 ) 

946 

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

948 module = _caller() 

949 if module is not None: 

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

951 ns['__module__'] = module 

952 

953 td = _TypedDictMeta(typename, (), ns, total=total) 

954 td.__orig_bases__ = (TypedDict,) 

955 return td 

956 

957 if hasattr(typing, "_TypedDictMeta"): 

958 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) 

959 else: 

960 _TYPEDDICT_TYPES = (_TypedDictMeta,) 

961 

962 def is_typeddict(tp): 

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

964 

965 For example:: 

966 class Film(TypedDict): 

967 title: str 

968 year: int 

969 

970 is_typeddict(Film) # => True 

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

972 """ 

973 # On 3.8, this would otherwise return True 

974 if hasattr(typing, "TypedDict") and tp is typing.TypedDict: 

975 return False 

976 return isinstance(tp, _TYPEDDICT_TYPES) 

977 

978 

979if hasattr(typing, "assert_type"): 

980 assert_type = typing.assert_type 

981 

982else: 

983 def assert_type(val, typ, /): 

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

985 

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

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

988 

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

990 assert_type(name, str) # ok 

991 assert_type(name, int) # type checker error 

992 

993 At runtime this returns the first argument unchanged and otherwise 

994 does nothing. 

995 """ 

996 return val 

997 

998 

999if hasattr(typing, "Required"): # 3.11+ 

1000 get_type_hints = typing.get_type_hints 

1001else: # <=3.10 

1002 # replaces _strip_annotations() 

1003 def _strip_extras(t): 

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

1005 if isinstance(t, _AnnotatedAlias): 

1006 return _strip_extras(t.__origin__) 

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

1008 return _strip_extras(t.__args__[0]) 

1009 if isinstance(t, typing._GenericAlias): 

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

1011 if stripped_args == t.__args__: 

1012 return t 

1013 return t.copy_with(stripped_args) 

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

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

1016 if stripped_args == t.__args__: 

1017 return t 

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

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

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

1021 if stripped_args == t.__args__: 

1022 return t 

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

1024 

1025 return t 

1026 

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

1028 """Return type hints for an object. 

1029 

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

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

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

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

1034 (unless 'include_extras=True'). 

1035 

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

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

1038 inherited members. 

1039 

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

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

1042 present. 

1043 

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

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

1046 search order is locals first, then globals. 

1047 

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

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

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

1051 to have globals, an empty dictionary is used. 

1052 

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

1054 locals. 

1055 

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

1057 locals, respectively. 

1058 """ 

1059 if hasattr(typing, "Annotated"): # 3.9+ 

1060 hint = typing.get_type_hints( 

1061 obj, globalns=globalns, localns=localns, include_extras=True 

1062 ) 

1063 else: # 3.8 

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

1065 if include_extras: 

1066 return hint 

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

1068 

1069 

1070# Python 3.9+ has PEP 593 (Annotated) 

1071if hasattr(typing, 'Annotated'): 

1072 Annotated = typing.Annotated 

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

1074 # to work. 

1075 _AnnotatedAlias = typing._AnnotatedAlias 

1076# 3.8 

1077else: 

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

1079 """Runtime representation of an annotated type. 

1080 

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

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

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

1084 it to types is also the same. 

1085 """ 

1086 def __init__(self, origin, metadata): 

1087 if isinstance(origin, _AnnotatedAlias): 

1088 metadata = origin.__metadata__ + metadata 

1089 origin = origin.__origin__ 

1090 super().__init__(origin, origin) 

1091 self.__metadata__ = metadata 

1092 

1093 def copy_with(self, params): 

1094 assert len(params) == 1 

1095 new_type = params[0] 

1096 return _AnnotatedAlias(new_type, self.__metadata__) 

1097 

1098 def __repr__(self): 

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

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

1101 

1102 def __reduce__(self): 

1103 return operator.getitem, ( 

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

1105 ) 

1106 

1107 def __eq__(self, other): 

1108 if not isinstance(other, _AnnotatedAlias): 

1109 return NotImplemented 

1110 if self.__origin__ != other.__origin__: 

1111 return False 

1112 return self.__metadata__ == other.__metadata__ 

1113 

1114 def __hash__(self): 

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

1116 

1117 class Annotated: 

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

1119 

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

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

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

1123 this type as int. 

1124 

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

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

1127 the __extra__ field. 

1128 

1129 Details: 

1130 

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

1132 - Nested Annotated are flattened:: 

1133 

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

1135 

1136 - Instantiating an annotated type is equivalent to instantiating the 

1137 underlying type:: 

1138 

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

1140 

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

1142 

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

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

1145 

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

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

1148 """ 

1149 

1150 __slots__ = () 

1151 

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

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

1154 

1155 @typing._tp_cache 

1156 def __class_getitem__(cls, params): 

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

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

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

1160 "annotation).") 

1161 allowed_special_forms = (ClassVar, Final) 

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

1163 origin = params[0] 

1164 else: 

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

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

1167 metadata = tuple(params[1:]) 

1168 return _AnnotatedAlias(origin, metadata) 

1169 

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

1171 raise TypeError( 

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

1173 ) 

1174 

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

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

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

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

1179 get_origin = typing.get_origin 

1180 get_args = typing.get_args 

1181# 3.8-3.9 

1182else: 

1183 try: 

1184 # 3.9+ 

1185 from typing import _BaseGenericAlias 

1186 except ImportError: 

1187 _BaseGenericAlias = typing._GenericAlias 

1188 try: 

1189 # 3.9+ 

1190 from typing import GenericAlias as _typing_GenericAlias 

1191 except ImportError: 

1192 _typing_GenericAlias = typing._GenericAlias 

1193 

1194 def get_origin(tp): 

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

1196 

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

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

1199 

1200 get_origin(Literal[42]) is Literal 

1201 get_origin(int) is None 

1202 get_origin(ClassVar[int]) is ClassVar 

1203 get_origin(Generic) is Generic 

1204 get_origin(Generic[T]) is Generic 

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

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

1207 get_origin(P.args) is P 

1208 """ 

1209 if isinstance(tp, _AnnotatedAlias): 

1210 return Annotated 

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

1212 ParamSpecArgs, ParamSpecKwargs)): 

1213 return tp.__origin__ 

1214 if tp is typing.Generic: 

1215 return typing.Generic 

1216 return None 

1217 

1218 def get_args(tp): 

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

1220 

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

1222 Examples:: 

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

1224 get_args(int) == () 

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

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

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

1228 """ 

1229 if isinstance(tp, _AnnotatedAlias): 

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

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

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

1233 return () 

1234 res = tp.__args__ 

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

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

1237 return res 

1238 return () 

1239 

1240 

1241# 3.10+ 

1242if hasattr(typing, 'TypeAlias'): 

1243 TypeAlias = typing.TypeAlias 

1244# 3.9 

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

1246 @_ExtensionsSpecialForm 

1247 def TypeAlias(self, parameters): 

1248 """Special marker indicating that an assignment should 

1249 be recognized as a proper type alias definition by type 

1250 checkers. 

1251 

1252 For example:: 

1253 

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

1255 

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

1257 """ 

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

1259# 3.8 

1260else: 

1261 TypeAlias = _ExtensionsSpecialForm( 

1262 'TypeAlias', 

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

1264 be recognized as a proper type alias definition by type 

1265 checkers. 

1266 

1267 For example:: 

1268 

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

1270 

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

1272 above.""" 

1273 ) 

1274 

1275 

1276def _set_default(type_param, default): 

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

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

1279 for d in default)) 

1280 elif default != _marker: 

1281 if isinstance(type_param, ParamSpec) and default is ...: # ... not valid <3.11 

1282 type_param.__default__ = default 

1283 else: 

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

1285 else: 

1286 type_param.__default__ = None 

1287 

1288 

1289def _set_module(typevarlike): 

1290 # for pickling: 

1291 def_mod = _caller(depth=3) 

1292 if def_mod != 'typing_extensions': 

1293 typevarlike.__module__ = def_mod 

1294 

1295 

1296class _DefaultMixin: 

1297 """Mixin for TypeVarLike defaults.""" 

1298 

1299 __slots__ = () 

1300 __init__ = _set_default 

1301 

1302 

1303# Classes using this metaclass must provide a _backported_typevarlike ClassVar 

1304class _TypeVarLikeMeta(type): 

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

1306 return isinstance(__instance, cls._backported_typevarlike) 

1307 

1308 

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

1310class TypeVar(metaclass=_TypeVarLikeMeta): 

1311 """Type variable.""" 

1312 

1313 _backported_typevarlike = typing.TypeVar 

1314 

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

1316 covariant=False, contravariant=False, 

1317 default=_marker, infer_variance=False): 

1318 if hasattr(typing, "TypeAliasType"): 

1319 # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar 

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

1321 covariant=covariant, contravariant=contravariant, 

1322 infer_variance=infer_variance) 

1323 else: 

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

1325 covariant=covariant, contravariant=contravariant) 

1326 if infer_variance and (covariant or contravariant): 

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

1328 typevar.__infer_variance__ = infer_variance 

1329 _set_default(typevar, default) 

1330 _set_module(typevar) 

1331 return typevar 

1332 

1333 def __init_subclass__(cls) -> None: 

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

1335 

1336 

1337# Python 3.10+ has PEP 612 

1338if hasattr(typing, 'ParamSpecArgs'): 

1339 ParamSpecArgs = typing.ParamSpecArgs 

1340 ParamSpecKwargs = typing.ParamSpecKwargs 

1341# 3.8-3.9 

1342else: 

1343 class _Immutable: 

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

1345 __slots__ = () 

1346 

1347 def __copy__(self): 

1348 return self 

1349 

1350 def __deepcopy__(self, memo): 

1351 return self 

1352 

1353 class ParamSpecArgs(_Immutable): 

1354 """The args for a ParamSpec object. 

1355 

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

1357 

1358 ParamSpecArgs objects have a reference back to their ParamSpec: 

1359 

1360 P.args.__origin__ is P 

1361 

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

1363 static type checkers. 

1364 """ 

1365 def __init__(self, origin): 

1366 self.__origin__ = origin 

1367 

1368 def __repr__(self): 

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

1370 

1371 def __eq__(self, other): 

1372 if not isinstance(other, ParamSpecArgs): 

1373 return NotImplemented 

1374 return self.__origin__ == other.__origin__ 

1375 

1376 class ParamSpecKwargs(_Immutable): 

1377 """The kwargs for a ParamSpec object. 

1378 

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

1380 

1381 ParamSpecKwargs objects have a reference back to their ParamSpec: 

1382 

1383 P.kwargs.__origin__ is P 

1384 

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

1386 static type checkers. 

1387 """ 

1388 def __init__(self, origin): 

1389 self.__origin__ = origin 

1390 

1391 def __repr__(self): 

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

1393 

1394 def __eq__(self, other): 

1395 if not isinstance(other, ParamSpecKwargs): 

1396 return NotImplemented 

1397 return self.__origin__ == other.__origin__ 

1398 

1399# 3.10+ 

1400if hasattr(typing, 'ParamSpec'): 

1401 

1402 # Add default parameter - PEP 696 

1403 class ParamSpec(metaclass=_TypeVarLikeMeta): 

1404 """Parameter specification.""" 

1405 

1406 _backported_typevarlike = typing.ParamSpec 

1407 

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

1409 covariant=False, contravariant=False, 

1410 infer_variance=False, default=_marker): 

1411 if hasattr(typing, "TypeAliasType"): 

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

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

1414 covariant=covariant, 

1415 contravariant=contravariant, 

1416 infer_variance=infer_variance) 

1417 else: 

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

1419 covariant=covariant, 

1420 contravariant=contravariant) 

1421 paramspec.__infer_variance__ = infer_variance 

1422 

1423 _set_default(paramspec, default) 

1424 _set_module(paramspec) 

1425 return paramspec 

1426 

1427 def __init_subclass__(cls) -> None: 

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

1429 

1430# 3.8-3.9 

1431else: 

1432 

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

1434 class ParamSpec(list, _DefaultMixin): 

1435 """Parameter specification variable. 

1436 

1437 Usage:: 

1438 

1439 P = ParamSpec('P') 

1440 

1441 Parameter specification variables exist primarily for the benefit of static 

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

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

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

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

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

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

1448 example for annotating a decorator:: 

1449 

1450 T = TypeVar('T') 

1451 P = ParamSpec('P') 

1452 

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

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

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

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

1457 return f(*args, **kwargs) 

1458 return inner 

1459 

1460 @add_logging 

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

1462 '''Add two numbers together.''' 

1463 return x + y 

1464 

1465 Parameter specification variables defined with covariant=True or 

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

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

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

1469 

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

1471 

1472 P.__name__ == 'T' 

1473 P.__bound__ == None 

1474 P.__covariant__ == False 

1475 P.__contravariant__ == False 

1476 

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

1478 be pickled. 

1479 """ 

1480 

1481 # Trick Generic __parameters__. 

1482 __class__ = typing.TypeVar 

1483 

1484 @property 

1485 def args(self): 

1486 return ParamSpecArgs(self) 

1487 

1488 @property 

1489 def kwargs(self): 

1490 return ParamSpecKwargs(self) 

1491 

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

1493 infer_variance=False, default=_marker): 

1494 super().__init__([self]) 

1495 self.__name__ = name 

1496 self.__covariant__ = bool(covariant) 

1497 self.__contravariant__ = bool(contravariant) 

1498 self.__infer_variance__ = bool(infer_variance) 

1499 if bound: 

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

1501 else: 

1502 self.__bound__ = None 

1503 _DefaultMixin.__init__(self, default) 

1504 

1505 # for pickling: 

1506 def_mod = _caller() 

1507 if def_mod != 'typing_extensions': 

1508 self.__module__ = def_mod 

1509 

1510 def __repr__(self): 

1511 if self.__infer_variance__: 

1512 prefix = '' 

1513 elif self.__covariant__: 

1514 prefix = '+' 

1515 elif self.__contravariant__: 

1516 prefix = '-' 

1517 else: 

1518 prefix = '~' 

1519 return prefix + self.__name__ 

1520 

1521 def __hash__(self): 

1522 return object.__hash__(self) 

1523 

1524 def __eq__(self, other): 

1525 return self is other 

1526 

1527 def __reduce__(self): 

1528 return self.__name__ 

1529 

1530 # Hack to get typing._type_check to pass. 

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

1532 pass 

1533 

1534 

1535# 3.8-3.9 

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

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

1538 class _ConcatenateGenericAlias(list): 

1539 

1540 # Trick Generic into looking into this for __parameters__. 

1541 __class__ = typing._GenericAlias 

1542 

1543 # Flag in 3.8. 

1544 _special = False 

1545 

1546 def __init__(self, origin, args): 

1547 super().__init__(args) 

1548 self.__origin__ = origin 

1549 self.__args__ = args 

1550 

1551 def __repr__(self): 

1552 _type_repr = typing._type_repr 

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

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

1555 

1556 def __hash__(self): 

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

1558 

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

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

1561 pass 

1562 

1563 @property 

1564 def __parameters__(self): 

1565 return tuple( 

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

1567 ) 

1568 

1569 

1570# 3.8-3.9 

1571@typing._tp_cache 

1572def _concatenate_getitem(self, parameters): 

1573 if parameters == (): 

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

1575 if not isinstance(parameters, tuple): 

1576 parameters = (parameters,) 

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

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

1579 "ParamSpec variable.") 

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

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

1582 return _ConcatenateGenericAlias(self, parameters) 

1583 

1584 

1585# 3.10+ 

1586if hasattr(typing, 'Concatenate'): 

1587 Concatenate = typing.Concatenate 

1588 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811 

1589# 3.9 

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

1591 @_ExtensionsSpecialForm 

1592 def Concatenate(self, parameters): 

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

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

1595 callable. 

1596 

1597 For example:: 

1598 

1599 Callable[Concatenate[int, P], int] 

1600 

1601 See PEP 612 for detailed information. 

1602 """ 

1603 return _concatenate_getitem(self, parameters) 

1604# 3.8 

1605else: 

1606 class _ConcatenateForm(_ExtensionsSpecialForm, _root=True): 

1607 def __getitem__(self, parameters): 

1608 return _concatenate_getitem(self, parameters) 

1609 

1610 Concatenate = _ConcatenateForm( 

1611 'Concatenate', 

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

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

1614 callable. 

1615 

1616 For example:: 

1617 

1618 Callable[Concatenate[int, P], int] 

1619 

1620 See PEP 612 for detailed information. 

1621 """) 

1622 

1623# 3.10+ 

1624if hasattr(typing, 'TypeGuard'): 

1625 TypeGuard = typing.TypeGuard 

1626# 3.9 

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

1628 @_ExtensionsSpecialForm 

1629 def TypeGuard(self, parameters): 

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

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

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

1633 

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

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

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

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

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

1639 

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

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

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

1643 

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

1645 function: 

1646 

1647 1. The return value is a boolean. 

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

1649 is the type inside ``TypeGuard``. 

1650 

1651 For example:: 

1652 

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

1654 # "isinstance" type guard 

1655 if isinstance(val, str): 

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

1657 ... 

1658 else: 

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

1660 ... 

1661 

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

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

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

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

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

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

1668 

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

1670 PEP 647 (User-Defined Type Guards). 

1671 """ 

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

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

1674# 3.8 

1675else: 

1676 class _TypeGuardForm(_ExtensionsSpecialForm, _root=True): 

1677 def __getitem__(self, parameters): 

1678 item = typing._type_check(parameters, 

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

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

1681 

1682 TypeGuard = _TypeGuardForm( 

1683 'TypeGuard', 

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

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

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

1687 

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

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

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

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

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

1693 

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

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

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

1697 

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

1699 function: 

1700 

1701 1. The return value is a boolean. 

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

1703 is the type inside ``TypeGuard``. 

1704 

1705 For example:: 

1706 

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

1708 # "isinstance" type guard 

1709 if isinstance(val, str): 

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

1711 ... 

1712 else: 

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

1714 ... 

1715 

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

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

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

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

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

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

1722 

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

1724 PEP 647 (User-Defined Type Guards). 

1725 """) 

1726 

1727 

1728# Vendored from cpython typing._SpecialFrom 

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

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

1731 

1732 def __init__(self, getitem): 

1733 self._getitem = getitem 

1734 self._name = getitem.__name__ 

1735 self.__doc__ = getitem.__doc__ 

1736 

1737 def __getattr__(self, item): 

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

1739 return self._name 

1740 

1741 raise AttributeError(item) 

1742 

1743 def __mro_entries__(self, bases): 

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

1745 

1746 def __repr__(self): 

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

1748 

1749 def __reduce__(self): 

1750 return self._name 

1751 

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

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

1754 

1755 def __or__(self, other): 

1756 return typing.Union[self, other] 

1757 

1758 def __ror__(self, other): 

1759 return typing.Union[other, self] 

1760 

1761 def __instancecheck__(self, obj): 

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

1763 

1764 def __subclasscheck__(self, cls): 

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

1766 

1767 @typing._tp_cache 

1768 def __getitem__(self, parameters): 

1769 return self._getitem(self, parameters) 

1770 

1771 

1772if hasattr(typing, "LiteralString"): # 3.11+ 

1773 LiteralString = typing.LiteralString 

1774else: 

1775 @_SpecialForm 

1776 def LiteralString(self, params): 

1777 """Represents an arbitrary literal string. 

1778 

1779 Example:: 

1780 

1781 from typing_extensions import LiteralString 

1782 

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

1784 ... 

1785 

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

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

1788 

1789 See PEP 675 for details. 

1790 

1791 """ 

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

1793 

1794 

1795if hasattr(typing, "Self"): # 3.11+ 

1796 Self = typing.Self 

1797else: 

1798 @_SpecialForm 

1799 def Self(self, params): 

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

1801 

1802 Example:: 

1803 

1804 from typing import Self 

1805 

1806 class ReturnsSelf: 

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

1808 ... 

1809 return self 

1810 

1811 """ 

1812 

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

1814 

1815 

1816if hasattr(typing, "Never"): # 3.11+ 

1817 Never = typing.Never 

1818else: 

1819 @_SpecialForm 

1820 def Never(self, params): 

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

1822 

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

1824 called, or a function that never returns:: 

1825 

1826 from typing_extensions import Never 

1827 

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

1829 pass 

1830 

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

1832 never_call_me(arg) # type checker error 

1833 match arg: 

1834 case int(): 

1835 print("It's an int") 

1836 case str(): 

1837 print("It's a str") 

1838 case _: 

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

1840 

1841 """ 

1842 

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

1844 

1845 

1846if hasattr(typing, 'Required'): # 3.11+ 

1847 Required = typing.Required 

1848 NotRequired = typing.NotRequired 

1849elif sys.version_info[:2] >= (3, 9): # 3.9-3.10 

1850 @_ExtensionsSpecialForm 

1851 def Required(self, parameters): 

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

1853 as required. For example: 

1854 

1855 class Movie(TypedDict, total=False): 

1856 title: Required[str] 

1857 year: int 

1858 

1859 m = Movie( 

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

1861 year=1999, 

1862 ) 

1863 

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

1865 when instantiating a related TypedDict. 

1866 """ 

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

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

1869 

1870 @_ExtensionsSpecialForm 

1871 def NotRequired(self, parameters): 

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

1873 potentially missing. For example: 

1874 

1875 class Movie(TypedDict): 

1876 title: str 

1877 year: NotRequired[int] 

1878 

1879 m = Movie( 

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

1881 year=1999, 

1882 ) 

1883 """ 

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

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

1886 

1887else: # 3.8 

1888 class _RequiredForm(_ExtensionsSpecialForm, _root=True): 

1889 def __getitem__(self, parameters): 

1890 item = typing._type_check(parameters, 

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

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

1893 

1894 Required = _RequiredForm( 

1895 'Required', 

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

1897 as required. For example: 

1898 

1899 class Movie(TypedDict, total=False): 

1900 title: Required[str] 

1901 year: int 

1902 

1903 m = Movie( 

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

1905 year=1999, 

1906 ) 

1907 

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

1909 when instantiating a related TypedDict. 

1910 """) 

1911 NotRequired = _RequiredForm( 

1912 'NotRequired', 

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

1914 potentially missing. For example: 

1915 

1916 class Movie(TypedDict): 

1917 title: str 

1918 year: NotRequired[int] 

1919 

1920 m = Movie( 

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

1922 year=1999, 

1923 ) 

1924 """) 

1925 

1926 

1927_UNPACK_DOC = """\ 

1928Type unpack operator. 

1929 

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

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

1932example: 

1933 

1934 # For some generic class `Foo`: 

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

1936 

1937 Ts = TypeVarTuple('Ts') 

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

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

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

1941 # `Generic[]`.) 

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

1943 Bar[int] # Valid 

1944 Bar[int, str] # Also valid 

1945 

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

1947 

1948 Foo[*tuple[int, str]] 

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

1950 

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

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

1953 

1954 class Movie(TypedDict): 

1955 name: str 

1956 year: int 

1957 

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

1959 # *year* of type `int`. 

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

1961 

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

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

1964 

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

1966""" 

1967 

1968 

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

1970 Unpack = typing.Unpack 

1971 

1972 def _is_unpack(obj): 

1973 return get_origin(obj) is Unpack 

1974 

1975elif sys.version_info[:2] >= (3, 9): # 3.9+ 

1976 class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True): 

1977 def __init__(self, getitem): 

1978 super().__init__(getitem) 

1979 self.__doc__ = _UNPACK_DOC 

1980 

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

1982 __class__ = typing.TypeVar 

1983 

1984 @_UnpackSpecialForm 

1985 def Unpack(self, parameters): 

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

1987 return _UnpackAlias(self, (item,)) 

1988 

1989 def _is_unpack(obj): 

1990 return isinstance(obj, _UnpackAlias) 

1991 

1992else: # 3.8 

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

1994 __class__ = typing.TypeVar 

1995 

1996 class _UnpackForm(_ExtensionsSpecialForm, _root=True): 

1997 def __getitem__(self, parameters): 

1998 item = typing._type_check(parameters, 

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

2000 return _UnpackAlias(self, (item,)) 

2001 

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

2003 

2004 def _is_unpack(obj): 

2005 return isinstance(obj, _UnpackAlias) 

2006 

2007 

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

2009 

2010 # Add default parameter - PEP 696 

2011 class TypeVarTuple(metaclass=_TypeVarLikeMeta): 

2012 """Type variable tuple.""" 

2013 

2014 _backported_typevarlike = typing.TypeVarTuple 

2015 

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

2017 tvt = typing.TypeVarTuple(name) 

2018 _set_default(tvt, default) 

2019 _set_module(tvt) 

2020 return tvt 

2021 

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

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

2024 

2025else: # <=3.10 

2026 class TypeVarTuple(_DefaultMixin): 

2027 """Type variable tuple. 

2028 

2029 Usage:: 

2030 

2031 Ts = TypeVarTuple('Ts') 

2032 

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

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

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

2036 

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

2038 Consider the following example:: 

2039 

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

2041 

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

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

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

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

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

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

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

2049 

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

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

2052 signatures and variable annotations:: 

2053 

2054 class Array(Generic[*Ts]): 

2055 

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

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

2058 

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

2060 return self._shape 

2061 

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

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

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

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

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

2067 

2068 """ 

2069 

2070 # Trick Generic __parameters__. 

2071 __class__ = typing.TypeVar 

2072 

2073 def __iter__(self): 

2074 yield self.__unpacked__ 

2075 

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

2077 self.__name__ = name 

2078 _DefaultMixin.__init__(self, default) 

2079 

2080 # for pickling: 

2081 def_mod = _caller() 

2082 if def_mod != 'typing_extensions': 

2083 self.__module__ = def_mod 

2084 

2085 self.__unpacked__ = Unpack[self] 

2086 

2087 def __repr__(self): 

2088 return self.__name__ 

2089 

2090 def __hash__(self): 

2091 return object.__hash__(self) 

2092 

2093 def __eq__(self, other): 

2094 return self is other 

2095 

2096 def __reduce__(self): 

2097 return self.__name__ 

2098 

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

2100 if '_root' not in kwds: 

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

2102 

2103 

2104if hasattr(typing, "reveal_type"): # 3.11+ 

2105 reveal_type = typing.reveal_type 

2106else: # <=3.10 

2107 def reveal_type(obj: T, /) -> T: 

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

2109 

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

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

2112 

2113 x: int = 1 

2114 reveal_type(x) 

2115 

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

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

2118 

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

2120 argument and returns it unchanged. 

2121 

2122 """ 

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

2124 return obj 

2125 

2126 

2127if hasattr(typing, "assert_never"): # 3.11+ 

2128 assert_never = typing.assert_never 

2129else: # <=3.10 

2130 def assert_never(arg: Never, /) -> Never: 

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

2132 

2133 Example:: 

2134 

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

2136 match arg: 

2137 case int(): 

2138 print("It's an int") 

2139 case str(): 

2140 print("It's a str") 

2141 case _: 

2142 assert_never(arg) 

2143 

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

2145 reachable, it will emit an error. 

2146 

2147 At runtime, this throws an exception when called. 

2148 

2149 """ 

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

2151 

2152 

2153if sys.version_info >= (3, 12): # 3.12+ 

2154 # dataclass_transform exists in 3.11 but lacks the frozen_default parameter 

2155 dataclass_transform = typing.dataclass_transform 

2156else: # <=3.11 

2157 def dataclass_transform( 

2158 *, 

2159 eq_default: bool = True, 

2160 order_default: bool = False, 

2161 kw_only_default: bool = False, 

2162 frozen_default: bool = False, 

2163 field_specifiers: typing.Tuple[ 

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

2165 ... 

2166 ] = (), 

2167 **kwargs: typing.Any, 

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

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

2170 dataclass-like behavior. 

2171 

2172 Example: 

2173 

2174 from typing_extensions import dataclass_transform 

2175 

2176 _T = TypeVar("_T") 

2177 

2178 # Used on a decorator function 

2179 @dataclass_transform() 

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

2181 ... 

2182 return cls 

2183 

2184 @create_model 

2185 class CustomerModel: 

2186 id: int 

2187 name: str 

2188 

2189 # Used on a base class 

2190 @dataclass_transform() 

2191 class ModelBase: ... 

2192 

2193 class CustomerModel(ModelBase): 

2194 id: int 

2195 name: str 

2196 

2197 # Used on a metaclass 

2198 @dataclass_transform() 

2199 class ModelMeta(type): ... 

2200 

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

2202 

2203 class CustomerModel(ModelBase): 

2204 id: int 

2205 name: str 

2206 

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

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

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

2210 method. 

2211 

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

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

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

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

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

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

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

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

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

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

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

2223 

2224 At runtime, this decorator records its arguments in the 

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

2226 

2227 See PEP 681 for details. 

2228 

2229 """ 

2230 def decorator(cls_or_fn): 

2231 cls_or_fn.__dataclass_transform__ = { 

2232 "eq_default": eq_default, 

2233 "order_default": order_default, 

2234 "kw_only_default": kw_only_default, 

2235 "frozen_default": frozen_default, 

2236 "field_specifiers": field_specifiers, 

2237 "kwargs": kwargs, 

2238 } 

2239 return cls_or_fn 

2240 return decorator 

2241 

2242 

2243if hasattr(typing, "override"): # 3.12+ 

2244 override = typing.override 

2245else: # <=3.11 

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

2247 

2248 def override(arg: _F, /) -> _F: 

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

2250 

2251 Usage: 

2252 

2253 class Base: 

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

2255 pass 

2256 

2257 class Child(Base): 

2258 @override 

2259 def method(self) -> None: 

2260 super().method() 

2261 

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

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

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

2265 without an equivalent change to a child class. 

2266 

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

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

2269 to allow runtime introspection. 

2270 

2271 See PEP 698 for details. 

2272 

2273 """ 

2274 try: 

2275 arg.__override__ = True 

2276 except (AttributeError, TypeError): 

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

2278 # AttributeError happens if the object has __slots__ or a 

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

2280 pass 

2281 return arg 

2282 

2283 

2284if hasattr(typing, "deprecated"): 

2285 deprecated = typing.deprecated 

2286else: 

2287 _T = typing.TypeVar("_T") 

2288 

2289 def deprecated( 

2290 msg: str, 

2291 /, 

2292 *, 

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

2294 stacklevel: int = 1, 

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

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

2297 

2298 Usage: 

2299 

2300 @deprecated("Use B instead") 

2301 class A: 

2302 pass 

2303 

2304 @deprecated("Use g instead") 

2305 def f(): 

2306 pass 

2307 

2308 @overload 

2309 @deprecated("int support is deprecated") 

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

2311 @overload 

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

2313 

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

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

2316 

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

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

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

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

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

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

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

2324 

2325 The decorator sets the ``__deprecated__`` 

2326 attribute on the decorated object to the deprecation message 

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

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

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

2330 

2331 See PEP 702 for details. 

2332 

2333 """ 

2334 def decorator(arg: _T, /) -> _T: 

2335 if category is None: 

2336 arg.__deprecated__ = msg 

2337 return arg 

2338 elif isinstance(arg, type): 

2339 original_new = arg.__new__ 

2340 has_init = arg.__init__ is not object.__init__ 

2341 

2342 @functools.wraps(original_new) 

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

2344 warnings.warn(msg, category=category, stacklevel=stacklevel + 1) 

2345 if original_new is not object.__new__: 

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

2347 # Mirrors a similar check in object.__new__. 

2348 elif not has_init and (args or kwargs): 

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

2350 else: 

2351 return original_new(cls) 

2352 

2353 arg.__new__ = staticmethod(__new__) 

2354 arg.__deprecated__ = __new__.__deprecated__ = msg 

2355 return arg 

2356 elif callable(arg): 

2357 @functools.wraps(arg) 

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

2359 warnings.warn(msg, category=category, stacklevel=stacklevel + 1) 

2360 return arg(*args, **kwargs) 

2361 

2362 arg.__deprecated__ = wrapper.__deprecated__ = msg 

2363 return wrapper 

2364 else: 

2365 raise TypeError( 

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

2367 f"a class or callable, not {arg!r}" 

2368 ) 

2369 

2370 return decorator 

2371 

2372 

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

2374# Unpack/TypeVarTuple: 

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

2376# Generic[Unpack[Ts]] 

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

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

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

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

2381 typing._collect_type_vars = _collect_type_vars 

2382 typing._check_generic = _check_generic 

2383 

2384 

2385# Backport typing.NamedTuple as it exists in Python 3.13. 

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

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

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

2389# On 3.13, we deprecated kwargs-based NamedTuples 

2390if sys.version_info >= (3, 13): 

2391 NamedTuple = typing.NamedTuple 

2392else: 

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

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

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

2396 for n, t in types} 

2397 nm_tpl = collections.namedtuple(name, fields, 

2398 defaults=defaults, module=module) 

2399 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations 

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

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

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

2403 nm_tpl._field_types = annotations 

2404 return nm_tpl 

2405 

2406 _prohibited_namedtuple_fields = typing._prohibited 

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

2408 

2409 class _NamedTupleMeta(type): 

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

2411 assert _NamedTuple in bases 

2412 for base in bases: 

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

2414 raise TypeError( 

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

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

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

2418 default_names = [] 

2419 for field_name in types: 

2420 if field_name in ns: 

2421 default_names.append(field_name) 

2422 elif default_names: 

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

2424 f"cannot follow default field" 

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

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

2427 nm_tpl = _make_nmtuple( 

2428 typename, types.items(), 

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

2430 module=ns['__module__'] 

2431 ) 

2432 nm_tpl.__bases__ = bases 

2433 if typing.Generic in bases: 

2434 if hasattr(typing, '_generic_class_getitem'): # 3.12+ 

2435 nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem) 

2436 else: 

2437 class_getitem = typing.Generic.__class_getitem__.__func__ 

2438 nm_tpl.__class_getitem__ = classmethod(class_getitem) 

2439 # update from user namespace without overriding special namedtuple attributes 

2440 for key in ns: 

2441 if key in _prohibited_namedtuple_fields: 

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

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

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

2445 if typing.Generic in bases: 

2446 nm_tpl.__init_subclass__() 

2447 return nm_tpl 

2448 

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

2450 

2451 def _namedtuple_mro_entries(bases): 

2452 assert NamedTuple in bases 

2453 return (_NamedTuple,) 

2454 

2455 @_ensure_subclassable(_namedtuple_mro_entries) 

2456 def NamedTuple(typename, fields=_marker, /, **kwargs): 

2457 """Typed version of namedtuple. 

2458 

2459 Usage:: 

2460 

2461 class Employee(NamedTuple): 

2462 name: str 

2463 id: int 

2464 

2465 This is equivalent to:: 

2466 

2467 Employee = collections.namedtuple('Employee', ['name', 'id']) 

2468 

2469 The resulting class has an extra __annotations__ attribute, giving a 

2470 dict that maps field names to types. (The field names are also in 

2471 the _fields attribute, which is part of the namedtuple API.) 

2472 An alternative equivalent functional syntax is also accepted:: 

2473 

2474 Employee = NamedTuple('Employee', [('name', str), ('id', int)]) 

2475 """ 

2476 if fields is _marker: 

2477 if kwargs: 

2478 deprecated_thing = "Creating NamedTuple classes using keyword arguments" 

2479 deprecation_msg = ( 

2480 "{name} is deprecated and will be disallowed in Python {remove}. " 

2481 "Use the class-based or functional syntax instead." 

2482 ) 

2483 else: 

2484 deprecated_thing = "Failing to pass a value for the 'fields' parameter" 

2485 example = f"`{typename} = NamedTuple({typename!r}, [])`" 

2486 deprecation_msg = ( 

2487 "{name} is deprecated and will be disallowed in Python {remove}. " 

2488 "To create a NamedTuple class with 0 fields " 

2489 "using the functional syntax, " 

2490 "pass an empty list, e.g. " 

2491 ) + example + "." 

2492 elif fields is None: 

2493 if kwargs: 

2494 raise TypeError( 

2495 "Cannot pass `None` as the 'fields' parameter " 

2496 "and also specify fields using keyword arguments" 

2497 ) 

2498 else: 

2499 deprecated_thing = "Passing `None` as the 'fields' parameter" 

2500 example = f"`{typename} = NamedTuple({typename!r}, [])`" 

2501 deprecation_msg = ( 

2502 "{name} is deprecated and will be disallowed in Python {remove}. " 

2503 "To create a NamedTuple class with 0 fields " 

2504 "using the functional syntax, " 

2505 "pass an empty list, e.g. " 

2506 ) + example + "." 

2507 elif kwargs: 

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

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

2510 if fields is _marker or fields is None: 

2511 warnings.warn( 

2512 deprecation_msg.format(name=deprecated_thing, remove="3.15"), 

2513 DeprecationWarning, 

2514 stacklevel=2, 

2515 ) 

2516 fields = kwargs.items() 

2517 nt = _make_nmtuple(typename, fields, module=_caller()) 

2518 nt.__orig_bases__ = (NamedTuple,) 

2519 return nt 

2520 

2521 

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

2523 Buffer = collections.abc.Buffer 

2524else: 

2525 class Buffer(abc.ABC): 

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

2527 

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

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

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

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

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

2533 to the buffer protocol from Python code, and the 

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

2535 implements the buffer protocol. 

2536 

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

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

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

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

2541 classes. It is useful primarily for static checks. 

2542 

2543 """ 

2544 

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

2546 Buffer.register(memoryview) 

2547 Buffer.register(bytearray) 

2548 Buffer.register(bytes) 

2549 

2550 

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

2552if hasattr(_types, "get_original_bases"): 

2553 get_original_bases = _types.get_original_bases 

2554else: 

2555 def get_original_bases(cls, /): 

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

2557 

2558 Examples:: 

2559 

2560 from typing import TypeVar, Generic 

2561 from typing_extensions import NamedTuple, TypedDict 

2562 

2563 T = TypeVar("T") 

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

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

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

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

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

2569 

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

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

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

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

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

2575 """ 

2576 try: 

2577 return cls.__dict__.get("__orig_bases__", cls.__bases__) 

2578 except AttributeError: 

2579 raise TypeError( 

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

2581 ) from None 

2582 

2583 

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

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

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

2587 NewType = typing.NewType 

2588else: 

2589 class NewType: 

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

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

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

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

2594 UserId = NewType('UserId', int) 

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

2596 ... 

2597 UserId('user') # Fails type check 

2598 name_by_id(42) # Fails type check 

2599 name_by_id(UserId(42)) # OK 

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

2601 """ 

2602 

2603 def __call__(self, obj): 

2604 return obj 

2605 

2606 def __init__(self, name, tp): 

2607 self.__qualname__ = name 

2608 if '.' in name: 

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

2610 self.__name__ = name 

2611 self.__supertype__ = tp 

2612 def_mod = _caller() 

2613 if def_mod != 'typing_extensions': 

2614 self.__module__ = def_mod 

2615 

2616 def __mro_entries__(self, bases): 

2617 # We defined __mro_entries__ to get a better error message 

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

2619 supercls_name = self.__name__ 

2620 

2621 class Dummy: 

2622 def __init_subclass__(cls): 

2623 subcls_name = cls.__name__ 

2624 raise TypeError( 

2625 f"Cannot subclass an instance of NewType. " 

2626 f"Perhaps you were looking for: " 

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

2628 ) 

2629 

2630 return (Dummy,) 

2631 

2632 def __repr__(self): 

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

2634 

2635 def __reduce__(self): 

2636 return self.__qualname__ 

2637 

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

2639 # PEP 604 methods 

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

2641 

2642 def __or__(self, other): 

2643 return typing.Union[self, other] 

2644 

2645 def __ror__(self, other): 

2646 return typing.Union[other, self] 

2647 

2648 

2649if hasattr(typing, "TypeAliasType"): 

2650 TypeAliasType = typing.TypeAliasType 

2651else: 

2652 def _is_unionable(obj): 

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

2654 return obj is None or isinstance(obj, ( 

2655 type, 

2656 _types.GenericAlias, 

2657 _types.UnionType, 

2658 TypeAliasType, 

2659 )) 

2660 

2661 class TypeAliasType: 

2662 """Create named, parameterized type aliases. 

2663 

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

2665 

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

2667 

2668 is equivalent to: 

2669 

2670 T = TypeVar("T") 

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

2672 

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

2674 

2675 The type_params argument should contain all the type parameters used 

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

2677 argument is omitted. 

2678 

2679 Static type checkers should only support type aliases declared using 

2680 TypeAliasType that follow these rules: 

2681 

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

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

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

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

2686 

2687 """ 

2688 

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

2690 if not isinstance(name, str): 

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

2692 self.__value__ = value 

2693 self.__type_params__ = type_params 

2694 

2695 parameters = [] 

2696 for type_param in type_params: 

2697 if isinstance(type_param, TypeVarTuple): 

2698 parameters.extend(type_param) 

2699 else: 

2700 parameters.append(type_param) 

2701 self.__parameters__ = tuple(parameters) 

2702 def_mod = _caller() 

2703 if def_mod != 'typing_extensions': 

2704 self.__module__ = def_mod 

2705 # Setting this attribute closes the TypeAliasType from further modification 

2706 self.__name__ = name 

2707 

2708 def __setattr__(self, name: str, value: object, /) -> None: 

2709 if hasattr(self, "__name__"): 

2710 self._raise_attribute_error(name) 

2711 super().__setattr__(name, value) 

2712 

2713 def __delattr__(self, name: str, /) -> Never: 

2714 self._raise_attribute_error(name) 

2715 

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

2717 # Match the Python 3.12 error messages exactly 

2718 if name == "__name__": 

2719 raise AttributeError("readonly attribute") 

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

2721 raise AttributeError( 

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

2723 "is not writable" 

2724 ) 

2725 else: 

2726 raise AttributeError( 

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

2728 ) 

2729 

2730 def __repr__(self) -> str: 

2731 return self.__name__ 

2732 

2733 def __getitem__(self, parameters): 

2734 if not isinstance(parameters, tuple): 

2735 parameters = (parameters,) 

2736 parameters = [ 

2737 typing._type_check( 

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

2739 ) 

2740 for item in parameters 

2741 ] 

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

2743 

2744 def __reduce__(self): 

2745 return self.__name__ 

2746 

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

2748 raise TypeError( 

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

2750 ) 

2751 

2752 # The presence of this method convinces typing._type_check 

2753 # that TypeAliasTypes are types. 

2754 def __call__(self): 

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

2756 

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

2758 def __or__(self, right): 

2759 # For forward compatibility with 3.12, reject Unions 

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

2761 if not _is_unionable(right): 

2762 return NotImplemented 

2763 return typing.Union[self, right] 

2764 

2765 def __ror__(self, left): 

2766 if not _is_unionable(left): 

2767 return NotImplemented 

2768 return typing.Union[left, self] 

2769 

2770 

2771if hasattr(typing, "is_protocol"): 

2772 is_protocol = typing.is_protocol 

2773 get_protocol_members = typing.get_protocol_members 

2774else: 

2775 def is_protocol(tp: type, /) -> bool: 

2776 """Return True if the given type is a Protocol. 

2777 

2778 Example:: 

2779 

2780 >>> from typing_extensions import Protocol, is_protocol 

2781 >>> class P(Protocol): 

2782 ... def a(self) -> str: ... 

2783 ... b: int 

2784 >>> is_protocol(P) 

2785 True 

2786 >>> is_protocol(int) 

2787 False 

2788 """ 

2789 return ( 

2790 isinstance(tp, type) 

2791 and getattr(tp, '_is_protocol', False) 

2792 and tp is not Protocol 

2793 and tp is not typing.Protocol 

2794 ) 

2795 

2796 def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]: 

2797 """Return the set of members defined in a Protocol. 

2798 

2799 Example:: 

2800 

2801 >>> from typing_extensions import Protocol, get_protocol_members 

2802 >>> class P(Protocol): 

2803 ... def a(self) -> str: ... 

2804 ... b: int 

2805 >>> get_protocol_members(P) 

2806 frozenset({'a', 'b'}) 

2807 

2808 Raise a TypeError for arguments that are not Protocols. 

2809 """ 

2810 if not is_protocol(tp): 

2811 raise TypeError(f'{tp!r} is not a Protocol') 

2812 if hasattr(tp, '__protocol_attrs__'): 

2813 return frozenset(tp.__protocol_attrs__) 

2814 return frozenset(_get_protocol_attrs(tp)) 

2815 

2816 

2817if hasattr(typing, "Doc"): 

2818 Doc = typing.Doc 

2819else: 

2820 class Doc: 

2821 """Define the documentation of a type annotation using ``Annotated``, to be 

2822 used in class attributes, function and method parameters, return values, 

2823 and variables. 

2824 

2825 The value should be a positional-only string literal to allow static tools 

2826 like editors and documentation generators to use it. 

2827 

2828 This complements docstrings. 

2829 

2830 The string value passed is available in the attribute ``documentation``. 

2831 

2832 Example:: 

2833 

2834 >>> from typing_extensions import Annotated, Doc 

2835 >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ... 

2836 """ 

2837 def __init__(self, documentation: str, /) -> None: 

2838 self.documentation = documentation 

2839 

2840 def __repr__(self) -> str: 

2841 return f"Doc({self.documentation!r})" 

2842 

2843 def __hash__(self) -> int: 

2844 return hash(self.documentation) 

2845 

2846 def __eq__(self, other: object) -> bool: 

2847 if not isinstance(other, Doc): 

2848 return NotImplemented 

2849 return self.documentation == other.documentation 

2850 

2851 

2852# Aliases for items that have always been in typing. 

2853# Explicitly assign these (rather than using `from typing import *` at the top), 

2854# so that we get a CI error if one of these is deleted from typing.py 

2855# in a future version of Python 

2856AbstractSet = typing.AbstractSet 

2857AnyStr = typing.AnyStr 

2858BinaryIO = typing.BinaryIO 

2859Callable = typing.Callable 

2860Collection = typing.Collection 

2861Container = typing.Container 

2862Dict = typing.Dict 

2863ForwardRef = typing.ForwardRef 

2864FrozenSet = typing.FrozenSet 

2865Generator = typing.Generator 

2866Generic = typing.Generic 

2867Hashable = typing.Hashable 

2868IO = typing.IO 

2869ItemsView = typing.ItemsView 

2870Iterable = typing.Iterable 

2871Iterator = typing.Iterator 

2872KeysView = typing.KeysView 

2873List = typing.List 

2874Mapping = typing.Mapping 

2875MappingView = typing.MappingView 

2876Match = typing.Match 

2877MutableMapping = typing.MutableMapping 

2878MutableSequence = typing.MutableSequence 

2879MutableSet = typing.MutableSet 

2880Optional = typing.Optional 

2881Pattern = typing.Pattern 

2882Reversible = typing.Reversible 

2883Sequence = typing.Sequence 

2884Set = typing.Set 

2885Sized = typing.Sized 

2886TextIO = typing.TextIO 

2887Tuple = typing.Tuple 

2888Union = typing.Union 

2889ValuesView = typing.ValuesView 

2890cast = typing.cast 

2891no_type_check = typing.no_type_check 

2892no_type_check_decorator = typing.no_type_check_decorator