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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1811 statements  

1import abc 

2import builtins 

3import collections 

4import collections.abc 

5import contextlib 

6import enum 

7import functools 

8import inspect 

9import io 

10import keyword 

11import operator 

12import sys 

13import types as _types 

14import typing 

15import warnings 

16 

17# Breakpoint: https://github.com/python/cpython/pull/119891 

18if sys.version_info >= (3, 14): 

19 import annotationlib 

20 

21__all__ = [ 

22 # Super-special typing primitives. 

23 'Any', 

24 'ClassVar', 

25 'Concatenate', 

26 'Final', 

27 'LiteralString', 

28 'ParamSpec', 

29 'ParamSpecArgs', 

30 'ParamSpecKwargs', 

31 'Self', 

32 'Type', 

33 'TypeVar', 

34 'TypeVarTuple', 

35 'Unpack', 

36 

37 # ABCs (from collections.abc). 

38 'Awaitable', 

39 'AsyncIterator', 

40 'AsyncIterable', 

41 'Coroutine', 

42 'AsyncGenerator', 

43 'AsyncContextManager', 

44 'Buffer', 

45 'ChainMap', 

46 

47 # Concrete collection types. 

48 'ContextManager', 

49 'Counter', 

50 'Deque', 

51 'DefaultDict', 

52 'NamedTuple', 

53 'OrderedDict', 

54 'TypedDict', 

55 

56 # Structural checks, a.k.a. protocols. 

57 'SupportsAbs', 

58 'SupportsBytes', 

59 'SupportsComplex', 

60 'SupportsFloat', 

61 'SupportsIndex', 

62 'SupportsInt', 

63 'SupportsRound', 

64 'Reader', 

65 'Writer', 

66 

67 # One-off things. 

68 'Annotated', 

69 'assert_never', 

70 'assert_type', 

71 'clear_overloads', 

72 'dataclass_transform', 

73 'deprecated', 

74 'disjoint_base', 

75 'Doc', 

76 'evaluate_forward_ref', 

77 'get_overloads', 

78 'final', 

79 'Format', 

80 'get_annotations', 

81 'get_args', 

82 'get_origin', 

83 'get_original_bases', 

84 'get_protocol_members', 

85 'get_type_hints', 

86 'IntVar', 

87 'is_protocol', 

88 'is_typeddict', 

89 'Literal', 

90 'NewType', 

91 'overload', 

92 'override', 

93 'Protocol', 

94 'sentinel', 

95 'Sentinel', 

96 'reveal_type', 

97 'runtime', 

98 'runtime_checkable', 

99 'Text', 

100 'TypeAlias', 

101 'TypeAliasType', 

102 'TypeForm', 

103 'TypeGuard', 

104 'TypeIs', 

105 'TYPE_CHECKING', 

106 'type_repr', 

107 'Never', 

108 'NoReturn', 

109 'ReadOnly', 

110 'Required', 

111 'NotRequired', 

112 'NoDefault', 

113 'NoExtraItems', 

114 

115 # Pure aliases, have always been in typing 

116 'AbstractSet', 

117 'AnyStr', 

118 'BinaryIO', 

119 'Callable', 

120 'Collection', 

121 'Container', 

122 'Dict', 

123 'ForwardRef', 

124 'FrozenSet', 

125 'Generator', 

126 'Generic', 

127 'Hashable', 

128 'IO', 

129 'ItemsView', 

130 'Iterable', 

131 'Iterator', 

132 'KeysView', 

133 'List', 

134 'Mapping', 

135 'MappingView', 

136 'Match', 

137 'MutableMapping', 

138 'MutableSequence', 

139 'MutableSet', 

140 'Optional', 

141 'Pattern', 

142 'Reversible', 

143 'Sequence', 

144 'Set', 

145 'Sized', 

146 'TextIO', 

147 'Tuple', 

148 'Union', 

149 'ValuesView', 

150 'cast', 

151 'no_type_check', 

152] 

153 

154# for backward compatibility 

155PEP_560 = True 

156GenericMeta = type 

157# Breakpoint: https://github.com/python/cpython/pull/116129 

158_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta") 

159 

160# Added with bpo-45166 to 3.10.1+ and some 3.9 versions 

161_FORWARD_REF_HAS_CLASS = "__forward_is_class__" in typing.ForwardRef.__slots__ 

162 

163 

164def _caller(depth=1, default='__main__'): 

165 try: 

166 return sys._getframemodulename(depth + 1) or default 

167 except AttributeError: # For platforms without _getframemodulename() 

168 pass 

169 try: 

170 return sys._getframe(depth + 1).f_globals.get('__name__', default) 

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

172 pass 

173 return None 

174 

175 

176# Placeholder for sentinel methods, because sentinels can not have their own sentinels 

177_sentinel_placeholder = object() 

178 

179if hasattr(builtins, "sentinel"): # 3.15+ 

180 sentinel = builtins.sentinel 

181else: 

182 class sentinel: 

183 """Create a unique sentinel object. 

184 

185 *name* should be the name of the variable to which the return value 

186 shall be assigned. 

187 """ 

188 

189 def __init__( 

190 self, 

191 __name: str = _sentinel_placeholder, 

192 __repr: typing.Optional[str] = _sentinel_placeholder, 

193 /, 

194 *, 

195 repr: typing.Optional[str] = None, 

196 name: str = _sentinel_placeholder, 

197 ) -> None: 

198 if name is not _sentinel_placeholder: 

199 warnings.warn( 

200 "Passing 'name' as a keyword argument is deprecated; " 

201 "pass it positionally instead.", 

202 DeprecationWarning, 

203 stacklevel=2, 

204 ) 

205 __name = name 

206 if __name is _sentinel_placeholder: 

207 raise TypeError("First parameter 'name' is required") 

208 if __repr is not _sentinel_placeholder: 

209 warnings.warn( 

210 "Passing 'repr' as a positional argument is deprecated; " 

211 "pass it by keyword instead.", 

212 DeprecationWarning, 

213 stacklevel=2, 

214 ) 

215 repr = __repr 

216 

217 self._name = __name 

218 self._repr = repr if repr is not None else __name 

219 

220 # For pickling as a singleton: 

221 self.__module__ = _caller() 

222 

223 def __init_subclass__(cls): 

224 warnings.warn( 

225 "Subclassing sentinel is deprecated " 

226 "and will be disallowed in Python 3.15", 

227 DeprecationWarning, 

228 stacklevel=2, 

229 ) 

230 super().__init_subclass__() 

231 

232 def __setattr__(self, attr: str, value: object) -> None: 

233 if attr not in {"_name", "_repr", "__module__"}: 

234 warnings.warn( 

235 f"Setting attribute {attr!r} on sentinel objects is deprecated " 

236 "and will be disallowed in Python 3.15.", 

237 DeprecationWarning, 

238 stacklevel=2, 

239 ) 

240 super().__setattr__(attr, value) 

241 

242 @property 

243 def __name__(self) -> str: 

244 return self._name 

245 

246 @__name__.setter 

247 def __name__(self, value: str) -> None: 

248 self._name = value 

249 

250 def __repr__(self) -> str: 

251 return self._repr 

252 

253 if sys.version_info < (3, 11): 

254 # The presence of this method convinces typing._type_check 

255 # that Sentinels are types. 

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

257 raise TypeError(f"{type(self).__name__!r} object is not callable") 

258 

259 # Breakpoint: https://github.com/python/cpython/pull/21515 

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

261 def __or__(self, other): 

262 return typing.Union[self, other] 

263 

264 def __ror__(self, other): 

265 return typing.Union[other, self] 

266 

267 def __reduce__(self) -> str: 

268 """Reduce this sentinel to a singleton.""" 

269 return self.__name__ # Module is taken from the __module__ attribute 

270 

271Sentinel = sentinel 

272 

273_marker = sentinel("sentinel") 

274 

275 

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

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

278 

279# Breakpoint: https://github.com/python/cpython/pull/27342 

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

281 def _should_collect_from_parameters(t): 

282 return isinstance( 

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

284 ) 

285else: 

286 def _should_collect_from_parameters(t): 

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

288 

289 

290NoReturn = typing.NoReturn 

291 

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

293# (These are not for export.) 

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

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

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

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

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

299 

300 

301# Breakpoint: https://github.com/python/cpython/pull/31841 

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

303 from typing import Any 

304else: 

305 

306 class _AnyMeta(type): 

307 def __instancecheck__(self, obj): 

308 if self is Any: 

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

310 return super().__instancecheck__(obj) 

311 

312 def __repr__(self): 

313 if self is Any: 

314 return "typing_extensions.Any" 

315 return super().__repr__() 

316 

317 class Any(metaclass=_AnyMeta): 

318 """Special type indicating an unconstrained type. 

319 - Any is compatible with every type. 

320 - Any assumed to have all methods. 

321 - All values assumed to be instances of Any. 

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

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

324 checks. 

325 """ 

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

327 if cls is Any: 

328 raise TypeError("Any cannot be instantiated") 

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

330 

331 

332ClassVar = typing.ClassVar 

333 

334# Vendored from cpython typing._SpecialFrom 

335# Having a separate class means that instances will not be rejected by 

336# typing._type_check. 

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

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

339 

340 def __init__(self, getitem): 

341 self._getitem = getitem 

342 self._name = getitem.__name__ 

343 self.__doc__ = getitem.__doc__ 

344 

345 def __getattr__(self, item): 

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

347 return self._name 

348 

349 raise AttributeError(item) 

350 

351 def __mro_entries__(self, bases): 

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

353 

354 def __repr__(self): 

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

356 

357 def __reduce__(self): 

358 return self._name 

359 

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

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

362 

363 def __or__(self, other): 

364 return typing.Union[self, other] 

365 

366 def __ror__(self, other): 

367 return typing.Union[other, self] 

368 

369 def __instancecheck__(self, obj): 

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

371 

372 def __subclasscheck__(self, cls): 

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

374 

375 @typing._tp_cache 

376 def __getitem__(self, parameters): 

377 return self._getitem(self, parameters) 

378 

379 

380# Note that inheriting from this class means that the object will be 

381# rejected by typing._type_check, so do not use it if the special form 

382# is arguably valid as a type by itself. 

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

384 def __repr__(self): 

385 return 'typing_extensions.' + self._name 

386 

387 

388Final = typing.Final 

389 

390# Breakpoint: https://github.com/python/cpython/pull/30530 

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

392 final = typing.final 

393else: 

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

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

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

397 def final(f): 

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

399 the decorated method cannot be overridden, and decorated class 

400 cannot be subclassed. For example: 

401 

402 class Base: 

403 @final 

404 def done(self) -> None: 

405 ... 

406 class Sub(Base): 

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

408 ... 

409 @final 

410 class Leaf: 

411 ... 

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

413 ... 

414 

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

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

417 to allow runtime introspection. 

418 """ 

419 try: 

420 f.__final__ = True 

421 except (AttributeError, TypeError): 

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

423 # AttributeError happens if the object has __slots__ or a 

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

425 pass 

426 return f 

427 

428 

429if hasattr(typing, "disjoint_base"): # 3.15 

430 disjoint_base = typing.disjoint_base 

431else: 

432 def disjoint_base(cls): 

433 """This decorator marks a class as a disjoint base. 

434 

435 Child classes of a disjoint base cannot inherit from other disjoint bases that are 

436 not parent classes of the disjoint base. 

437 

438 For example: 

439 

440 @disjoint_base 

441 class Disjoint1: pass 

442 

443 @disjoint_base 

444 class Disjoint2: pass 

445 

446 class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error 

447 

448 Type checkers can use knowledge of disjoint bases to detect unreachable code 

449 and determine when two types can overlap. 

450 

451 See PEP 800.""" 

452 cls.__disjoint_base__ = True 

453 return cls 

454 

455 

456def IntVar(name): 

457 return typing.TypeVar(name) 

458 

459 

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

461# Breakpoint: https://github.com/python/cpython/pull/29334 

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

463 Literal = typing.Literal 

464else: 

465 def _flatten_literal_params(parameters): 

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

467 params = [] 

468 for p in parameters: 

469 if isinstance(p, _LiteralGenericAlias): 

470 params.extend(p.__args__) 

471 else: 

472 params.append(p) 

473 return tuple(params) 

474 

475 def _value_and_type_iter(params): 

476 for p in params: 

477 yield p, type(p) 

478 

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

480 def __eq__(self, other): 

481 if not isinstance(other, _LiteralGenericAlias): 

482 return NotImplemented 

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

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

485 return these_args_deduped == other_args_deduped 

486 

487 def __hash__(self): 

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

489 

490 class _LiteralForm(_ExtensionsSpecialForm, _root=True): 

491 def __init__(self, doc: str): 

492 self._name = 'Literal' 

493 self._doc = self.__doc__ = doc 

494 

495 def __getitem__(self, parameters): 

496 if not isinstance(parameters, tuple): 

497 parameters = (parameters,) 

498 

499 parameters = _flatten_literal_params(parameters) 

500 

501 val_type_pairs = list(_value_and_type_iter(parameters)) 

502 try: 

503 deduped_pairs = set(val_type_pairs) 

504 except TypeError: 

505 # unhashable parameters 

506 pass 

507 else: 

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

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

510 new_parameters = [] 

511 for pair in val_type_pairs: 

512 if pair in deduped_pairs: 

513 new_parameters.append(pair[0]) 

514 deduped_pairs.remove(pair) 

515 assert not deduped_pairs, deduped_pairs 

516 parameters = tuple(new_parameters) 

517 

518 return _LiteralGenericAlias(self, parameters) 

519 

520 Literal = _LiteralForm(doc="""\ 

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

522 that the corresponding value has a value literally equivalent 

523 to the provided parameter. For example: 

524 

525 var: Literal[4] = 4 

526 

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

528 the value 4 and no other value. 

529 

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

531 checking verifying that the parameter is actually a value 

532 instead of a type.""") 

533 

534 

535_overload_dummy = typing._overload_dummy 

536 

537 

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

539 overload = typing.overload 

540 get_overloads = typing.get_overloads 

541 clear_overloads = typing.clear_overloads 

542else: 

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

544 _overload_registry = collections.defaultdict( 

545 functools.partial(collections.defaultdict, dict) 

546 ) 

547 

548 def overload(func): 

549 """Decorator for overloaded functions/methods. 

550 

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

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

553 

554 @overload 

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

556 @overload 

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

558 @overload 

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

560 

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

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

563 be decorated with @overload. For example: 

564 

565 @overload 

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

567 @overload 

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

569 @overload 

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

571 def utf8(value): 

572 # implementation goes here 

573 

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

575 get_overloads() function. 

576 """ 

577 # classmethod and staticmethod 

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

579 try: 

580 _overload_registry[f.__module__][f.__qualname__][ 

581 f.__code__.co_firstlineno 

582 ] = func 

583 except AttributeError: 

584 # Not a normal function; ignore. 

585 pass 

586 return _overload_dummy 

587 

588 def get_overloads(func): 

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

590 # classmethod and staticmethod 

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

592 if f.__module__ not in _overload_registry: 

593 return [] 

594 mod_dict = _overload_registry[f.__module__] 

595 if f.__qualname__ not in mod_dict: 

596 return [] 

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

598 

599 def clear_overloads(): 

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

601 _overload_registry.clear() 

602 

603 

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

605Type = typing.Type 

606 

607# Various ABCs mimicking those in collections.abc. 

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

609Awaitable = typing.Awaitable 

610Coroutine = typing.Coroutine 

611AsyncIterable = typing.AsyncIterable 

612AsyncIterator = typing.AsyncIterator 

613Deque = typing.Deque 

614DefaultDict = typing.DefaultDict 

615OrderedDict = typing.OrderedDict 

616Counter = typing.Counter 

617ChainMap = typing.ChainMap 

618Text = typing.Text 

619TYPE_CHECKING = typing.TYPE_CHECKING 

620 

621 

622# Breakpoint: https://github.com/python/cpython/pull/118681 

623if sys.version_info >= (3, 13, 0, "beta"): 

624 from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator 

625else: 

626 def _is_dunder(attr): 

627 return attr.startswith('__') and attr.endswith('__') 

628 

629 

630 class _SpecialGenericAlias(typing._SpecialGenericAlias, _root=True): 

631 def __init__(self, origin, nparams, *, defaults, inst=True, name=None): 

632 assert nparams > 0, "`nparams` must be a positive integer" 

633 assert defaults, "Must always specify a non-empty sequence for `defaults`" 

634 super().__init__(origin, nparams, inst=inst, name=name) 

635 self._defaults = defaults 

636 

637 def __setattr__(self, attr, val): 

638 allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'} 

639 if _is_dunder(attr) or attr in allowed_attrs: 

640 object.__setattr__(self, attr, val) 

641 else: 

642 setattr(self.__origin__, attr, val) 

643 

644 @typing._tp_cache 

645 def __getitem__(self, params): 

646 if not isinstance(params, tuple): 

647 params = (params,) 

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

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

650 if ( 

651 len(params) < self._nparams 

652 and len(params) + len(self._defaults) >= self._nparams 

653 ): 

654 params = (*params, *self._defaults[len(params) - self._nparams:]) 

655 actual_len = len(params) 

656 

657 if actual_len != self._nparams: 

658 expected = f"at least {self._nparams - len(self._defaults)}" 

659 raise TypeError( 

660 f"Too {'many' if actual_len > self._nparams else 'few'}" 

661 f" arguments for {self};" 

662 f" actual {actual_len}, expected {expected}" 

663 ) 

664 return self.copy_with(params) 

665 

666 _NoneType = type(None) 

667 Generator = _SpecialGenericAlias( 

668 collections.abc.Generator, 3, defaults=(_NoneType, _NoneType) 

669 ) 

670 AsyncGenerator = _SpecialGenericAlias( 

671 collections.abc.AsyncGenerator, 2, defaults=(_NoneType,) 

672 ) 

673 ContextManager = _SpecialGenericAlias( 

674 contextlib.AbstractContextManager, 

675 2, 

676 name="ContextManager", 

677 defaults=(typing.Optional[bool],) 

678 ) 

679 AsyncContextManager = _SpecialGenericAlias( 

680 contextlib.AbstractAsyncContextManager, 

681 2, 

682 name="AsyncContextManager", 

683 defaults=(typing.Optional[bool],) 

684 ) 

685 

686 

687_PROTO_ALLOWLIST = { 

688 'collections.abc': [ 

689 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', 

690 'AsyncIterator', 'Hashable', 'Sized', 'Container', 'Collection', 

691 'Reversible', 'Buffer', 

692 ], 

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

694 'io': ['Reader', 'Writer'], 

695 'typing_extensions': ['Buffer'], 

696 'os': ['PathLike'], 

697} 

698 

699 

700_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | { 

701 "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__", 

702 "__final__", 

703} 

704 

705 

706def _get_protocol_attrs(cls): 

707 attrs = set() 

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

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

710 continue 

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

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

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

714 attrs.add(attr) 

715 return attrs 

716 

717 

718# `__match_args__` attribute was removed from protocol members in 3.13, 

719# we want to backport this change to older Python versions. 

720# 3.14 additionally added `io.Reader`, `io.Writer` and `os.PathLike` to 

721# the list of allowed protocol allowlist. 

722# https://github.com/python/cpython/issues/127647 

723if sys.version_info >= (3, 14): 

724 Protocol = typing.Protocol 

725else: 

726 def _allow_reckless_class_checks(depth=2): 

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

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

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

730 """ 

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

732 

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

734 if type(self)._is_protocol: 

735 raise TypeError('Protocols cannot be instantiated') 

736 

737 def _type_check_issubclass_arg_1(arg): 

738 """Raise TypeError if `arg` is not an instance of `type` 

739 in `issubclass(arg, <protocol>)`. 

740 

741 In most cases, this is verified by type.__subclasscheck__. 

742 Checking it again unnecessarily would slow down issubclass() checks, 

743 so, we don't perform this check unless we absolutely have to. 

744 

745 For various error paths, however, 

746 we want to ensure that *this* error message is shown to the user 

747 where relevant, rather than a typing.py-specific error message. 

748 """ 

749 if not isinstance(arg, type): 

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

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

752 

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

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

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

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

757 # This metaclass is somewhat unfortunate, 

758 # but is necessary for several reasons... 

759 # 

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

761 # That would call the methods on typing._ProtocolMeta on Python <=3.11 

762 # and those are slow 

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

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

765 pass 

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

767 for base in bases: 

768 if not ( 

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

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

771 or is_protocol(base) 

772 ): 

773 raise TypeError( 

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

775 f"got {base!r}" 

776 ) 

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

778 

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

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

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

782 cls.__protocol_attrs__ = _get_protocol_attrs(cls) 

783 

784 def __subclasscheck__(cls, other): 

785 if cls is Protocol: 

786 return type.__subclasscheck__(cls, other) 

787 if ( 

788 getattr(cls, '_is_protocol', False) 

789 and not _allow_reckless_class_checks() 

790 ): 

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

792 _type_check_issubclass_arg_1(other) 

793 raise TypeError( 

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

795 "@runtime_checkable protocols" 

796 ) 

797 if ( 

798 # this attribute is set by @runtime_checkable: 

799 cls.__non_callable_proto_members__ 

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

801 ): 

802 _type_check_issubclass_arg_1(other) 

803 non_method_attrs = sorted(cls.__non_callable_proto_members__) 

804 raise TypeError( 

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

806 f" Non-method members: {str(non_method_attrs)[1:-1]}." 

807 ) 

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

809 

810 def __instancecheck__(cls, instance): 

811 # We need this method for situations where attributes are 

812 # assigned in __init__. 

813 if cls is Protocol: 

814 return type.__instancecheck__(cls, instance) 

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

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

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

818 

819 if ( 

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

821 not _allow_reckless_class_checks() 

822 ): 

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

824 " @runtime_checkable protocols") 

825 

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

827 return True 

828 

829 for attr in cls.__protocol_attrs__: 

830 try: 

831 val = inspect.getattr_static(instance, attr) 

832 except AttributeError: 

833 break 

834 # this attribute is set by @runtime_checkable: 

835 if val is None and attr not in cls.__non_callable_proto_members__: 

836 break 

837 else: 

838 return True 

839 

840 return False 

841 

842 def __eq__(cls, other): 

843 # Hack so that typing.Generic.__class_getitem__ 

844 # treats typing_extensions.Protocol 

845 # as equivalent to typing.Protocol 

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

847 return True 

848 return cls is Protocol and other is typing.Protocol 

849 

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

851 # complains about classes with this metaclass being unhashable, 

852 # if we define only __eq__! 

853 def __hash__(cls) -> int: 

854 return type.__hash__(cls) 

855 

856 @classmethod 

857 def _proto_hook(cls, other): 

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

859 return NotImplemented 

860 

861 for attr in cls.__protocol_attrs__: 

862 for base in other.__mro__: 

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

864 if attr in base.__dict__: 

865 if base.__dict__[attr] is None: 

866 return NotImplemented 

867 break 

868 

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

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

871 if ( 

872 isinstance(annotations, collections.abc.Mapping) 

873 and attr in annotations 

874 and is_protocol(other) 

875 ): 

876 break 

877 else: 

878 return NotImplemented 

879 return True 

880 

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

882 __doc__ = typing.Protocol.__doc__ 

883 __slots__ = () 

884 _is_protocol = True 

885 _is_runtime_protocol = False 

886 

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

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

889 

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

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

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

893 

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

895 if '__subclasshook__' not in cls.__dict__: 

896 cls.__subclasshook__ = _proto_hook 

897 

898 # Prohibit instantiation for protocol classes 

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

900 cls.__init__ = _no_init 

901 

902 

903# Breakpoint: https://github.com/python/cpython/pull/113401 

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

905 runtime_checkable = typing.runtime_checkable 

906else: 

907 def runtime_checkable(cls): 

908 """Mark a protocol class as a runtime protocol. 

909 

910 Such protocol can be used with isinstance() and issubclass(). 

911 Raise TypeError if applied to a non-protocol class. 

912 This allows a simple-minded structural check very similar to 

913 one trick ponies in collections.abc such as Iterable. 

914 

915 For example:: 

916 

917 @runtime_checkable 

918 class Closable(Protocol): 

919 def close(self): ... 

920 

921 assert isinstance(open('/some/file'), Closable) 

922 

923 Warning: this will check only the presence of the required methods, 

924 not their type signatures! 

925 """ 

926 if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False): 

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

928 f' got {cls!r}') 

929 cls._is_runtime_protocol = True 

930 

931 # typing.Protocol classes on <=3.11 break if we execute this block, 

932 # because typing.Protocol classes on <=3.11 don't have a 

933 # `__protocol_attrs__` attribute, and this block relies on the 

934 # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+ 

935 # break if we *don't* execute this block, because *they* assume that all 

936 # protocol classes have a `__non_callable_proto_members__` attribute 

937 # (which this block sets) 

938 if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2): 

939 # PEP 544 prohibits using issubclass() 

940 # with protocols that have non-method members. 

941 # See gh-113320 for why we compute this attribute here, 

942 # rather than in `_ProtocolMeta.__init__` 

943 cls.__non_callable_proto_members__ = set() 

944 for attr in cls.__protocol_attrs__: 

945 try: 

946 is_callable = callable(getattr(cls, attr, None)) 

947 except Exception as e: 

948 raise TypeError( 

949 f"Failed to determine whether protocol member {attr!r} " 

950 "is a method member" 

951 ) from e 

952 else: 

953 if not is_callable: 

954 cls.__non_callable_proto_members__.add(attr) 

955 

956 return cls 

957 

958 

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

960runtime = runtime_checkable 

961 

962 

963# Our version of runtime-checkable protocols is faster on Python <=3.11 

964# Breakpoint: https://github.com/python/cpython/pull/112717 

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

966 SupportsInt = typing.SupportsInt 

967 SupportsFloat = typing.SupportsFloat 

968 SupportsComplex = typing.SupportsComplex 

969 SupportsBytes = typing.SupportsBytes 

970 SupportsIndex = typing.SupportsIndex 

971 SupportsAbs = typing.SupportsAbs 

972 SupportsRound = typing.SupportsRound 

973else: 

974 @runtime_checkable 

975 class SupportsInt(Protocol): 

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

977 __slots__ = () 

978 

979 @abc.abstractmethod 

980 def __int__(self) -> int: 

981 pass 

982 

983 @runtime_checkable 

984 class SupportsFloat(Protocol): 

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

986 __slots__ = () 

987 

988 @abc.abstractmethod 

989 def __float__(self) -> float: 

990 pass 

991 

992 @runtime_checkable 

993 class SupportsComplex(Protocol): 

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

995 __slots__ = () 

996 

997 @abc.abstractmethod 

998 def __complex__(self) -> complex: 

999 pass 

1000 

1001 @runtime_checkable 

1002 class SupportsBytes(Protocol): 

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

1004 __slots__ = () 

1005 

1006 @abc.abstractmethod 

1007 def __bytes__(self) -> bytes: 

1008 pass 

1009 

1010 @runtime_checkable 

1011 class SupportsIndex(Protocol): 

1012 __slots__ = () 

1013 

1014 @abc.abstractmethod 

1015 def __index__(self) -> int: 

1016 pass 

1017 

1018 @runtime_checkable 

1019 class SupportsAbs(Protocol[T_co]): 

1020 """ 

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

1022 """ 

1023 __slots__ = () 

1024 

1025 @abc.abstractmethod 

1026 def __abs__(self) -> T_co: 

1027 pass 

1028 

1029 @runtime_checkable 

1030 class SupportsRound(Protocol[T_co]): 

1031 """ 

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

1033 """ 

1034 __slots__ = () 

1035 

1036 @abc.abstractmethod 

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

1038 pass 

1039 

1040 

1041if hasattr(io, "Reader") and hasattr(io, "Writer"): 

1042 Reader = io.Reader 

1043 Writer = io.Writer 

1044else: 

1045 @runtime_checkable 

1046 class Reader(Protocol[T_co]): 

1047 """Protocol for simple I/O reader instances. 

1048 

1049 This protocol only supports blocking I/O. 

1050 """ 

1051 

1052 __slots__ = () 

1053 

1054 @abc.abstractmethod 

1055 def read(self, size: int = ..., /) -> T_co: 

1056 """Read data from the input stream and return it. 

1057 

1058 If *size* is specified, at most *size* items (bytes/characters) will be 

1059 read. 

1060 """ 

1061 

1062 @runtime_checkable 

1063 class Writer(Protocol[T_contra]): 

1064 """Protocol for simple I/O writer instances. 

1065 

1066 This protocol only supports blocking I/O. 

1067 """ 

1068 

1069 __slots__ = () 

1070 

1071 @abc.abstractmethod 

1072 def write(self, data: T_contra, /) -> int: 

1073 """Write *data* to the output stream and return the number of items written.""" # noqa: E501 

1074 

1075 

1076_NEEDS_SINGLETONMETA = ( 

1077 not hasattr(typing, "NoDefault") or not hasattr(typing, "NoExtraItems") 

1078) 

1079 

1080if _NEEDS_SINGLETONMETA: 

1081 class SingletonMeta(type): 

1082 def __setattr__(cls, attr, value): 

1083 # TypeError is consistent with the behavior of NoneType 

1084 raise TypeError( 

1085 f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}" 

1086 ) 

1087 

1088 

1089if hasattr(typing, "NoDefault"): 

1090 NoDefault = typing.NoDefault 

1091else: 

1092 class NoDefaultType(metaclass=SingletonMeta): 

1093 """The type of the NoDefault singleton.""" 

1094 

1095 __slots__ = () 

1096 

1097 def __new__(cls): 

1098 return globals().get("NoDefault") or object.__new__(cls) 

1099 

1100 def __repr__(self): 

1101 return "typing_extensions.NoDefault" 

1102 

1103 def __reduce__(self): 

1104 return "NoDefault" 

1105 

1106 NoDefault = NoDefaultType() 

1107 del NoDefaultType 

1108 

1109if hasattr(typing, "NoExtraItems"): 

1110 NoExtraItems = typing.NoExtraItems 

1111else: 

1112 class NoExtraItemsType(metaclass=SingletonMeta): 

1113 """The type of the NoExtraItems singleton.""" 

1114 

1115 __slots__ = () 

1116 

1117 def __new__(cls): 

1118 return globals().get("NoExtraItems") or object.__new__(cls) 

1119 

1120 def __repr__(self): 

1121 return "typing_extensions.NoExtraItems" 

1122 

1123 def __reduce__(self): 

1124 return "NoExtraItems" 

1125 

1126 NoExtraItems = NoExtraItemsType() 

1127 del NoExtraItemsType 

1128 

1129if _NEEDS_SINGLETONMETA: 

1130 del SingletonMeta 

1131 

1132 

1133# Update this to something like >=3.13.0b1 if and when 

1134# PEP 728 is implemented in CPython 

1135_PEP_728_IMPLEMENTED = False 

1136 

1137if _PEP_728_IMPLEMENTED: 

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

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

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

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

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

1143 # Aaaand on 3.12 we add __orig_bases__ to TypedDict 

1144 # to enable better runtime introspection. 

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

1146 # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier. 

1147 # PEP 728 (still pending) makes more changes. 

1148 TypedDict = typing.TypedDict 

1149 _TypedDictMeta = typing._TypedDictMeta 

1150 is_typeddict = typing.is_typeddict 

1151else: 

1152 # 3.10.0 and later 

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

1154 

1155 def _get_typeddict_qualifiers(annotation_type): 

1156 while True: 

1157 annotation_origin = get_origin(annotation_type) 

1158 if annotation_origin is Annotated: 

1159 annotation_args = get_args(annotation_type) 

1160 if annotation_args: 

1161 annotation_type = annotation_args[0] 

1162 else: 

1163 break 

1164 elif annotation_origin is Required: 

1165 yield Required 

1166 annotation_type, = get_args(annotation_type) 

1167 elif annotation_origin is NotRequired: 

1168 yield NotRequired 

1169 annotation_type, = get_args(annotation_type) 

1170 elif annotation_origin is ReadOnly: 

1171 yield ReadOnly 

1172 annotation_type, = get_args(annotation_type) 

1173 else: 

1174 break 

1175 

1176 class _TypedDictMeta(type): 

1177 

1178 def __new__(cls, name, bases, ns, *, total=True, closed=None, 

1179 extra_items=NoExtraItems): 

1180 """Create new typed dict class object. 

1181 

1182 This method is called when TypedDict is subclassed, 

1183 or when TypedDict is instantiated. This way 

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

1185 Subclasses and instances of TypedDict return actual dictionaries. 

1186 """ 

1187 for base in bases: 

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

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

1190 'and a non-TypedDict base class') 

1191 if closed is not None and extra_items is not NoExtraItems: 

1192 raise TypeError(f"Cannot combine closed={closed!r} and extra_items") 

1193 

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

1195 generic_base = (typing.Generic,) 

1196 else: 

1197 generic_base = () 

1198 

1199 ns_annotations = ns.pop('__annotations__', None) 

1200 

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

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

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

1204 tp_dict.__name__ = name 

1205 if tp_dict.__qualname__ == "Protocol": 

1206 tp_dict.__qualname__ = name 

1207 

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

1209 tp_dict.__orig_bases__ = bases 

1210 

1211 annotations = {} 

1212 own_annotate = None 

1213 if ns_annotations is not None: 

1214 own_annotations = ns_annotations 

1215 elif sys.version_info >= (3, 14): 

1216 if hasattr(annotationlib, "get_annotate_from_class_namespace"): 

1217 own_annotate = annotationlib.get_annotate_from_class_namespace(ns) 

1218 else: 

1219 # 3.14.0a7 and earlier 

1220 own_annotate = ns.get("__annotate__") 

1221 if own_annotate is not None: 

1222 own_annotations = annotationlib.call_annotate_function( 

1223 own_annotate, Format.FORWARDREF, owner=tp_dict 

1224 ) 

1225 else: 

1226 own_annotations = {} 

1227 else: 

1228 own_annotations = {} 

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

1230 if _TAKES_MODULE: 

1231 own_checked_annotations = { 

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

1233 for n, tp in own_annotations.items() 

1234 } 

1235 else: 

1236 own_checked_annotations = { 

1237 n: typing._type_check(tp, msg) 

1238 for n, tp in own_annotations.items() 

1239 } 

1240 required_keys = set() 

1241 optional_keys = set() 

1242 readonly_keys = set() 

1243 mutable_keys = set() 

1244 extra_items_type = extra_items 

1245 

1246 for base in bases: 

1247 base_dict = base.__dict__ 

1248 

1249 if sys.version_info <= (3, 14): 

1250 annotations.update(base_dict.get('__annotations__', {})) 

1251 base_required = base_dict.get('__required_keys__', set()) 

1252 required_keys |= base_required 

1253 optional_keys -= base_required 

1254 

1255 base_optional = base_dict.get('__optional_keys__', set()) 

1256 required_keys -= base_optional 

1257 optional_keys |= base_optional 

1258 

1259 readonly_keys.update(base_dict.get('__readonly_keys__', ())) 

1260 mutable_keys.update(base_dict.get('__mutable_keys__', ())) 

1261 

1262 # This was specified in an earlier version of PEP 728. Support 

1263 # is retained for backwards compatibility, but only for Python 

1264 # 3.13 and lower. 

1265 if (closed and sys.version_info < (3, 14) 

1266 and "__extra_items__" in own_checked_annotations): 

1267 annotation_type = own_checked_annotations.pop("__extra_items__") 

1268 qualifiers = set(_get_typeddict_qualifiers(annotation_type)) 

1269 if Required in qualifiers: 

1270 raise TypeError( 

1271 "Special key __extra_items__ does not support " 

1272 "Required" 

1273 ) 

1274 if NotRequired in qualifiers: 

1275 raise TypeError( 

1276 "Special key __extra_items__ does not support " 

1277 "NotRequired" 

1278 ) 

1279 extra_items_type = annotation_type 

1280 

1281 annotations.update(own_checked_annotations) 

1282 for annotation_key, annotation_type in own_checked_annotations.items(): 

1283 qualifiers = set(_get_typeddict_qualifiers(annotation_type)) 

1284 

1285 if Required in qualifiers: 

1286 is_required = True 

1287 elif NotRequired in qualifiers: 

1288 is_required = False 

1289 else: 

1290 is_required = total 

1291 

1292 if is_required: 

1293 required_keys.add(annotation_key) 

1294 optional_keys.discard(annotation_key) 

1295 else: 

1296 optional_keys.add(annotation_key) 

1297 required_keys.discard(annotation_key) 

1298 

1299 if ReadOnly in qualifiers: 

1300 mutable_keys.discard(annotation_key) 

1301 readonly_keys.add(annotation_key) 

1302 else: 

1303 mutable_keys.add(annotation_key) 

1304 readonly_keys.discard(annotation_key) 

1305 

1306 # Breakpoint: https://github.com/python/cpython/pull/119891 

1307 if sys.version_info >= (3, 14): 

1308 def __annotate__(format): 

1309 annos = {} 

1310 for base in bases: 

1311 if base is Generic: 

1312 continue 

1313 base_annotate = base.__annotate__ 

1314 if base_annotate is None: 

1315 continue 

1316 base_annos = annotationlib.call_annotate_function( 

1317 base_annotate, format, owner=base) 

1318 annos.update(base_annos) 

1319 if own_annotate is not None: 

1320 own = annotationlib.call_annotate_function( 

1321 own_annotate, format, owner=tp_dict) 

1322 if format != Format.STRING: 

1323 own = { 

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

1325 for n, tp in own.items() 

1326 } 

1327 elif format == Format.STRING: 

1328 own = annotationlib.annotations_to_string(own_annotations) 

1329 elif format in (Format.FORWARDREF, Format.VALUE): 

1330 own = own_checked_annotations 

1331 else: 

1332 raise NotImplementedError(format) 

1333 annos.update(own) 

1334 return annos 

1335 

1336 tp_dict.__annotate__ = __annotate__ 

1337 else: 

1338 tp_dict.__annotations__ = annotations 

1339 tp_dict.__required_keys__ = frozenset(required_keys) 

1340 tp_dict.__optional_keys__ = frozenset(optional_keys) 

1341 tp_dict.__readonly_keys__ = frozenset(readonly_keys) 

1342 tp_dict.__mutable_keys__ = frozenset(mutable_keys) 

1343 tp_dict.__total__ = total 

1344 tp_dict.__closed__ = closed 

1345 tp_dict.__extra_items__ = extra_items_type 

1346 return tp_dict 

1347 

1348 __call__ = dict # static method 

1349 

1350 def __subclasscheck__(cls, other): 

1351 # Typed dicts are only for static structural subtyping. 

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

1353 

1354 __instancecheck__ = __subclasscheck__ 

1355 

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

1357 

1358 def _create_typeddict( 

1359 typename, 

1360 fields, 

1361 /, 

1362 *, 

1363 typing_is_inline, 

1364 total, 

1365 closed, 

1366 extra_items, 

1367 **kwargs, 

1368 ): 

1369 if fields is _marker or fields is None: 

1370 if fields is _marker: 

1371 deprecated_thing = ( 

1372 "Failing to pass a value for the 'fields' parameter" 

1373 ) 

1374 else: 

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

1376 

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

1378 deprecation_msg = ( 

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

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

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

1382 ) + example + "." 

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

1384 # Support a field called "closed" 

1385 if closed is not False and closed is not True and closed is not None: 

1386 kwargs["closed"] = closed 

1387 closed = None 

1388 # Or "extra_items" 

1389 if extra_items is not NoExtraItems: 

1390 kwargs["extra_items"] = extra_items 

1391 extra_items = NoExtraItems 

1392 fields = kwargs 

1393 elif kwargs: 

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

1395 " but not both") 

1396 if kwargs: 

1397 # Breakpoint: https://github.com/python/cpython/pull/104891 

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

1399 raise TypeError("TypedDict takes no keyword arguments") 

1400 warnings.warn( 

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

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

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

1404 DeprecationWarning, 

1405 stacklevel=2, 

1406 ) 

1407 

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

1409 module = _caller(depth=4 if typing_is_inline else 2) 

1410 if module is not None: 

1411 # Setting correct module is necessary to make typed dict classes 

1412 # pickleable. 

1413 ns['__module__'] = module 

1414 

1415 td = _TypedDictMeta(typename, (), ns, total=total, closed=closed, 

1416 extra_items=extra_items) 

1417 td.__orig_bases__ = (TypedDict,) 

1418 return td 

1419 

1420 class _TypedDictSpecialForm(_SpecialForm, _root=True): 

1421 def __call__( 

1422 self, 

1423 typename, 

1424 fields=_marker, 

1425 /, 

1426 *, 

1427 total=True, 

1428 closed=None, 

1429 extra_items=NoExtraItems, 

1430 **kwargs 

1431 ): 

1432 return _create_typeddict( 

1433 typename, 

1434 fields, 

1435 typing_is_inline=False, 

1436 total=total, 

1437 closed=closed, 

1438 extra_items=extra_items, 

1439 **kwargs, 

1440 ) 

1441 

1442 def __mro_entries__(self, bases): 

1443 return (_TypedDict,) 

1444 

1445 @_TypedDictSpecialForm 

1446 def TypedDict(self, args): 

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

1448 

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

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

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

1452 is not checked at runtime. 

1453 

1454 Usage:: 

1455 

1456 class Point2D(TypedDict): 

1457 x: int 

1458 y: int 

1459 label: str 

1460 

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

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

1463 

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

1465 

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

1467 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. 

1468 TypedDict supports an additional equivalent form:: 

1469 

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

1471 

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

1473 to override this by specifying totality:: 

1474 

1475 class Point2D(TypedDict, total=False): 

1476 x: int 

1477 y: int 

1478 

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

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

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

1482 class body be required. 

1483 

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

1485 individual keys as being required or not required:: 

1486 

1487 class Point2D(TypedDict): 

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

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

1490 

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

1492 """ 

1493 # This runs when creating inline TypedDicts: 

1494 if not isinstance(args, dict): 

1495 raise TypeError( 

1496 "TypedDict[...] should be used with a single dict argument" 

1497 ) 

1498 

1499 return _create_typeddict( 

1500 "<inline TypedDict>", 

1501 args, 

1502 typing_is_inline=True, 

1503 total=True, 

1504 closed=True, 

1505 extra_items=NoExtraItems, 

1506 ) 

1507 

1508 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) 

1509 

1510 def is_typeddict(tp): 

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

1512 

1513 For example:: 

1514 class Film(TypedDict): 

1515 title: str 

1516 year: int 

1517 

1518 is_typeddict(Film) # => True 

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

1520 """ 

1521 return isinstance(tp, _TYPEDDICT_TYPES) 

1522 

1523 

1524if hasattr(typing, "assert_type"): 

1525 assert_type = typing.assert_type 

1526 

1527else: 

1528 def assert_type(val, typ, /): 

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

1530 

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

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

1533 

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

1535 assert_type(name, str) # ok 

1536 assert_type(name, int) # type checker error 

1537 

1538 At runtime this returns the first argument unchanged and otherwise 

1539 does nothing. 

1540 """ 

1541 return val 

1542 

1543 

1544if hasattr(typing, "ReadOnly"): # 3.13+ 

1545 get_type_hints = typing.get_type_hints 

1546else: # <=3.13 

1547 # replaces _strip_annotations() 

1548 def _strip_extras(t): 

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

1550 if isinstance(t, typing._AnnotatedAlias): 

1551 return _strip_extras(t.__origin__) 

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

1553 return _strip_extras(t.__args__[0]) 

1554 if isinstance(t, typing._GenericAlias): 

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

1556 if stripped_args == t.__args__: 

1557 return t 

1558 return t.copy_with(stripped_args) 

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

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

1561 if stripped_args == t.__args__: 

1562 return t 

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

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

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

1566 if stripped_args == t.__args__: 

1567 return t 

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

1569 

1570 return t 

1571 

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

1573 """Return type hints for an object. 

1574 

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

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

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

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

1579 (unless 'include_extras=True'). 

1580 

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

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

1583 inherited members. 

1584 

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

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

1587 present. 

1588 

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

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

1591 search order is locals first, then globals. 

1592 

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

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

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

1596 to have globals, an empty dictionary is used. 

1597 

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

1599 locals. 

1600 

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

1602 locals, respectively. 

1603 """ 

1604 hint = typing.get_type_hints( 

1605 obj, globalns=globalns, localns=localns, include_extras=True 

1606 ) 

1607 # Breakpoint: https://github.com/python/cpython/pull/30304 

1608 if sys.version_info < (3, 11): 

1609 _clean_optional(obj, hint, globalns, localns) 

1610 if include_extras: 

1611 return hint 

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

1613 

1614 _NoneType = type(None) 

1615 

1616 def _could_be_inserted_optional(t): 

1617 """detects Union[..., None] pattern""" 

1618 if not isinstance(t, typing._UnionGenericAlias): 

1619 return False 

1620 # Assume if last argument is not None they are user defined 

1621 if t.__args__[-1] is not _NoneType: 

1622 return False 

1623 return True 

1624 

1625 # < 3.11 

1626 def _clean_optional(obj, hints, globalns=None, localns=None): 

1627 # reverts injected Union[..., None] cases from typing.get_type_hints 

1628 # when a None default value is used. 

1629 # see https://github.com/python/typing_extensions/issues/310 

1630 if not hints or isinstance(obj, type): 

1631 return 

1632 defaults = typing._get_defaults(obj) # avoid accessing __annotations___ 

1633 if not defaults: 

1634 return 

1635 original_hints = obj.__annotations__ 

1636 for name, value in hints.items(): 

1637 # Not a Union[..., None] or replacement conditions not fullfilled 

1638 if (not _could_be_inserted_optional(value) 

1639 or name not in defaults 

1640 or defaults[name] is not None 

1641 ): 

1642 continue 

1643 original_value = original_hints[name] 

1644 # value=NoneType should have caused a skip above but check for safety 

1645 if original_value is None: 

1646 original_value = _NoneType 

1647 # Forward reference 

1648 if isinstance(original_value, str): 

1649 if globalns is None: 

1650 if isinstance(obj, _types.ModuleType): 

1651 globalns = obj.__dict__ 

1652 else: 

1653 nsobj = obj 

1654 # Find globalns for the unwrapped object. 

1655 while hasattr(nsobj, '__wrapped__'): 

1656 nsobj = nsobj.__wrapped__ 

1657 globalns = getattr(nsobj, '__globals__', {}) 

1658 if localns is None: 

1659 localns = globalns 

1660 elif localns is None: 

1661 localns = globalns 

1662 

1663 original_value = ForwardRef( 

1664 original_value, 

1665 is_argument=not isinstance(obj, _types.ModuleType) 

1666 ) 

1667 original_evaluated = typing._eval_type(original_value, globalns, localns) 

1668 # Compare if values differ. Note that even if equal 

1669 # value might be cached by typing._tp_cache contrary to original_evaluated 

1670 if original_evaluated != value or ( 

1671 # 3.10: ForwardRefs of UnionType might be turned into _UnionGenericAlias 

1672 hasattr(_types, "UnionType") 

1673 and isinstance(original_evaluated, _types.UnionType) 

1674 and not isinstance(value, _types.UnionType) 

1675 ): 

1676 hints[name] = original_evaluated 

1677 

1678# Python 3.9 has get_origin() and get_args() but those implementations don't support 

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

1680# Breakpoint: https://github.com/python/cpython/pull/25298 

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

1682 get_origin = typing.get_origin 

1683 get_args = typing.get_args 

1684# 3.9 

1685else: 

1686 def get_origin(tp): 

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

1688 

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

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

1691 

1692 get_origin(Literal[42]) is Literal 

1693 get_origin(int) is None 

1694 get_origin(ClassVar[int]) is ClassVar 

1695 get_origin(Generic) is Generic 

1696 get_origin(Generic[T]) is Generic 

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

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

1699 get_origin(P.args) is P 

1700 """ 

1701 if isinstance(tp, typing._AnnotatedAlias): 

1702 return Annotated 

1703 if isinstance(tp, (typing._BaseGenericAlias, _types.GenericAlias, 

1704 ParamSpecArgs, ParamSpecKwargs)): 

1705 return tp.__origin__ 

1706 if tp is typing.Generic: 

1707 return typing.Generic 

1708 return None 

1709 

1710 def get_args(tp): 

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

1712 

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

1714 Examples:: 

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

1716 get_args(int) == () 

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

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

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

1720 """ 

1721 if isinstance(tp, typing._AnnotatedAlias): 

1722 return (tp.__origin__, *tp.__metadata__) 

1723 if isinstance(tp, (typing._GenericAlias, _types.GenericAlias)): 

1724 res = tp.__args__ 

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

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

1727 return res 

1728 return () 

1729 

1730 

1731# 3.10+ 

1732if hasattr(typing, 'TypeAlias'): 

1733 TypeAlias = typing.TypeAlias 

1734# 3.9 

1735else: 

1736 @_ExtensionsSpecialForm 

1737 def TypeAlias(self, parameters): 

1738 """Special marker indicating that an assignment should 

1739 be recognized as a proper type alias definition by type 

1740 checkers. 

1741 

1742 For example:: 

1743 

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

1745 

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

1747 """ 

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

1749 

1750 

1751def _set_default(type_param, default): 

1752 type_param.has_default = lambda: default is not NoDefault 

1753 type_param.__default__ = default 

1754 

1755 

1756def _set_module(typevarlike): 

1757 # for pickling: 

1758 def_mod = _caller(depth=2) 

1759 if def_mod != 'typing_extensions': 

1760 typevarlike.__module__ = def_mod 

1761 

1762 

1763class _DefaultMixin: 

1764 """Mixin for TypeVarLike defaults.""" 

1765 

1766 __slots__ = () 

1767 __init__ = _set_default 

1768 

1769 

1770# Classes using this metaclass must provide a _backported_typevarlike ClassVar 

1771class _TypeVarLikeMeta(type): 

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

1773 return isinstance(__instance, cls._backported_typevarlike) 

1774 

1775 

1776if _PEP_696_IMPLEMENTED: 

1777 from typing import TypeVar 

1778else: 

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

1780 class TypeVar(metaclass=_TypeVarLikeMeta): 

1781 """Type variable.""" 

1782 

1783 _backported_typevarlike = typing.TypeVar 

1784 

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

1786 covariant=False, contravariant=False, 

1787 default=NoDefault, infer_variance=False): 

1788 if hasattr(typing, "TypeAliasType"): 

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

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

1791 covariant=covariant, contravariant=contravariant, 

1792 infer_variance=infer_variance) 

1793 else: 

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

1795 covariant=covariant, contravariant=contravariant) 

1796 if infer_variance and (covariant or contravariant): 

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

1798 typevar.__infer_variance__ = infer_variance 

1799 

1800 _set_default(typevar, default) 

1801 _set_module(typevar) 

1802 

1803 def _tvar_prepare_subst(alias, args): 

1804 if ( 

1805 typevar.has_default() 

1806 and alias.__parameters__.index(typevar) == len(args) 

1807 ): 

1808 args += (typevar.__default__,) 

1809 return args 

1810 

1811 typevar.__typing_prepare_subst__ = _tvar_prepare_subst 

1812 return typevar 

1813 

1814 def __init_subclass__(cls) -> None: 

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

1816 

1817 

1818# Python 3.10+ has PEP 612 

1819if hasattr(typing, 'ParamSpecArgs'): 

1820 ParamSpecArgs = typing.ParamSpecArgs 

1821 ParamSpecKwargs = typing.ParamSpecKwargs 

1822# 3.9 

1823else: 

1824 class _Immutable: 

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

1826 __slots__ = () 

1827 

1828 def __copy__(self): 

1829 return self 

1830 

1831 def __deepcopy__(self, memo): 

1832 return self 

1833 

1834 class ParamSpecArgs(_Immutable): 

1835 """The args for a ParamSpec object. 

1836 

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

1838 

1839 ParamSpecArgs objects have a reference back to their ParamSpec: 

1840 

1841 P.args.__origin__ is P 

1842 

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

1844 static type checkers. 

1845 """ 

1846 def __init__(self, origin): 

1847 self.__origin__ = origin 

1848 

1849 def __repr__(self): 

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

1851 

1852 def __eq__(self, other): 

1853 if not isinstance(other, ParamSpecArgs): 

1854 return NotImplemented 

1855 return self.__origin__ == other.__origin__ 

1856 

1857 class ParamSpecKwargs(_Immutable): 

1858 """The kwargs for a ParamSpec object. 

1859 

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

1861 

1862 ParamSpecKwargs objects have a reference back to their ParamSpec: 

1863 

1864 P.kwargs.__origin__ is P 

1865 

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

1867 static type checkers. 

1868 """ 

1869 def __init__(self, origin): 

1870 self.__origin__ = origin 

1871 

1872 def __repr__(self): 

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

1874 

1875 def __eq__(self, other): 

1876 if not isinstance(other, ParamSpecKwargs): 

1877 return NotImplemented 

1878 return self.__origin__ == other.__origin__ 

1879 

1880 

1881if _PEP_696_IMPLEMENTED: 

1882 from typing import ParamSpec 

1883 

1884# 3.10+ 

1885elif hasattr(typing, 'ParamSpec'): 

1886 

1887 # Add default parameter - PEP 696 

1888 class ParamSpec(metaclass=_TypeVarLikeMeta): 

1889 """Parameter specification.""" 

1890 

1891 _backported_typevarlike = typing.ParamSpec 

1892 

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

1894 covariant=False, contravariant=False, 

1895 infer_variance=False, default=NoDefault): 

1896 if hasattr(typing, "TypeAliasType"): 

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

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

1899 covariant=covariant, 

1900 contravariant=contravariant, 

1901 infer_variance=infer_variance) 

1902 else: 

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

1904 covariant=covariant, 

1905 contravariant=contravariant) 

1906 paramspec.__infer_variance__ = infer_variance 

1907 

1908 _set_default(paramspec, default) 

1909 _set_module(paramspec) 

1910 

1911 def _paramspec_prepare_subst(alias, args): 

1912 params = alias.__parameters__ 

1913 i = params.index(paramspec) 

1914 if i == len(args) and paramspec.has_default(): 

1915 args = [*args, paramspec.__default__] 

1916 if i >= len(args): 

1917 raise TypeError(f"Too few arguments for {alias}") 

1918 # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. 

1919 if len(params) == 1 and not typing._is_param_expr(args[0]): 

1920 assert i == 0 

1921 args = (args,) 

1922 # Convert lists to tuples to help other libraries cache the results. 

1923 elif isinstance(args[i], list): 

1924 args = (*args[:i], tuple(args[i]), *args[i + 1:]) 

1925 return args 

1926 

1927 paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst 

1928 return paramspec 

1929 

1930 def __init_subclass__(cls) -> None: 

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

1932 

1933# 3.9 

1934else: 

1935 

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

1937 class ParamSpec(list, _DefaultMixin): 

1938 """Parameter specification variable. 

1939 

1940 Usage:: 

1941 

1942 P = ParamSpec('P') 

1943 

1944 Parameter specification variables exist primarily for the benefit of static 

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

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

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

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

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

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

1951 example for annotating a decorator:: 

1952 

1953 T = TypeVar('T') 

1954 P = ParamSpec('P') 

1955 

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

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

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

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

1960 return f(*args, **kwargs) 

1961 return inner 

1962 

1963 @add_logging 

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

1965 '''Add two numbers together.''' 

1966 return x + y 

1967 

1968 Parameter specification variables defined with covariant=True or 

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

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

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

1972 

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

1974 

1975 P.__name__ == 'T' 

1976 P.__bound__ == None 

1977 P.__covariant__ == False 

1978 P.__contravariant__ == False 

1979 

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

1981 be pickled. 

1982 """ 

1983 

1984 # Trick Generic __parameters__. 

1985 __class__ = typing.TypeVar 

1986 

1987 @property 

1988 def args(self): 

1989 return ParamSpecArgs(self) 

1990 

1991 @property 

1992 def kwargs(self): 

1993 return ParamSpecKwargs(self) 

1994 

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

1996 infer_variance=False, default=NoDefault): 

1997 list.__init__(self, [self]) 

1998 self.__name__ = name 

1999 self.__covariant__ = bool(covariant) 

2000 self.__contravariant__ = bool(contravariant) 

2001 self.__infer_variance__ = bool(infer_variance) 

2002 if bound: 

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

2004 else: 

2005 self.__bound__ = None 

2006 _DefaultMixin.__init__(self, default) 

2007 

2008 # for pickling: 

2009 def_mod = _caller() 

2010 if def_mod != 'typing_extensions': 

2011 self.__module__ = def_mod 

2012 

2013 def __repr__(self): 

2014 if self.__infer_variance__: 

2015 prefix = '' 

2016 elif self.__covariant__: 

2017 prefix = '+' 

2018 elif self.__contravariant__: 

2019 prefix = '-' 

2020 else: 

2021 prefix = '~' 

2022 return prefix + self.__name__ 

2023 

2024 def __hash__(self): 

2025 return object.__hash__(self) 

2026 

2027 def __eq__(self, other): 

2028 return self is other 

2029 

2030 def __reduce__(self): 

2031 return self.__name__ 

2032 

2033 # Hack to get typing._type_check to pass. 

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

2035 pass 

2036 

2037 def __init_subclass__(cls) -> None: 

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

2039 

2040 

2041# 3.9 

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

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

2044 

2045 # 3.9.0-1 

2046 if not hasattr(typing, '_type_convert'): 

2047 def _type_convert(arg, module=None, *, allow_special_forms=False): 

2048 """For converting None to type(None), and strings to ForwardRef.""" 

2049 if arg is None: 

2050 return type(None) 

2051 if isinstance(arg, str): 

2052 if sys.version_info <= (3, 9, 6): 

2053 return ForwardRef(arg) 

2054 if sys.version_info <= (3, 9, 7): 

2055 return ForwardRef(arg, module=module) 

2056 return ForwardRef(arg, module=module, is_class=allow_special_forms) 

2057 return arg 

2058 else: 

2059 _type_convert = typing._type_convert 

2060 

2061 class _ConcatenateGenericAlias(list): 

2062 

2063 # Trick Generic into looking into this for __parameters__. 

2064 __class__ = typing._GenericAlias 

2065 

2066 def __init__(self, origin, args): 

2067 # Cannot use `super().__init__` here because of the `__class__` assignment 

2068 # in the class body (https://github.com/python/typing_extensions/issues/661) 

2069 list.__init__(self, args) 

2070 self.__origin__ = origin 

2071 self.__args__ = args 

2072 

2073 def __repr__(self): 

2074 _type_repr = typing._type_repr 

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

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

2077 

2078 def __hash__(self): 

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

2080 

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

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

2083 pass 

2084 

2085 @property 

2086 def __parameters__(self): 

2087 return tuple( 

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

2089 ) 

2090 

2091 # 3.9 used by __getitem__ below 

2092 def copy_with(self, params): 

2093 if isinstance(params[-1], _ConcatenateGenericAlias): 

2094 params = (*params[:-1], *params[-1].__args__) 

2095 elif isinstance(params[-1], (list, tuple)): 

2096 return (*params[:-1], *params[-1]) 

2097 elif (not (params[-1] is ... or isinstance(params[-1], ParamSpec))): 

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

2099 "ParamSpec variable or ellipsis.") 

2100 return self.__class__(self.__origin__, params) 

2101 

2102 # 3.9; accessed during GenericAlias.__getitem__ when substituting 

2103 def __getitem__(self, args): 

2104 if self.__origin__ in (Generic, Protocol): 

2105 # Can't subscript Generic[...] or Protocol[...]. 

2106 raise TypeError(f"Cannot subscript already-subscripted {self}") 

2107 if not self.__parameters__: 

2108 raise TypeError(f"{self} is not a generic class") 

2109 

2110 if not isinstance(args, tuple): 

2111 args = (args,) 

2112 args = _unpack_args(*(_type_convert(p) for p in args)) 

2113 params = self.__parameters__ 

2114 for param in params: 

2115 prepare = getattr(param, "__typing_prepare_subst__", None) 

2116 if prepare is not None: 

2117 args = prepare(self, args) 

2118 # 3.9 & typing.ParamSpec 

2119 elif isinstance(param, ParamSpec): 

2120 i = params.index(param) 

2121 if ( 

2122 i == len(args) 

2123 and getattr(param, '__default__', NoDefault) is not NoDefault 

2124 ): 

2125 args = [*args, param.__default__] 

2126 if i >= len(args): 

2127 raise TypeError(f"Too few arguments for {self}") 

2128 # Special case for Z[[int, str, bool]] == Z[int, str, bool] 

2129 if len(params) == 1 and not _is_param_expr(args[0]): 

2130 assert i == 0 

2131 args = (args,) 

2132 elif ( 

2133 isinstance(args[i], list) 

2134 # 3.9 

2135 # This class inherits from list do not convert 

2136 and not isinstance(args[i], _ConcatenateGenericAlias) 

2137 ): 

2138 args = (*args[:i], tuple(args[i]), *args[i + 1:]) 

2139 

2140 alen = len(args) 

2141 plen = len(params) 

2142 if alen != plen: 

2143 raise TypeError( 

2144 f"Too {'many' if alen > plen else 'few'} arguments for {self};" 

2145 f" actual {alen}, expected {plen}" 

2146 ) 

2147 

2148 subst = dict(zip(self.__parameters__, args)) 

2149 # determine new args 

2150 new_args = [] 

2151 for arg in self.__args__: 

2152 if isinstance(arg, type): 

2153 new_args.append(arg) 

2154 continue 

2155 if isinstance(arg, TypeVar): 

2156 arg = subst[arg] 

2157 if ( 

2158 (isinstance(arg, typing._GenericAlias) and _is_unpack(arg)) 

2159 or ( 

2160 hasattr(_types, "GenericAlias") 

2161 and isinstance(arg, _types.GenericAlias) 

2162 and getattr(arg, "__unpacked__", False) 

2163 ) 

2164 ): 

2165 raise TypeError(f"{arg} is not valid as type argument") 

2166 

2167 elif isinstance(arg, 

2168 typing._GenericAlias 

2169 if not hasattr(_types, "GenericAlias") else 

2170 (typing._GenericAlias, _types.GenericAlias) 

2171 ): 

2172 subparams = arg.__parameters__ 

2173 if subparams: 

2174 subargs = tuple(subst[x] for x in subparams) 

2175 arg = arg[subargs] 

2176 new_args.append(arg) 

2177 return self.copy_with(tuple(new_args)) 

2178 

2179# 3.10+ 

2180else: 

2181 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias 

2182 

2183 # 3.10 

2184 if sys.version_info < (3, 11): 

2185 

2186 class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True): 

2187 # needed for checks in collections.abc.Callable to accept this class 

2188 __module__ = "typing" 

2189 

2190 def copy_with(self, params): 

2191 if isinstance(params[-1], (list, tuple)): 

2192 return (*params[:-1], *params[-1]) 

2193 if isinstance(params[-1], typing._ConcatenateGenericAlias): 

2194 params = (*params[:-1], *params[-1].__args__) 

2195 elif not (params[-1] is ... or isinstance(params[-1], ParamSpec)): 

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

2197 "ParamSpec variable or ellipsis.") 

2198 return super(typing._ConcatenateGenericAlias, self).copy_with(params) 

2199 

2200 def __getitem__(self, args): 

2201 value = super().__getitem__(args) 

2202 if isinstance(value, tuple) and any(_is_unpack(t) for t in value): 

2203 return tuple(_unpack_args(*(n for n in value))) 

2204 return value 

2205 

2206 

2207# 3.9.2 

2208class _EllipsisDummy: ... 

2209 

2210 

2211# <=3.10 

2212def _create_concatenate_alias(origin, parameters): 

2213 if parameters[-1] is ... and sys.version_info < (3, 9, 2): 

2214 # Hack: Arguments must be types, replace it with one. 

2215 parameters = (*parameters[:-1], _EllipsisDummy) 

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

2217 concatenate = _ConcatenateGenericAlias(origin, parameters, 

2218 _typevar_types=(TypeVar, ParamSpec), 

2219 _paramspec_tvars=True) 

2220 else: 

2221 concatenate = _ConcatenateGenericAlias(origin, parameters) 

2222 if parameters[-1] is not _EllipsisDummy: 

2223 return concatenate 

2224 # Remove dummy again 

2225 concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ... 

2226 for p in concatenate.__args__) 

2227 if sys.version_info < (3, 10): 

2228 # backport needs __args__ adjustment only 

2229 return concatenate 

2230 concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__ 

2231 if p is not _EllipsisDummy) 

2232 return concatenate 

2233 

2234 

2235# <=3.10 

2236@typing._tp_cache 

2237def _concatenate_getitem(self, parameters): 

2238 if parameters == (): 

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

2240 if not isinstance(parameters, tuple): 

2241 parameters = (parameters,) 

2242 if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)): 

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

2244 "ParamSpec variable or ellipsis.") 

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

2246 parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]), 

2247 parameters[-1]) 

2248 return _create_concatenate_alias(self, parameters) 

2249 

2250 

2251# 3.11+; Concatenate does not accept ellipsis in 3.10 

2252# Breakpoint: https://github.com/python/cpython/pull/30969 

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

2254 Concatenate = typing.Concatenate 

2255# <=3.10 

2256else: 

2257 @_ExtensionsSpecialForm 

2258 def Concatenate(self, parameters): 

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

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

2261 callable. 

2262 

2263 For example:: 

2264 

2265 Callable[Concatenate[int, P], int] 

2266 

2267 See PEP 612 for detailed information. 

2268 """ 

2269 return _concatenate_getitem(self, parameters) 

2270 

2271 

2272# 3.10+ 

2273if hasattr(typing, 'TypeGuard'): 

2274 TypeGuard = typing.TypeGuard 

2275# 3.9 

2276else: 

2277 @_ExtensionsSpecialForm 

2278 def TypeGuard(self, parameters): 

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

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

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

2282 

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

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

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

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

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

2288 

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

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

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

2292 

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

2294 function: 

2295 

2296 1. The return value is a boolean. 

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

2298 is the type inside ``TypeGuard``. 

2299 

2300 For example:: 

2301 

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

2303 # "isinstance" type guard 

2304 if isinstance(val, str): 

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

2306 ... 

2307 else: 

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

2309 ... 

2310 

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

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

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

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

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

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

2317 

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

2319 PEP 647 (User-Defined Type Guards). 

2320 """ 

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

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

2323 

2324 

2325# 3.13+ 

2326if hasattr(typing, 'TypeIs'): 

2327 TypeIs = typing.TypeIs 

2328# <=3.12 

2329else: 

2330 @_ExtensionsSpecialForm 

2331 def TypeIs(self, parameters): 

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

2333 type narrower function. ``TypeIs`` only accepts a single type argument. 

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

2335 

2336 ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static 

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

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

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

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

2341 

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

2343 as a type guard. Such a function should use ``TypeIs[...]`` as its 

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

2345 

2346 Using ``-> TypeIs`` tells the static type checker that for a given 

2347 function: 

2348 

2349 1. The return value is a boolean. 

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

2351 is the intersection of the type inside ``TypeIs`` and the argument's 

2352 previously known type. 

2353 

2354 For example:: 

2355 

2356 def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]: 

2357 return hasattr(val, '__await__') 

2358 

2359 def f(val: Union[int, Awaitable[int]]) -> int: 

2360 if is_awaitable(val): 

2361 assert_type(val, Awaitable[int]) 

2362 else: 

2363 assert_type(val, int) 

2364 

2365 ``TypeIs`` also works with type variables. For more information, see 

2366 PEP 742 (Narrowing types with TypeIs). 

2367 """ 

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

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

2370 

2371 

2372# 3.15+? 

2373if hasattr(typing, 'TypeForm'): 

2374 TypeForm = typing.TypeForm 

2375# <=3.14 

2376else: 

2377 class _TypeFormForm(_ExtensionsSpecialForm, _root=True): 

2378 # TypeForm(X) is equivalent to X but indicates to the type checker 

2379 # that the object is a TypeForm. 

2380 def __call__(self, obj, /): 

2381 return obj 

2382 

2383 @_TypeFormForm 

2384 def TypeForm(self, parameters): 

2385 """A special form representing the value that results from the evaluation 

2386 of a type expression. This value encodes the information supplied in the 

2387 type expression, and it represents the type described by that type expression. 

2388 

2389 When used in a type expression, TypeForm describes a set of type form objects. 

2390 It accepts a single type argument, which must be a valid type expression. 

2391 ``TypeForm[T]`` describes the set of all type form objects that represent 

2392 the type T or types that are assignable to T. 

2393 

2394 Usage: 

2395 

2396 def cast[T](typ: TypeForm[T], value: Any) -> T: ... 

2397 

2398 reveal_type(cast(int, "x")) # int 

2399 

2400 See PEP 747 for more information. 

2401 """ 

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

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

2404 

2405 

2406 

2407 

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

2409 LiteralString = typing.LiteralString 

2410else: 

2411 @_SpecialForm 

2412 def LiteralString(self, params): 

2413 """Represents an arbitrary literal string. 

2414 

2415 Example:: 

2416 

2417 from typing_extensions import LiteralString 

2418 

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

2420 ... 

2421 

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

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

2424 

2425 See PEP 675 for details. 

2426 

2427 """ 

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

2429 

2430 

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

2432 Self = typing.Self 

2433else: 

2434 @_SpecialForm 

2435 def Self(self, params): 

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

2437 

2438 Example:: 

2439 

2440 from typing import Self 

2441 

2442 class ReturnsSelf: 

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

2444 ... 

2445 return self 

2446 

2447 """ 

2448 

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

2450 

2451 

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

2453 Never = typing.Never 

2454else: 

2455 @_SpecialForm 

2456 def Never(self, params): 

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

2458 

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

2460 called, or a function that never returns:: 

2461 

2462 from typing_extensions import Never 

2463 

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

2465 pass 

2466 

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

2468 never_call_me(arg) # type checker error 

2469 match arg: 

2470 case int(): 

2471 print("It's an int") 

2472 case str(): 

2473 print("It's a str") 

2474 case _: 

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

2476 

2477 """ 

2478 

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

2480 

2481 

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

2483 Required = typing.Required 

2484 NotRequired = typing.NotRequired 

2485else: # <=3.10 

2486 @_ExtensionsSpecialForm 

2487 def Required(self, parameters): 

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

2489 as required. For example: 

2490 

2491 class Movie(TypedDict, total=False): 

2492 title: Required[str] 

2493 year: int 

2494 

2495 m = Movie( 

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

2497 year=1999, 

2498 ) 

2499 

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

2501 when instantiating a related TypedDict. 

2502 """ 

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

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

2505 

2506 @_ExtensionsSpecialForm 

2507 def NotRequired(self, parameters): 

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

2509 potentially missing. For example: 

2510 

2511 class Movie(TypedDict): 

2512 title: str 

2513 year: NotRequired[int] 

2514 

2515 m = Movie( 

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

2517 year=1999, 

2518 ) 

2519 """ 

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

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

2522 

2523 

2524if hasattr(typing, 'ReadOnly'): 

2525 ReadOnly = typing.ReadOnly 

2526else: # <=3.12 

2527 @_ExtensionsSpecialForm 

2528 def ReadOnly(self, parameters): 

2529 """A special typing construct to mark an item of a TypedDict as read-only. 

2530 

2531 For example: 

2532 

2533 class Movie(TypedDict): 

2534 title: ReadOnly[str] 

2535 year: int 

2536 

2537 def mutate_movie(m: Movie) -> None: 

2538 m["year"] = 1992 # allowed 

2539 m["title"] = "The Matrix" # typechecker error 

2540 

2541 There is no runtime checking for this property. 

2542 """ 

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

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

2545 

2546 

2547_UNPACK_DOC = """\ 

2548Type unpack operator. 

2549 

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

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

2552example: 

2553 

2554 # For some generic class `Foo`: 

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

2556 

2557 Ts = TypeVarTuple('Ts') 

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

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

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

2561 # `Generic[]`.) 

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

2563 Bar[int] # Valid 

2564 Bar[int, str] # Also valid 

2565 

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

2567 

2568 Foo[*tuple[int, str]] 

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

2570 

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

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

2573 

2574 class Movie(TypedDict): 

2575 name: str 

2576 year: int 

2577 

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

2579 # *year* of type `int`. 

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

2581 

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

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

2584 

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

2586""" 

2587 

2588 

2589# PEP 692 changed the repr of Unpack[] 

2590# Breakpoint: https://github.com/python/cpython/pull/104048 

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

2592 Unpack = typing.Unpack 

2593 

2594 def _is_unpack(obj): 

2595 return get_origin(obj) is Unpack 

2596 

2597else: # <=3.11 

2598 class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True): 

2599 def __init__(self, getitem): 

2600 super().__init__(getitem) 

2601 self.__doc__ = _UNPACK_DOC 

2602 

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

2604 if sys.version_info < (3, 11): 

2605 # needed for compatibility with Generic[Unpack[Ts]] 

2606 __class__ = typing.TypeVar 

2607 

2608 @property 

2609 def __typing_unpacked_tuple_args__(self): 

2610 assert self.__origin__ is Unpack 

2611 assert len(self.__args__) == 1 

2612 arg, = self.__args__ 

2613 if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)): 

2614 if arg.__origin__ is not tuple: 

2615 raise TypeError("Unpack[...] must be used with a tuple type") 

2616 return arg.__args__ 

2617 return None 

2618 

2619 @property 

2620 def __typing_is_unpacked_typevartuple__(self): 

2621 assert self.__origin__ is Unpack 

2622 assert len(self.__args__) == 1 

2623 return isinstance(self.__args__[0], TypeVarTuple) 

2624 

2625 def __getitem__(self, args): 

2626 if self.__typing_is_unpacked_typevartuple__: 

2627 return args 

2628 # Cannot use `super().__getitem__` here because of the `__class__` assignment 

2629 # in the class body on Python <=3.11 

2630 # (https://github.com/python/typing_extensions/issues/661) 

2631 return typing._GenericAlias.__getitem__(self, args) 

2632 

2633 @_UnpackSpecialForm 

2634 def Unpack(self, parameters): 

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

2636 return _UnpackAlias(self, (item,)) 

2637 

2638 def _is_unpack(obj): 

2639 return isinstance(obj, _UnpackAlias) 

2640 

2641 

2642def _unpack_args(*args): 

2643 newargs = [] 

2644 for arg in args: 

2645 subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) 

2646 if subargs is not None and (not (subargs and subargs[-1] is ...)): 

2647 newargs.extend(subargs) 

2648 else: 

2649 newargs.append(arg) 

2650 return newargs 

2651 

2652 

2653if _PEP_696_IMPLEMENTED: 

2654 from typing import TypeVarTuple 

2655 

2656elif hasattr(typing, "TypeVarTuple"): # 3.11+ 

2657 

2658 # Add default parameter - PEP 696 

2659 class TypeVarTuple(metaclass=_TypeVarLikeMeta): 

2660 """Type variable tuple.""" 

2661 

2662 _backported_typevarlike = typing.TypeVarTuple 

2663 

2664 def __new__(cls, name, *, default=NoDefault): 

2665 tvt = typing.TypeVarTuple(name) 

2666 _set_default(tvt, default) 

2667 _set_module(tvt) 

2668 

2669 def _typevartuple_prepare_subst(alias, args): 

2670 params = alias.__parameters__ 

2671 typevartuple_index = params.index(tvt) 

2672 for param in params[typevartuple_index + 1:]: 

2673 if isinstance(param, TypeVarTuple): 

2674 raise TypeError( 

2675 f"More than one TypeVarTuple parameter in {alias}" 

2676 ) 

2677 

2678 alen = len(args) 

2679 plen = len(params) 

2680 left = typevartuple_index 

2681 right = plen - typevartuple_index - 1 

2682 var_tuple_index = None 

2683 fillarg = None 

2684 for k, arg in enumerate(args): 

2685 if not isinstance(arg, type): 

2686 subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) 

2687 if subargs and len(subargs) == 2 and subargs[-1] is ...: 

2688 if var_tuple_index is not None: 

2689 raise TypeError( 

2690 "More than one unpacked " 

2691 "arbitrary-length tuple argument" 

2692 ) 

2693 var_tuple_index = k 

2694 fillarg = subargs[0] 

2695 if var_tuple_index is not None: 

2696 left = min(left, var_tuple_index) 

2697 right = min(right, alen - var_tuple_index - 1) 

2698 elif left + right > alen: 

2699 raise TypeError(f"Too few arguments for {alias};" 

2700 f" actual {alen}, expected at least {plen - 1}") 

2701 if left == alen - right and tvt.has_default(): 

2702 replacement = _unpack_args(tvt.__default__) 

2703 else: 

2704 replacement = args[left: alen - right] 

2705 

2706 return ( 

2707 *args[:left], 

2708 *([fillarg] * (typevartuple_index - left)), 

2709 replacement, 

2710 *([fillarg] * (plen - right - left - typevartuple_index - 1)), 

2711 *args[alen - right:], 

2712 ) 

2713 

2714 tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst 

2715 return tvt 

2716 

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

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

2719 

2720else: # <=3.10 

2721 class TypeVarTuple(_DefaultMixin): 

2722 """Type variable tuple. 

2723 

2724 Usage:: 

2725 

2726 Ts = TypeVarTuple('Ts') 

2727 

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

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

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

2731 

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

2733 Consider the following example:: 

2734 

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

2736 

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

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

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

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

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

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

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

2744 

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

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

2747 signatures and variable annotations:: 

2748 

2749 class Array(Generic[*Ts]): 

2750 

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

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

2753 

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

2755 return self._shape 

2756 

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

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

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

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

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

2762 

2763 """ 

2764 

2765 # Trick Generic __parameters__. 

2766 __class__ = typing.TypeVar 

2767 

2768 def __iter__(self): 

2769 yield self.__unpacked__ 

2770 

2771 def __init__(self, name, *, default=NoDefault): 

2772 self.__name__ = name 

2773 _DefaultMixin.__init__(self, default) 

2774 

2775 # for pickling: 

2776 def_mod = _caller() 

2777 if def_mod != 'typing_extensions': 

2778 self.__module__ = def_mod 

2779 

2780 self.__unpacked__ = Unpack[self] 

2781 

2782 def __repr__(self): 

2783 return self.__name__ 

2784 

2785 def __hash__(self): 

2786 return object.__hash__(self) 

2787 

2788 def __eq__(self, other): 

2789 return self is other 

2790 

2791 def __reduce__(self): 

2792 return self.__name__ 

2793 

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

2795 if '_root' not in kwds: 

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

2797 

2798 

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

2800 reveal_type = typing.reveal_type 

2801else: # <=3.10 

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

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

2804 

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

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

2807 

2808 x: int = 1 

2809 reveal_type(x) 

2810 

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

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

2813 

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

2815 argument and returns it unchanged. 

2816 

2817 """ 

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

2819 return obj 

2820 

2821 

2822if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+ 

2823 _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH 

2824else: # <=3.10 

2825 _ASSERT_NEVER_REPR_MAX_LENGTH = 100 

2826 

2827 

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

2829 assert_never = typing.assert_never 

2830else: # <=3.10 

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

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

2833 

2834 Example:: 

2835 

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

2837 match arg: 

2838 case int(): 

2839 print("It's an int") 

2840 case str(): 

2841 print("It's a str") 

2842 case _: 

2843 assert_never(arg) 

2844 

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

2846 reachable, it will emit an error. 

2847 

2848 At runtime, this throws an exception when called. 

2849 

2850 """ 

2851 value = repr(arg) 

2852 if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: 

2853 value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...' 

2854 raise AssertionError(f"Expected code to be unreachable, but got: {value}") 

2855 

2856 

2857# dataclass_transform exists in 3.11 but lacks the frozen_default parameter 

2858# Breakpoint: https://github.com/python/cpython/pull/99958 

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

2860 dataclass_transform = typing.dataclass_transform 

2861else: # <=3.11 

2862 def dataclass_transform( 

2863 *, 

2864 eq_default: bool = True, 

2865 order_default: bool = False, 

2866 kw_only_default: bool = False, 

2867 frozen_default: bool = False, 

2868 field_specifiers: typing.Tuple[ 

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

2870 ... 

2871 ] = (), 

2872 **kwargs: typing.Any, 

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

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

2875 dataclass-like behavior. 

2876 

2877 Example: 

2878 

2879 from typing_extensions import dataclass_transform 

2880 

2881 _T = TypeVar("_T") 

2882 

2883 # Used on a decorator function 

2884 @dataclass_transform() 

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

2886 ... 

2887 return cls 

2888 

2889 @create_model 

2890 class CustomerModel: 

2891 id: int 

2892 name: str 

2893 

2894 # Used on a base class 

2895 @dataclass_transform() 

2896 class ModelBase: ... 

2897 

2898 class CustomerModel(ModelBase): 

2899 id: int 

2900 name: str 

2901 

2902 # Used on a metaclass 

2903 @dataclass_transform() 

2904 class ModelMeta(type): ... 

2905 

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

2907 

2908 class CustomerModel(ModelBase): 

2909 id: int 

2910 name: str 

2911 

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

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

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

2915 method. 

2916 

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

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

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

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

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

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

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

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

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

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

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

2928 

2929 At runtime, this decorator records its arguments in the 

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

2931 

2932 See PEP 681 for details. 

2933 

2934 """ 

2935 def decorator(cls_or_fn): 

2936 cls_or_fn.__dataclass_transform__ = { 

2937 "eq_default": eq_default, 

2938 "order_default": order_default, 

2939 "kw_only_default": kw_only_default, 

2940 "frozen_default": frozen_default, 

2941 "field_specifiers": field_specifiers, 

2942 "kwargs": kwargs, 

2943 } 

2944 return cls_or_fn 

2945 return decorator 

2946 

2947 

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

2949 override = typing.override 

2950else: # <=3.11 

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

2952 

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

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

2955 

2956 Usage: 

2957 

2958 class Base: 

2959 def method(self) -> None: 

2960 pass 

2961 

2962 class Child(Base): 

2963 @override 

2964 def method(self) -> None: 

2965 super().method() 

2966 

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

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

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

2970 without an equivalent change to a child class. 

2971 

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

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

2974 to allow runtime introspection. 

2975 

2976 See PEP 698 for details. 

2977 

2978 """ 

2979 try: 

2980 arg.__override__ = True 

2981 except (AttributeError, TypeError): 

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

2983 # AttributeError happens if the object has __slots__ or a 

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

2985 pass 

2986 return arg 

2987 

2988 

2989# Python 3.13.8+ and 3.14.1+ contain a fix for the wrapped __init_subclass__ 

2990# Breakpoint: https://github.com/python/cpython/pull/138210 

2991if ((3, 13, 8) <= sys.version_info < (3, 14)) or sys.version_info >= (3, 14, 1): 

2992 deprecated = warnings.deprecated 

2993else: 

2994 _T = typing.TypeVar("_T") 

2995 

2996 class deprecated: 

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

2998 

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

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

3001 

3002 Usage: 

3003 

3004 @deprecated("Use B instead") 

3005 class A: 

3006 pass 

3007 

3008 @deprecated("Use g instead") 

3009 def f(): 

3010 pass 

3011 

3012 @overload 

3013 @deprecated("int support is deprecated") 

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

3015 @overload 

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

3017 

3018 The warning specified by *category* will be emitted at runtime 

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

3020 for classes, on instantiation and on creation of subclasses. 

3021 If the *category* is ``None``, no warning is emitted at runtime. 

3022 The *stacklevel* determines where the 

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

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

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

3026 Static type checker behavior is not affected by the *category* 

3027 and *stacklevel* arguments. 

3028 

3029 The deprecation message passed to the decorator is saved in the 

3030 ``__deprecated__`` attribute on the decorated object. 

3031 If applied to an overload, the decorator 

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

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

3034 

3035 See PEP 702 for details. 

3036 

3037 """ 

3038 def __init__( 

3039 self, 

3040 message: str, 

3041 /, 

3042 *, 

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

3044 stacklevel: int = 1, 

3045 ) -> None: 

3046 if not isinstance(message, str): 

3047 raise TypeError( 

3048 "Expected an object of type str for 'message', not " 

3049 f"{type(message).__name__!r}" 

3050 ) 

3051 self.message = message 

3052 self.category = category 

3053 self.stacklevel = stacklevel 

3054 

3055 def __call__(self, arg: _T, /) -> _T: 

3056 # Make sure the inner functions created below don't 

3057 # retain a reference to self. 

3058 msg = self.message 

3059 category = self.category 

3060 stacklevel = self.stacklevel 

3061 if category is None: 

3062 arg.__deprecated__ = msg 

3063 return arg 

3064 elif isinstance(arg, type): 

3065 import functools 

3066 from types import MethodType 

3067 

3068 original_new = arg.__new__ 

3069 

3070 @functools.wraps(original_new) 

3071 def __new__(cls, /, *args, **kwargs): 

3072 if cls is arg: 

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

3074 if original_new is not object.__new__: 

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

3076 # Mirrors a similar check in object.__new__. 

3077 elif cls.__init__ is object.__init__ and (args or kwargs): 

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

3079 else: 

3080 return original_new(cls) 

3081 

3082 arg.__new__ = staticmethod(__new__) 

3083 

3084 if "__init_subclass__" in arg.__dict__: 

3085 # __init_subclass__ is directly present on the decorated class. 

3086 # Synthesize a wrapper that calls this method directly. 

3087 original_init_subclass = arg.__init_subclass__ 

3088 # We need slightly different behavior if __init_subclass__ 

3089 # is a bound method (likely if it was implemented in Python). 

3090 # Otherwise, it likely means it's a builtin such as 

3091 # object's implementation of __init_subclass__. 

3092 if isinstance(original_init_subclass, MethodType): 

3093 original_init_subclass = original_init_subclass.__func__ 

3094 

3095 @functools.wraps(original_init_subclass) 

3096 def __init_subclass__(*args, **kwargs): 

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

3098 return original_init_subclass(*args, **kwargs) 

3099 else: 

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

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

3102 return super(arg, cls).__init_subclass__(*args, **kwargs) 

3103 

3104 arg.__init_subclass__ = classmethod(__init_subclass__) 

3105 

3106 arg.__deprecated__ = __new__.__deprecated__ = msg 

3107 __init_subclass__.__deprecated__ = msg 

3108 return arg 

3109 elif callable(arg): 

3110 import asyncio.coroutines 

3111 import functools 

3112 import inspect 

3113 

3114 @functools.wraps(arg) 

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

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

3117 return arg(*args, **kwargs) 

3118 

3119 if asyncio.coroutines.iscoroutinefunction(arg): 

3120 # Breakpoint: https://github.com/python/cpython/pull/99247 

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

3122 wrapper = inspect.markcoroutinefunction(wrapper) 

3123 else: 

3124 wrapper._is_coroutine = asyncio.coroutines._is_coroutine 

3125 

3126 arg.__deprecated__ = wrapper.__deprecated__ = msg 

3127 return wrapper 

3128 else: 

3129 raise TypeError( 

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

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

3132 ) 

3133 

3134# Breakpoint: https://github.com/python/cpython/pull/23702 

3135if sys.version_info < (3, 10): 

3136 def _is_param_expr(arg): 

3137 return arg is ... or isinstance( 

3138 arg, (tuple, list, ParamSpec, _ConcatenateGenericAlias) 

3139 ) 

3140else: 

3141 def _is_param_expr(arg): 

3142 return arg is ... or isinstance( 

3143 arg, 

3144 ( 

3145 tuple, 

3146 list, 

3147 ParamSpec, 

3148 _ConcatenateGenericAlias, 

3149 typing._ConcatenateGenericAlias, 

3150 ), 

3151 ) 

3152 

3153 

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

3155# Unpack/TypeVarTuple: 

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

3157# Generic[Unpack[Ts]] 

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

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

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

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

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

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

3164 

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

3166 """ 

3167 # If substituting a single ParamSpec with multiple arguments 

3168 # we do not check the count 

3169 if (inspect.isclass(cls) and issubclass(cls, typing.Generic) 

3170 and len(cls.__parameters__) == 1 

3171 and isinstance(cls.__parameters__[0], ParamSpec) 

3172 and parameters 

3173 and not _is_param_expr(parameters[0]) 

3174 ): 

3175 # Generic modifies parameters variable, but here we cannot do this 

3176 return 

3177 

3178 if not elen: 

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

3180 if elen is _marker: 

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

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

3183 elen = len(cls.__parameters__) 

3184 alen = len(parameters) 

3185 if alen != elen: 

3186 expect_val = elen 

3187 if hasattr(cls, "__parameters__"): 

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

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

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

3191 return 

3192 

3193 # deal with TypeVarLike defaults 

3194 # required TypeVarLikes cannot appear after a defaulted one. 

3195 if alen < elen: 

3196 # since we validate TypeVarLike default in _collect_type_vars 

3197 # or _collect_parameters we can safely check parameters[alen] 

3198 if ( 

3199 getattr(parameters[alen], '__default__', NoDefault) 

3200 is not NoDefault 

3201 ): 

3202 return 

3203 

3204 num_default_tv = sum(getattr(p, '__default__', NoDefault) 

3205 is not NoDefault for p in parameters) 

3206 

3207 elen -= num_default_tv 

3208 

3209 expect_val = f"at least {elen}" 

3210 

3211 # Breakpoint: https://github.com/python/cpython/pull/27515 

3212 things = "arguments" if sys.version_info >= (3, 10) else "parameters" 

3213 raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}" 

3214 f" for {cls}; actual {alen}, expected {expect_val}") 

3215else: 

3216 # Python 3.11+ 

3217 

3218 def _check_generic(cls, parameters, elen): 

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

3220 

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

3222 """ 

3223 if not elen: 

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

3225 alen = len(parameters) 

3226 if alen != elen: 

3227 expect_val = elen 

3228 if hasattr(cls, "__parameters__"): 

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

3230 

3231 # deal with TypeVarLike defaults 

3232 # required TypeVarLikes cannot appear after a defaulted one. 

3233 if alen < elen: 

3234 # since we validate TypeVarLike default in _collect_type_vars 

3235 # or _collect_parameters we can safely check parameters[alen] 

3236 if ( 

3237 getattr(parameters[alen], '__default__', NoDefault) 

3238 is not NoDefault 

3239 ): 

3240 return 

3241 

3242 num_default_tv = sum(getattr(p, '__default__', NoDefault) 

3243 is not NoDefault for p in parameters) 

3244 

3245 elen -= num_default_tv 

3246 

3247 expect_val = f"at least {elen}" 

3248 

3249 raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" 

3250 f" for {cls}; actual {alen}, expected {expect_val}") 

3251 

3252if not _PEP_696_IMPLEMENTED: 

3253 typing._check_generic = _check_generic 

3254 

3255 

3256def _has_generic_or_protocol_as_origin() -> bool: 

3257 try: 

3258 frame = sys._getframe(2) 

3259 # - Catch AttributeError: not all Python implementations have sys._getframe() 

3260 # - Catch ValueError: maybe we're called from an unexpected module 

3261 # and the call stack isn't deep enough 

3262 except (AttributeError, ValueError): 

3263 return False # err on the side of leniency 

3264 else: 

3265 # If we somehow get invoked from outside typing.py, 

3266 # also err on the side of leniency 

3267 if frame.f_globals.get("__name__") != "typing": 

3268 return False 

3269 origin = frame.f_locals.get("origin") 

3270 # Cannot use "in" because origin may be an object with a buggy __eq__ that 

3271 # throws an error. 

3272 return origin is typing.Generic or origin is Protocol or origin is typing.Protocol 

3273 

3274 

3275_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)} 

3276 

3277 

3278def _is_unpacked_typevartuple(x) -> bool: 

3279 if get_origin(x) is not Unpack: 

3280 return False 

3281 args = get_args(x) 

3282 return ( 

3283 bool(args) 

3284 and len(args) == 1 

3285 and type(args[0]) in _TYPEVARTUPLE_TYPES 

3286 ) 

3287 

3288 

3289# Python 3.11+ _collect_type_vars was renamed to _collect_parameters 

3290if hasattr(typing, '_collect_type_vars'): 

3291 def _collect_type_vars(types, typevar_types=None): 

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

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

3294 

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

3296 """ 

3297 if typevar_types is None: 

3298 typevar_types = typing.TypeVar 

3299 tvars = [] 

3300 

3301 # A required TypeVarLike cannot appear after a TypeVarLike with a default 

3302 # if it was a direct call to `Generic[]` or `Protocol[]` 

3303 enforce_default_ordering = _has_generic_or_protocol_as_origin() 

3304 default_encountered = False 

3305 

3306 # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple 

3307 type_var_tuple_encountered = False 

3308 

3309 for t in types: 

3310 if _is_unpacked_typevartuple(t): 

3311 type_var_tuple_encountered = True 

3312 elif ( 

3313 isinstance(t, typevar_types) and not isinstance(t, _UnpackAlias) 

3314 and t not in tvars 

3315 ): 

3316 if enforce_default_ordering: 

3317 has_default = getattr(t, '__default__', NoDefault) is not NoDefault 

3318 if has_default: 

3319 if type_var_tuple_encountered: 

3320 raise TypeError('Type parameter with a default' 

3321 ' follows TypeVarTuple') 

3322 default_encountered = True 

3323 elif default_encountered: 

3324 raise TypeError(f'Type parameter {t!r} without a default' 

3325 ' follows type parameter with a default') 

3326 

3327 tvars.append(t) 

3328 if _should_collect_from_parameters(t): 

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

3330 elif isinstance(t, tuple): 

3331 # Collect nested type_vars 

3332 # tuple wrapped by _prepare_paramspec_params(cls, params) 

3333 for x in t: 

3334 for collected in _collect_type_vars([x]): 

3335 if collected not in tvars: 

3336 tvars.append(collected) 

3337 return tuple(tvars) 

3338 

3339 typing._collect_type_vars = _collect_type_vars 

3340else: 

3341 def _collect_parameters(args): 

3342 """Collect all type variables and parameter specifications in args 

3343 in order of first appearance (lexicographic order). 

3344 

3345 For example:: 

3346 

3347 assert _collect_parameters((T, Callable[P, T])) == (T, P) 

3348 """ 

3349 parameters = [] 

3350 

3351 # A required TypeVarLike cannot appear after a TypeVarLike with default 

3352 # if it was a direct call to `Generic[]` or `Protocol[]` 

3353 enforce_default_ordering = _has_generic_or_protocol_as_origin() 

3354 default_encountered = False 

3355 

3356 # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple 

3357 type_var_tuple_encountered = False 

3358 

3359 for t in args: 

3360 if isinstance(t, type): 

3361 # We don't want __parameters__ descriptor of a bare Python class. 

3362 pass 

3363 elif isinstance(t, tuple): 

3364 # `t` might be a tuple, when `ParamSpec` is substituted with 

3365 # `[T, int]`, or `[int, *Ts]`, etc. 

3366 for x in t: 

3367 for collected in _collect_parameters([x]): 

3368 if collected not in parameters: 

3369 parameters.append(collected) 

3370 elif hasattr(t, '__typing_subst__'): 

3371 if t not in parameters: 

3372 if enforce_default_ordering: 

3373 has_default = ( 

3374 getattr(t, '__default__', NoDefault) is not NoDefault 

3375 ) 

3376 

3377 if type_var_tuple_encountered and has_default: 

3378 raise TypeError('Type parameter with a default' 

3379 ' follows TypeVarTuple') 

3380 

3381 if has_default: 

3382 default_encountered = True 

3383 elif default_encountered: 

3384 raise TypeError(f'Type parameter {t!r} without a default' 

3385 ' follows type parameter with a default') 

3386 

3387 parameters.append(t) 

3388 else: 

3389 if _is_unpacked_typevartuple(t): 

3390 type_var_tuple_encountered = True 

3391 for x in getattr(t, '__parameters__', ()): 

3392 if x not in parameters: 

3393 parameters.append(x) 

3394 

3395 return tuple(parameters) 

3396 

3397 if not _PEP_696_IMPLEMENTED: 

3398 typing._collect_parameters = _collect_parameters 

3399 

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

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

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

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

3404# On 3.13, we deprecated kwargs-based NamedTuples 

3405# Breakpoint: https://github.com/python/cpython/pull/105609 

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

3407 NamedTuple = typing.NamedTuple 

3408else: 

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

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

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

3412 for n, t in types} 

3413 nm_tpl = collections.namedtuple(name, fields, 

3414 defaults=defaults, module=module) 

3415 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations 

3416 return nm_tpl 

3417 

3418 _prohibited_namedtuple_fields = typing._prohibited 

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

3420 

3421 class _NamedTupleMeta(type): 

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

3423 assert _NamedTuple in bases 

3424 for base in bases: 

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

3426 raise TypeError( 

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

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

3429 if "__annotations__" in ns: 

3430 types = ns["__annotations__"] 

3431 elif "__annotate__" in ns: 

3432 # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated 

3433 types = ns["__annotate__"](1) 

3434 else: 

3435 types = {} 

3436 default_names = [] 

3437 for field_name in types: 

3438 if field_name in ns: 

3439 default_names.append(field_name) 

3440 elif default_names: 

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

3442 f"cannot follow default field" 

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

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

3445 nm_tpl = _make_nmtuple( 

3446 typename, types.items(), 

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

3448 module=ns['__module__'] 

3449 ) 

3450 nm_tpl.__bases__ = bases 

3451 if typing.Generic in bases: 

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

3453 nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem) 

3454 else: 

3455 class_getitem = typing.Generic.__class_getitem__.__func__ 

3456 nm_tpl.__class_getitem__ = classmethod(class_getitem) 

3457 # update from user namespace without overriding special namedtuple attributes 

3458 for key, val in ns.items(): 

3459 if key in _prohibited_namedtuple_fields: 

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

3461 elif key not in _special_namedtuple_fields: 

3462 if key not in nm_tpl._fields: 

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

3464 try: 

3465 set_name = type(val).__set_name__ 

3466 except AttributeError: 

3467 pass 

3468 else: 

3469 try: 

3470 set_name(val, nm_tpl, key) 

3471 except BaseException as e: 

3472 msg = ( 

3473 f"Error calling __set_name__ on {type(val).__name__!r} " 

3474 f"instance {key!r} in {typename!r}" 

3475 ) 

3476 # BaseException.add_note() existed on py311, 

3477 # but the __set_name__ machinery didn't start 

3478 # using add_note() until py312. 

3479 # Making sure exceptions are raised in the same way 

3480 # as in "normal" classes seems most important here. 

3481 # Breakpoint: https://github.com/python/cpython/pull/95915 

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

3483 e.add_note(msg) 

3484 raise 

3485 else: 

3486 raise RuntimeError(msg) from e 

3487 

3488 if typing.Generic in bases: 

3489 nm_tpl.__init_subclass__() 

3490 return nm_tpl 

3491 

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

3493 

3494 def _namedtuple_mro_entries(bases): 

3495 assert NamedTuple in bases 

3496 return (_NamedTuple,) 

3497 

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

3499 """Typed version of namedtuple. 

3500 

3501 Usage:: 

3502 

3503 class Employee(NamedTuple): 

3504 name: str 

3505 id: int 

3506 

3507 This is equivalent to:: 

3508 

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

3510 

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

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

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

3514 An alternative equivalent functional syntax is also accepted:: 

3515 

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

3517 """ 

3518 if fields is _marker: 

3519 if kwargs: 

3520 deprecated_thing = "Creating NamedTuple classes using keyword arguments" 

3521 deprecation_msg = ( 

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

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

3524 ) 

3525 else: 

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

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

3528 deprecation_msg = ( 

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

3530 "To create a NamedTuple class with 0 fields " 

3531 "using the functional syntax, " 

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

3533 ) + example + "." 

3534 elif fields is None: 

3535 if kwargs: 

3536 raise TypeError( 

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

3538 "and also specify fields using keyword arguments" 

3539 ) 

3540 else: 

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

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

3543 deprecation_msg = ( 

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

3545 "To create a NamedTuple class with 0 fields " 

3546 "using the functional syntax, " 

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

3548 ) + example + "." 

3549 elif kwargs: 

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

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

3552 if fields is _marker or fields is None: 

3553 warnings.warn( 

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

3555 DeprecationWarning, 

3556 stacklevel=2, 

3557 ) 

3558 fields = kwargs.items() 

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

3560 nt.__orig_bases__ = (NamedTuple,) 

3561 return nt 

3562 

3563 NamedTuple.__mro_entries__ = _namedtuple_mro_entries 

3564 

3565 

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

3567 Buffer = collections.abc.Buffer 

3568else: 

3569 class Buffer(abc.ABC): # noqa: B024 

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

3571 

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

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

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

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

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

3577 to the buffer protocol from Python code, and the 

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

3579 implements the buffer protocol. 

3580 

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

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

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

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

3585 classes. It is useful primarily for static checks. 

3586 

3587 """ 

3588 

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

3590 Buffer.register(memoryview) 

3591 Buffer.register(bytearray) 

3592 Buffer.register(bytes) 

3593 

3594 

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

3596if hasattr(_types, "get_original_bases"): 

3597 get_original_bases = _types.get_original_bases 

3598else: 

3599 def get_original_bases(cls, /): 

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

3601 

3602 Examples:: 

3603 

3604 from typing import TypeVar, Generic 

3605 from typing_extensions import NamedTuple, TypedDict 

3606 

3607 T = TypeVar("T") 

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

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

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

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

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

3613 

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

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

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

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

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

3619 """ 

3620 try: 

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

3622 except AttributeError: 

3623 raise TypeError( 

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

3625 ) from None 

3626 

3627 

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

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

3630# Breakpoint: https://github.com/python/cpython/pull/30268 

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

3632 NewType = typing.NewType 

3633else: 

3634 class NewType: 

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

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

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

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

3639 UserId = NewType('UserId', int) 

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

3641 ... 

3642 UserId('user') # Fails type check 

3643 name_by_id(42) # Fails type check 

3644 name_by_id(UserId(42)) # OK 

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

3646 """ 

3647 

3648 def __call__(self, obj, /): 

3649 return obj 

3650 

3651 def __init__(self, name, tp): 

3652 self.__qualname__ = name 

3653 if '.' in name: 

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

3655 self.__name__ = name 

3656 self.__supertype__ = tp 

3657 def_mod = _caller() 

3658 if def_mod != 'typing_extensions': 

3659 self.__module__ = def_mod 

3660 

3661 def __mro_entries__(self, bases): 

3662 # We defined __mro_entries__ to get a better error message 

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

3664 supercls_name = self.__name__ 

3665 

3666 class Dummy: 

3667 def __init_subclass__(cls): 

3668 subcls_name = cls.__name__ 

3669 raise TypeError( 

3670 f"Cannot subclass an instance of NewType. " 

3671 f"Perhaps you were looking for: " 

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

3673 ) 

3674 

3675 return (Dummy,) 

3676 

3677 def __repr__(self): 

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

3679 

3680 def __reduce__(self): 

3681 return self.__qualname__ 

3682 

3683 # Breakpoint: https://github.com/python/cpython/pull/21515 

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

3685 # PEP 604 methods 

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

3687 

3688 def __or__(self, other): 

3689 return typing.Union[self, other] 

3690 

3691 def __ror__(self, other): 

3692 return typing.Union[other, self] 

3693 

3694 

3695# Breakpoint: https://github.com/python/cpython/pull/149172 

3696if sys.version_info >= (3, 15): 

3697 TypeAliasType = typing.TypeAliasType 

3698# <=3.14 

3699else: 

3700 # Breakpoint: https://github.com/python/cpython/pull/103764 

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

3702 # 3.12-3.14 

3703 def _is_unionable(obj): 

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

3705 return obj is None or isinstance(obj, ( 

3706 type, 

3707 _types.GenericAlias, 

3708 _types.UnionType, 

3709 typing.TypeAliasType, 

3710 TypeAliasType, 

3711 )) 

3712 else: 

3713 # <=3.11 

3714 def _is_unionable(obj): 

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

3716 return obj is None or isinstance(obj, ( 

3717 type, 

3718 _types.GenericAlias, 

3719 _types.UnionType, 

3720 TypeAliasType, 

3721 )) 

3722 

3723 if sys.version_info < (3, 10): 

3724 # Copied and pasted from https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Objects/genericaliasobject.c#L568-L582, 

3725 # so that we emulate the behaviour of `types.GenericAlias` 

3726 # on the latest versions of CPython 

3727 _ATTRIBUTE_DELEGATION_EXCLUSIONS = frozenset({ 

3728 "__class__", 

3729 "__bases__", 

3730 "__origin__", 

3731 "__args__", 

3732 "__unpacked__", 

3733 "__parameters__", 

3734 "__typing_unpacked_tuple_args__", 

3735 "__mro_entries__", 

3736 "__reduce_ex__", 

3737 "__reduce__", 

3738 "__copy__", 

3739 "__deepcopy__", 

3740 }) 

3741 

3742 class _TypeAliasGenericAlias(typing._GenericAlias, _root=True): 

3743 def __getattr__(self, attr): 

3744 if attr in _ATTRIBUTE_DELEGATION_EXCLUSIONS: 

3745 return object.__getattr__(self, attr) 

3746 return getattr(self.__origin__, attr) 

3747 

3748 

3749 class TypeAliasType: 

3750 """Create named, parameterized type aliases. 

3751 

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

3753 

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

3755 

3756 is equivalent to: 

3757 

3758 T = TypeVar("T") 

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

3760 

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

3762 

3763 The type_params argument should contain all the type parameters used 

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

3765 argument is omitted. 

3766 

3767 Static type checkers should only support type aliases declared using 

3768 TypeAliasType that follow these rules: 

3769 

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

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

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

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

3774 

3775 """ 

3776 

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

3778 if not isinstance(name, str): 

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

3780 if not isinstance(type_params, tuple): 

3781 raise TypeError("type_params must be a tuple") 

3782 self.__value__ = value 

3783 self.__type_params__ = type_params 

3784 

3785 default_value_encountered = False 

3786 parameters = [] 

3787 for type_param in type_params: 

3788 if ( 

3789 not isinstance(type_param, (TypeVar, TypeVarTuple, ParamSpec)) 

3790 # <=3.11 

3791 # Unpack Backport passes isinstance(type_param, TypeVar) 

3792 or _is_unpack(type_param) 

3793 ): 

3794 raise TypeError(f"Expected a type param, got {type_param!r}") 

3795 has_default = ( 

3796 getattr(type_param, '__default__', NoDefault) is not NoDefault 

3797 ) 

3798 if default_value_encountered and not has_default: 

3799 raise TypeError(f"non-default type parameter '{type_param!r}'" 

3800 " follows default type parameter") 

3801 if has_default: 

3802 default_value_encountered = True 

3803 if isinstance(type_param, TypeVarTuple): 

3804 parameters.extend(type_param) 

3805 else: 

3806 parameters.append(type_param) 

3807 self.__parameters__ = tuple(parameters) 

3808 def_mod = _caller() 

3809 if def_mod != 'typing_extensions': 

3810 self.__module__ = def_mod 

3811 # Setting this attribute closes the TypeAliasType from further modification 

3812 self.__name__ = name 

3813 

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

3815 if hasattr(self, "__name__") and name != "__module__": 

3816 self._raise_attribute_error(name) 

3817 super().__setattr__(name, value) 

3818 

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

3820 self._raise_attribute_error(name) 

3821 

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

3823 # Match the Python 3.12 error messages exactly 

3824 if name == "__name__": 

3825 raise AttributeError("readonly attribute") 

3826 elif name in {"__value__", "__type_params__", "__parameters__"}: 

3827 raise AttributeError( 

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

3829 "is not writable" 

3830 ) 

3831 else: 

3832 raise AttributeError( 

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

3834 ) 

3835 

3836 def __repr__(self) -> str: 

3837 return self.__name__ 

3838 

3839 if sys.version_info < (3, 11): 

3840 def _check_single_param(self, param, recursion=0): 

3841 # Allow [], [int], [int, str], [int, ...], [int, T] 

3842 if param is ...: 

3843 return ... 

3844 if param is None: 

3845 return None 

3846 # Note in <= 3.9 _ConcatenateGenericAlias inherits from list 

3847 if isinstance(param, list) and recursion == 0: 

3848 return [self._check_single_param(arg, recursion+1) 

3849 for arg in param] 

3850 return typing._type_check( 

3851 param, f'Subscripting {self.__name__} requires a type.' 

3852 ) 

3853 

3854 def _check_parameters(self, parameters): 

3855 if sys.version_info < (3, 11): 

3856 return tuple( 

3857 self._check_single_param(item) 

3858 for item in parameters 

3859 ) 

3860 return tuple(typing._type_check( 

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

3862 ) 

3863 for item in parameters 

3864 ) 

3865 

3866 def __getitem__(self, parameters): 

3867 if not self.__type_params__: 

3868 raise TypeError("Only generic type aliases are subscriptable") 

3869 if not isinstance(parameters, tuple): 

3870 parameters = (parameters,) 

3871 # Using 3.9 here will create problems with Concatenate 

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

3873 return _types.GenericAlias(self, parameters) 

3874 type_vars = _collect_type_vars(parameters) 

3875 parameters = self._check_parameters(parameters) 

3876 alias = _TypeAliasGenericAlias(self, parameters) 

3877 # alias.__parameters__ is not complete if Concatenate is present 

3878 # as it is converted to a list from which no parameters are extracted. 

3879 if alias.__parameters__ != type_vars: 

3880 alias.__parameters__ = type_vars 

3881 return alias 

3882 

3883 def __reduce__(self): 

3884 return self.__name__ 

3885 

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

3887 raise TypeError( 

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

3889 ) 

3890 

3891 # The presence of this method convinces typing._type_check 

3892 # that TypeAliasTypes are types. 

3893 def __call__(self): 

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

3895 

3896 # Breakpoint: https://github.com/python/cpython/pull/21515 

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

3898 def __or__(self, right): 

3899 # For forward compatibility with 3.12, reject Unions 

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

3901 if not _is_unionable(right): 

3902 return NotImplemented 

3903 return typing.Union[self, right] 

3904 

3905 def __ror__(self, left): 

3906 if not _is_unionable(left): 

3907 return NotImplemented 

3908 return typing.Union[left, self] 

3909 

3910 

3911if hasattr(typing, "is_protocol"): 

3912 is_protocol = typing.is_protocol 

3913 get_protocol_members = typing.get_protocol_members 

3914else: 

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

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

3917 

3918 Example:: 

3919 

3920 >>> from typing_extensions import Protocol, is_protocol 

3921 >>> class P(Protocol): 

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

3923 ... b: int 

3924 >>> is_protocol(P) 

3925 True 

3926 >>> is_protocol(int) 

3927 False 

3928 """ 

3929 return ( 

3930 isinstance(tp, type) 

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

3932 and tp is not Protocol 

3933 and tp is not typing.Protocol 

3934 ) 

3935 

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

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

3938 

3939 Example:: 

3940 

3941 >>> from typing_extensions import Protocol, get_protocol_members 

3942 >>> class P(Protocol): 

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

3944 ... b: int 

3945 >>> get_protocol_members(P) == frozenset({'a', 'b'}) 

3946 True 

3947 

3948 Raise a TypeError for arguments that are not Protocols. 

3949 """ 

3950 if not is_protocol(tp): 

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

3952 if hasattr(tp, '__protocol_attrs__'): 

3953 return frozenset(tp.__protocol_attrs__) 

3954 return frozenset(_get_protocol_attrs(tp)) 

3955 

3956 

3957if hasattr(typing, "Doc"): 

3958 Doc = typing.Doc 

3959else: 

3960 class Doc: 

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

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

3963 and variables. 

3964 

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

3966 like editors and documentation generators to use it. 

3967 

3968 This complements docstrings. 

3969 

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

3971 

3972 Example:: 

3973 

3974 >>> from typing_extensions import Annotated, Doc 

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

3976 """ 

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

3978 self.documentation = documentation 

3979 

3980 def __repr__(self) -> str: 

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

3982 

3983 def __hash__(self) -> int: 

3984 return hash(self.documentation) 

3985 

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

3987 if not isinstance(other, Doc): 

3988 return NotImplemented 

3989 return self.documentation == other.documentation 

3990 

3991 

3992_CapsuleType = getattr(_types, "CapsuleType", None) 

3993 

3994if _CapsuleType is None: 

3995 try: 

3996 import _socket 

3997 except ImportError: 

3998 pass 

3999 else: 

4000 _CAPI = getattr(_socket, "CAPI", None) 

4001 if _CAPI is not None: 

4002 _CapsuleType = type(_CAPI) 

4003 

4004if _CapsuleType is not None: 

4005 CapsuleType = _CapsuleType 

4006 __all__.append("CapsuleType") 

4007 

4008 

4009if sys.version_info >= (3, 14): 

4010 from annotationlib import Format, get_annotations 

4011else: 

4012 # Available since Python 3.14.0a3 

4013 # PR: https://github.com/python/cpython/pull/124415 

4014 class Format(enum.IntEnum): 

4015 VALUE = 1 

4016 VALUE_WITH_FAKE_GLOBALS = 2 

4017 FORWARDREF = 3 

4018 STRING = 4 

4019 

4020 # Available since Python 3.14.0a1 

4021 # PR: https://github.com/python/cpython/pull/119891 

4022 def get_annotations(obj, *, globals=None, locals=None, eval_str=False, 

4023 format=Format.VALUE): 

4024 """Compute the annotations dict for an object. 

4025 

4026 obj may be a callable, class, or module. 

4027 Passing in an object of any other type raises TypeError. 

4028 

4029 Returns a dict. get_annotations() returns a new dict every time 

4030 it's called; calling it twice on the same object will return two 

4031 different but equivalent dicts. 

4032 

4033 This is a backport of `inspect.get_annotations`, which has been 

4034 in the standard library since Python 3.10. See the standard library 

4035 documentation for more: 

4036 

4037 https://docs.python.org/3/library/inspect.html#inspect.get_annotations 

4038 

4039 This backport adds the *format* argument introduced by PEP 649. The 

4040 three formats supported are: 

4041 * VALUE: the annotations are returned as-is. This is the default and 

4042 it is compatible with the behavior on previous Python versions. 

4043 * FORWARDREF: return annotations as-is if possible, but replace any 

4044 undefined names with ForwardRef objects. The implementation proposed by 

4045 PEP 649 relies on language changes that cannot be backported; the 

4046 typing-extensions implementation simply returns the same result as VALUE. 

4047 * STRING: return annotations as strings, in a format close to the original 

4048 source. Again, this behavior cannot be replicated directly in a backport. 

4049 As an approximation, typing-extensions retrieves the annotations under 

4050 VALUE semantics and then stringifies them. 

4051 

4052 The purpose of this backport is to allow users who would like to use 

4053 FORWARDREF or STRING semantics once PEP 649 is implemented, but who also 

4054 want to support earlier Python versions, to simply write: 

4055 

4056 typing_extensions.get_annotations(obj, format=Format.FORWARDREF) 

4057 

4058 """ 

4059 format = Format(format) 

4060 if format is Format.VALUE_WITH_FAKE_GLOBALS: 

4061 raise ValueError( 

4062 "The VALUE_WITH_FAKE_GLOBALS format is for internal use only" 

4063 ) 

4064 

4065 if eval_str and format is not Format.VALUE: 

4066 raise ValueError("eval_str=True is only supported with format=Format.VALUE") 

4067 

4068 if isinstance(obj, type): 

4069 # class 

4070 obj_dict = getattr(obj, '__dict__', None) 

4071 if obj_dict and hasattr(obj_dict, 'get'): 

4072 ann = obj_dict.get('__annotations__', None) 

4073 if isinstance(ann, _types.GetSetDescriptorType): 

4074 ann = None 

4075 else: 

4076 ann = None 

4077 

4078 obj_globals = None 

4079 module_name = getattr(obj, '__module__', None) 

4080 if module_name: 

4081 module = sys.modules.get(module_name, None) 

4082 if module: 

4083 obj_globals = getattr(module, '__dict__', None) 

4084 obj_locals = dict(vars(obj)) 

4085 unwrap = obj 

4086 elif isinstance(obj, _types.ModuleType): 

4087 # module 

4088 ann = getattr(obj, '__annotations__', None) 

4089 obj_globals = obj.__dict__ 

4090 obj_locals = None 

4091 unwrap = None 

4092 elif callable(obj): 

4093 # this includes types.Function, types.BuiltinFunctionType, 

4094 # types.BuiltinMethodType, functools.partial, functools.singledispatch, 

4095 # "class funclike" from Lib/test/test_inspect... on and on it goes. 

4096 ann = getattr(obj, '__annotations__', None) 

4097 obj_globals = getattr(obj, '__globals__', None) 

4098 obj_locals = None 

4099 unwrap = obj 

4100 elif hasattr(obj, '__annotations__'): 

4101 ann = obj.__annotations__ 

4102 obj_globals = obj_locals = unwrap = None 

4103 else: 

4104 raise TypeError(f"{obj!r} is not a module, class, or callable.") 

4105 

4106 if ann is None: 

4107 return {} 

4108 

4109 if not isinstance(ann, dict): 

4110 raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None") 

4111 

4112 if not ann: 

4113 return {} 

4114 

4115 if not eval_str: 

4116 if format is Format.STRING: 

4117 return { 

4118 key: value if isinstance(value, str) else typing._type_repr(value) 

4119 for key, value in ann.items() 

4120 } 

4121 return dict(ann) 

4122 

4123 if unwrap is not None: 

4124 while True: 

4125 if hasattr(unwrap, '__wrapped__'): 

4126 unwrap = unwrap.__wrapped__ 

4127 continue 

4128 if isinstance(unwrap, functools.partial): 

4129 unwrap = unwrap.func 

4130 continue 

4131 break 

4132 if hasattr(unwrap, "__globals__"): 

4133 obj_globals = unwrap.__globals__ 

4134 

4135 if globals is None: 

4136 globals = obj_globals 

4137 if locals is None: 

4138 locals = obj_locals or {} 

4139 

4140 # "Inject" type parameters into the local namespace 

4141 # (unless they are shadowed by assignments *in* the local namespace), 

4142 # as a way of emulating annotation scopes when calling `eval()` 

4143 if type_params := getattr(obj, "__type_params__", ()): 

4144 locals = {param.__name__: param for param in type_params} | locals 

4145 

4146 return_value = {key: 

4147 value if not isinstance(value, str) else eval(value, globals, locals) 

4148 for key, value in ann.items() } 

4149 return return_value 

4150 

4151 

4152if hasattr(typing, "evaluate_forward_ref"): 

4153 evaluate_forward_ref = typing.evaluate_forward_ref 

4154else: 

4155 # Implements annotationlib.ForwardRef.evaluate 

4156 def _eval_with_owner( 

4157 forward_ref, *, owner=None, globals=None, locals=None, type_params=None 

4158 ): 

4159 if forward_ref.__forward_evaluated__: 

4160 return forward_ref.__forward_value__ 

4161 if getattr(forward_ref, "__cell__", None) is not None: 

4162 try: 

4163 value = forward_ref.__cell__.cell_contents 

4164 except ValueError: 

4165 pass 

4166 else: 

4167 forward_ref.__forward_evaluated__ = True 

4168 forward_ref.__forward_value__ = value 

4169 return value 

4170 if owner is None: 

4171 owner = getattr(forward_ref, "__owner__", None) 

4172 

4173 if ( 

4174 globals is None 

4175 and getattr(forward_ref, "__forward_module__", None) is not None 

4176 ): 

4177 globals = getattr( 

4178 sys.modules.get(forward_ref.__forward_module__, None), "__dict__", None 

4179 ) 

4180 if globals is None: 

4181 globals = getattr(forward_ref, "__globals__", None) 

4182 if globals is None: 

4183 if isinstance(owner, type): 

4184 module_name = getattr(owner, "__module__", None) 

4185 if module_name: 

4186 module = sys.modules.get(module_name, None) 

4187 if module: 

4188 globals = getattr(module, "__dict__", None) 

4189 elif isinstance(owner, _types.ModuleType): 

4190 globals = getattr(owner, "__dict__", None) 

4191 elif callable(owner): 

4192 globals = getattr(owner, "__globals__", None) 

4193 

4194 # If we pass None to eval() below, the globals of this module are used. 

4195 if globals is None: 

4196 globals = {} 

4197 

4198 if locals is None: 

4199 locals = {} 

4200 if isinstance(owner, type): 

4201 locals.update(vars(owner)) 

4202 

4203 if type_params is None and owner is not None: 

4204 # "Inject" type parameters into the local namespace 

4205 # (unless they are shadowed by assignments *in* the local namespace), 

4206 # as a way of emulating annotation scopes when calling `eval()` 

4207 type_params = getattr(owner, "__type_params__", None) 

4208 

4209 # Type parameters exist in their own scope, which is logically 

4210 # between the locals and the globals. We simulate this by adding 

4211 # them to the globals. 

4212 if type_params is not None: 

4213 globals = dict(globals) 

4214 for param in type_params: 

4215 globals[param.__name__] = param 

4216 

4217 arg = forward_ref.__forward_arg__ 

4218 if arg.isidentifier() and not keyword.iskeyword(arg): 

4219 if arg in locals: 

4220 value = locals[arg] 

4221 elif arg in globals: 

4222 value = globals[arg] 

4223 elif hasattr(builtins, arg): 

4224 return getattr(builtins, arg) 

4225 else: 

4226 raise NameError(arg) 

4227 else: 

4228 code = forward_ref.__forward_code__ 

4229 value = eval(code, globals, locals) 

4230 forward_ref.__forward_evaluated__ = True 

4231 forward_ref.__forward_value__ = value 

4232 return value 

4233 

4234 def evaluate_forward_ref( 

4235 forward_ref, 

4236 *, 

4237 owner=None, 

4238 globals=None, 

4239 locals=None, 

4240 type_params=None, 

4241 format=None, 

4242 _recursive_guard=frozenset(), 

4243 ): 

4244 """Evaluate a forward reference as a type hint. 

4245 

4246 This is similar to calling the ForwardRef.evaluate() method, 

4247 but unlike that method, evaluate_forward_ref() also: 

4248 

4249 * Recursively evaluates forward references nested within the type hint. 

4250 * Rejects certain objects that are not valid type hints. 

4251 * Replaces type hints that evaluate to None with types.NoneType. 

4252 * Supports the *FORWARDREF* and *STRING* formats. 

4253 

4254 *forward_ref* must be an instance of ForwardRef. *owner*, if given, 

4255 should be the object that holds the annotations that the forward reference 

4256 derived from, such as a module, class object, or function. It is used to 

4257 infer the namespaces to use for looking up names. *globals* and *locals* 

4258 can also be explicitly given to provide the global and local namespaces. 

4259 *type_params* is a tuple of type parameters that are in scope when 

4260 evaluating the forward reference. This parameter must be provided (though 

4261 it may be an empty tuple) if *owner* is not given and the forward reference 

4262 does not already have an owner set. *format* specifies the format of the 

4263 annotation and is a member of the annotationlib.Format enum. 

4264 

4265 """ 

4266 if format == Format.STRING: 

4267 return forward_ref.__forward_arg__ 

4268 if forward_ref.__forward_arg__ in _recursive_guard: 

4269 return forward_ref 

4270 

4271 # Evaluate the forward reference 

4272 try: 

4273 value = _eval_with_owner( 

4274 forward_ref, 

4275 owner=owner, 

4276 globals=globals, 

4277 locals=locals, 

4278 type_params=type_params, 

4279 ) 

4280 except NameError: 

4281 if format == Format.FORWARDREF: 

4282 return forward_ref 

4283 else: 

4284 raise 

4285 

4286 if isinstance(value, str): 

4287 value = ForwardRef(value) 

4288 

4289 # Recursively evaluate the type 

4290 if isinstance(value, ForwardRef): 

4291 if getattr(value, "__forward_module__", True) is not None: 

4292 globals = None 

4293 return evaluate_forward_ref( 

4294 value, 

4295 globals=globals, 

4296 locals=locals, 

4297 type_params=type_params, owner=owner, 

4298 _recursive_guard=_recursive_guard, format=format 

4299 ) 

4300 if sys.version_info < (3, 12, 5) and type_params: 

4301 # Make use of type_params 

4302 locals = dict(locals) if locals else {} 

4303 for tvar in type_params: 

4304 if tvar.__name__ not in locals: # lets not overwrite something present 

4305 locals[tvar.__name__] = tvar 

4306 if sys.version_info < (3, 12, 5): 

4307 return typing._eval_type( 

4308 value, 

4309 globals, 

4310 locals, 

4311 recursive_guard=_recursive_guard | {forward_ref.__forward_arg__}, 

4312 ) 

4313 else: 

4314 return typing._eval_type( 

4315 value, 

4316 globals, 

4317 locals, 

4318 type_params, 

4319 recursive_guard=_recursive_guard | {forward_ref.__forward_arg__}, 

4320 ) 

4321 

4322 

4323if sys.version_info >= (3, 14, 0, "beta"): 

4324 type_repr = annotationlib.type_repr 

4325else: 

4326 def type_repr(value): 

4327 """Convert a Python value to a format suitable for use with the STRING format. 

4328 

4329 This is intended as a helper for tools that support the STRING format but do 

4330 not have access to the code that originally produced the annotations. It uses 

4331 repr() for most objects. 

4332 

4333 """ 

4334 if isinstance(value, (type, _types.FunctionType, _types.BuiltinFunctionType)): 

4335 if value.__module__ == "builtins": 

4336 return value.__qualname__ 

4337 return f"{value.__module__}.{value.__qualname__}" 

4338 if value is ...: 

4339 return "..." 

4340 return repr(value) 

4341 

4342 

4343# Aliases for items that are in typing in all supported versions. 

4344# We use hasattr() checks so this library will continue to import on 

4345# future versions of Python that may remove these names. 

4346_typing_names = [ 

4347 "AbstractSet", 

4348 "AnyStr", 

4349 "BinaryIO", 

4350 "Callable", 

4351 "Collection", 

4352 "Container", 

4353 "Dict", 

4354 "FrozenSet", 

4355 "Hashable", 

4356 "IO", 

4357 "ItemsView", 

4358 "Iterable", 

4359 "Iterator", 

4360 "KeysView", 

4361 "List", 

4362 "Mapping", 

4363 "MappingView", 

4364 "Match", 

4365 "MutableMapping", 

4366 "MutableSequence", 

4367 "MutableSet", 

4368 "Optional", 

4369 "Pattern", 

4370 "Reversible", 

4371 "Sequence", 

4372 "Set", 

4373 "Sized", 

4374 "TextIO", 

4375 "Tuple", 

4376 "Union", 

4377 "ValuesView", 

4378 "cast", 

4379 "no_type_check", 

4380 # This is private, but it was defined by typing_extensions for a long time 

4381 # and some users rely on it. 

4382 "_AnnotatedAlias", 

4383] 

4384 

4385# Breakpoint: https://github.com/python/cpython/pull/133602 

4386if sys.version_info < (3, 15, 0): 

4387 _typing_names.append("no_type_check_decorator") 

4388 __all__.append("no_type_check_decorator") 

4389 

4390globals().update( 

4391 {name: getattr(typing, name) for name in _typing_names if hasattr(typing, name)} 

4392) 

4393# These are defined unconditionally because they are used in 

4394# typing-extensions itself. 

4395Generic = typing.Generic 

4396ForwardRef = typing.ForwardRef 

4397Annotated = typing.Annotated