typing.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. # util/typing.py
  2. # Copyright (C) 2022-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. from __future__ import annotations
  9. import builtins
  10. from collections import deque
  11. import collections.abc as collections_abc
  12. import re
  13. import sys
  14. import typing
  15. from typing import Any
  16. from typing import Callable
  17. from typing import Dict
  18. from typing import ForwardRef
  19. from typing import Generic
  20. from typing import Iterable
  21. from typing import Mapping
  22. from typing import NewType
  23. from typing import NoReturn
  24. from typing import Optional
  25. from typing import overload
  26. from typing import Set
  27. from typing import Tuple
  28. from typing import Type
  29. from typing import TYPE_CHECKING
  30. from typing import TypeVar
  31. from typing import Union
  32. import typing_extensions
  33. from . import compat
  34. if True: # zimports removes the tailing comments
  35. from typing_extensions import Annotated as Annotated # 3.8
  36. from typing_extensions import Concatenate as Concatenate # 3.10
  37. from typing_extensions import (
  38. dataclass_transform as dataclass_transform, # 3.11,
  39. )
  40. from typing_extensions import Final as Final # 3.8
  41. from typing_extensions import final as final # 3.8
  42. from typing_extensions import get_args as get_args # 3.10
  43. from typing_extensions import get_origin as get_origin # 3.10
  44. from typing_extensions import Literal as Literal # 3.8
  45. from typing_extensions import NotRequired as NotRequired # 3.11
  46. from typing_extensions import ParamSpec as ParamSpec # 3.10
  47. from typing_extensions import Protocol as Protocol # 3.8
  48. from typing_extensions import SupportsIndex as SupportsIndex # 3.8
  49. from typing_extensions import TypeAlias as TypeAlias # 3.10
  50. from typing_extensions import TypedDict as TypedDict # 3.8
  51. from typing_extensions import TypeGuard as TypeGuard # 3.10
  52. from typing_extensions import Self as Self # 3.11
  53. from typing_extensions import TypeAliasType as TypeAliasType # 3.12
  54. from typing_extensions import Never as Never # 3.11
  55. from typing_extensions import LiteralString as LiteralString # 3.11
  56. _T = TypeVar("_T", bound=Any)
  57. _KT = TypeVar("_KT")
  58. _KT_co = TypeVar("_KT_co", covariant=True)
  59. _KT_contra = TypeVar("_KT_contra", contravariant=True)
  60. _VT = TypeVar("_VT")
  61. _VT_co = TypeVar("_VT_co", covariant=True)
  62. if compat.py310:
  63. # why they took until py310 to put this in stdlib is beyond me,
  64. # I've been wanting it since py27
  65. from types import NoneType as NoneType
  66. else:
  67. NoneType = type(None) # type: ignore
  68. def is_fwd_none(typ: Any) -> bool:
  69. return isinstance(typ, ForwardRef) and typ.__forward_arg__ == "None"
  70. _AnnotationScanType = Union[
  71. Type[Any], str, ForwardRef, NewType, TypeAliasType, "GenericProtocol[Any]"
  72. ]
  73. class ArgsTypeProtocol(Protocol):
  74. """protocol for types that have ``__args__``
  75. there's no public interface for this AFAIK
  76. """
  77. __args__: Tuple[_AnnotationScanType, ...]
  78. class GenericProtocol(Protocol[_T]):
  79. """protocol for generic types.
  80. this since Python.typing _GenericAlias is private
  81. """
  82. __args__: Tuple[_AnnotationScanType, ...]
  83. __origin__: Type[_T]
  84. # Python's builtin _GenericAlias has this method, however builtins like
  85. # list, dict, etc. do not, even though they have ``__origin__`` and
  86. # ``__args__``
  87. #
  88. # def copy_with(self, params: Tuple[_AnnotationScanType, ...]) -> Type[_T]:
  89. # ...
  90. # copied from TypeShed, required in order to implement
  91. # MutableMapping.update()
  92. class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]):
  93. def keys(self) -> Iterable[_KT]: ...
  94. def __getitem__(self, __k: _KT) -> _VT_co: ...
  95. # work around https://github.com/microsoft/pyright/issues/3025
  96. _LiteralStar = Literal["*"]
  97. def de_stringify_annotation(
  98. cls: Type[Any],
  99. annotation: _AnnotationScanType,
  100. originating_module: str,
  101. locals_: Mapping[str, Any],
  102. *,
  103. str_cleanup_fn: Optional[Callable[[str, str], str]] = None,
  104. include_generic: bool = False,
  105. _already_seen: Optional[Set[Any]] = None,
  106. ) -> Type[Any]:
  107. """Resolve annotations that may be string based into real objects.
  108. This is particularly important if a module defines "from __future__ import
  109. annotations", as everything inside of __annotations__ is a string. We want
  110. to at least have generic containers like ``Mapped``, ``Union``, ``List``,
  111. etc.
  112. """
  113. # looked at typing.get_type_hints(), looked at pydantic. We need much
  114. # less here, and we here try to not use any private typing internals
  115. # or construct ForwardRef objects which is documented as something
  116. # that should be avoided.
  117. original_annotation = annotation
  118. if is_fwd_ref(annotation):
  119. annotation = annotation.__forward_arg__
  120. if isinstance(annotation, str):
  121. if str_cleanup_fn:
  122. annotation = str_cleanup_fn(annotation, originating_module)
  123. annotation = eval_expression(
  124. annotation, originating_module, locals_=locals_, in_class=cls
  125. )
  126. if (
  127. include_generic
  128. and is_generic(annotation)
  129. and not is_literal(annotation)
  130. ):
  131. if _already_seen is None:
  132. _already_seen = set()
  133. if annotation in _already_seen:
  134. # only occurs recursively. outermost return type
  135. # will always be Type.
  136. # the element here will be either ForwardRef or
  137. # Optional[ForwardRef]
  138. return original_annotation # type: ignore
  139. else:
  140. _already_seen.add(annotation)
  141. elements = tuple(
  142. de_stringify_annotation(
  143. cls,
  144. elem,
  145. originating_module,
  146. locals_,
  147. str_cleanup_fn=str_cleanup_fn,
  148. include_generic=include_generic,
  149. _already_seen=_already_seen,
  150. )
  151. for elem in annotation.__args__
  152. )
  153. return _copy_generic_annotation_with(annotation, elements)
  154. return annotation # type: ignore
  155. def fixup_container_fwd_refs(
  156. type_: _AnnotationScanType,
  157. ) -> _AnnotationScanType:
  158. """Correct dict['x', 'y'] into dict[ForwardRef('x'), ForwardRef('y')]
  159. and similar for list, set
  160. """
  161. if (
  162. is_generic(type_)
  163. and get_origin(type_)
  164. in (
  165. dict,
  166. set,
  167. list,
  168. collections_abc.MutableSet,
  169. collections_abc.MutableMapping,
  170. collections_abc.MutableSequence,
  171. collections_abc.Mapping,
  172. collections_abc.Sequence,
  173. )
  174. # fight, kick and scream to struggle to tell the difference between
  175. # dict[] and typing.Dict[] which DO NOT compare the same and DO NOT
  176. # behave the same yet there is NO WAY to distinguish between which type
  177. # it is using public attributes
  178. and not re.match(
  179. "typing.(?:Dict|List|Set|.*Mapping|.*Sequence|.*Set)", repr(type_)
  180. )
  181. ):
  182. # compat with py3.10 and earlier
  183. return get_origin(type_).__class_getitem__( # type: ignore
  184. tuple(
  185. [
  186. ForwardRef(elem) if isinstance(elem, str) else elem
  187. for elem in get_args(type_)
  188. ]
  189. )
  190. )
  191. return type_
  192. def _copy_generic_annotation_with(
  193. annotation: GenericProtocol[_T], elements: Tuple[_AnnotationScanType, ...]
  194. ) -> Type[_T]:
  195. if hasattr(annotation, "copy_with"):
  196. # List, Dict, etc. real generics
  197. return annotation.copy_with(elements) # type: ignore
  198. else:
  199. # Python builtins list, dict, etc.
  200. return annotation.__origin__[elements] # type: ignore
  201. def eval_expression(
  202. expression: str,
  203. module_name: str,
  204. *,
  205. locals_: Optional[Mapping[str, Any]] = None,
  206. in_class: Optional[Type[Any]] = None,
  207. ) -> Any:
  208. try:
  209. base_globals: Dict[str, Any] = sys.modules[module_name].__dict__
  210. except KeyError as ke:
  211. raise NameError(
  212. f"Module {module_name} isn't present in sys.modules; can't "
  213. f"evaluate expression {expression}"
  214. ) from ke
  215. try:
  216. if in_class is not None:
  217. cls_namespace = dict(in_class.__dict__)
  218. cls_namespace.setdefault(in_class.__name__, in_class)
  219. # see #10899. We want the locals/globals to take precedence
  220. # over the class namespace in this context, even though this
  221. # is not the usual way variables would resolve.
  222. cls_namespace.update(base_globals)
  223. annotation = eval(expression, cls_namespace, locals_)
  224. else:
  225. annotation = eval(expression, base_globals, locals_)
  226. except Exception as err:
  227. raise NameError(
  228. f"Could not de-stringify annotation {expression!r}"
  229. ) from err
  230. else:
  231. return annotation
  232. def eval_name_only(
  233. name: str,
  234. module_name: str,
  235. *,
  236. locals_: Optional[Mapping[str, Any]] = None,
  237. ) -> Any:
  238. if "." in name:
  239. return eval_expression(name, module_name, locals_=locals_)
  240. try:
  241. base_globals: Dict[str, Any] = sys.modules[module_name].__dict__
  242. except KeyError as ke:
  243. raise NameError(
  244. f"Module {module_name} isn't present in sys.modules; can't "
  245. f"resolve name {name}"
  246. ) from ke
  247. # name only, just look in globals. eval() works perfectly fine here,
  248. # however we are seeking to have this be faster, as this occurs for
  249. # every Mapper[] keyword, etc. depending on configuration
  250. try:
  251. return base_globals[name]
  252. except KeyError as ke:
  253. # check in builtins as well to handle `list`, `set` or `dict`, etc.
  254. try:
  255. return builtins.__dict__[name]
  256. except KeyError:
  257. pass
  258. raise NameError(
  259. f"Could not locate name {name} in module {module_name}"
  260. ) from ke
  261. def resolve_name_to_real_class_name(name: str, module_name: str) -> str:
  262. try:
  263. obj = eval_name_only(name, module_name)
  264. except NameError:
  265. return name
  266. else:
  267. return getattr(obj, "__name__", name)
  268. def is_pep593(type_: Optional[Any]) -> bool:
  269. return type_ is not None and get_origin(type_) in _type_tuples.Annotated
  270. def is_non_string_iterable(obj: Any) -> TypeGuard[Iterable[Any]]:
  271. return isinstance(obj, collections_abc.Iterable) and not isinstance(
  272. obj, (str, bytes)
  273. )
  274. def is_literal(type_: Any) -> bool:
  275. return get_origin(type_) in _type_tuples.Literal
  276. def is_newtype(type_: Optional[_AnnotationScanType]) -> TypeGuard[NewType]:
  277. return hasattr(type_, "__supertype__")
  278. # doesn't work in 3.8, 3.7 as it passes a closure, not an
  279. # object instance
  280. # isinstance(type, type_instances.NewType)
  281. def is_generic(type_: _AnnotationScanType) -> TypeGuard[GenericProtocol[Any]]:
  282. return hasattr(type_, "__args__") and hasattr(type_, "__origin__")
  283. def is_pep695(type_: _AnnotationScanType) -> TypeGuard[TypeAliasType]:
  284. # NOTE: a generic TAT does not instance check as TypeAliasType outside of
  285. # python 3.10. For sqlalchemy use cases it's fine to consider it a TAT
  286. # though.
  287. # NOTE: things seems to work also without this additional check
  288. if is_generic(type_):
  289. return is_pep695(type_.__origin__)
  290. return isinstance(type_, _type_instances.TypeAliasType)
  291. def flatten_newtype(type_: NewType) -> Type[Any]:
  292. super_type = type_.__supertype__
  293. while is_newtype(super_type):
  294. super_type = super_type.__supertype__
  295. return super_type # type: ignore[return-value]
  296. def pep695_values(type_: _AnnotationScanType) -> Set[Any]:
  297. """Extracts the value from a TypeAliasType, recursively exploring unions
  298. and inner TypeAliasType to flatten them into a single set.
  299. Forward references are not evaluated, so no recursive exploration happens
  300. into them.
  301. """
  302. _seen = set()
  303. def recursive_value(inner_type):
  304. if inner_type in _seen:
  305. # recursion are not supported (at least it's flagged as
  306. # an error by pyright). Just avoid infinite loop
  307. return inner_type
  308. _seen.add(inner_type)
  309. if not is_pep695(inner_type):
  310. return inner_type
  311. value = inner_type.__value__
  312. if not is_union(value):
  313. return value
  314. return [recursive_value(t) for t in value.__args__]
  315. res = recursive_value(type_)
  316. if isinstance(res, list):
  317. types = set()
  318. stack = deque(res)
  319. while stack:
  320. t = stack.popleft()
  321. if isinstance(t, list):
  322. stack.extend(t)
  323. else:
  324. types.add(None if t is NoneType or is_fwd_none(t) else t)
  325. return types
  326. else:
  327. return {res}
  328. def is_fwd_ref(
  329. type_: _AnnotationScanType,
  330. check_generic: bool = False,
  331. check_for_plain_string: bool = False,
  332. ) -> TypeGuard[ForwardRef]:
  333. if check_for_plain_string and isinstance(type_, str):
  334. return True
  335. elif isinstance(type_, _type_instances.ForwardRef):
  336. return True
  337. elif check_generic and is_generic(type_):
  338. return any(
  339. is_fwd_ref(
  340. arg, True, check_for_plain_string=check_for_plain_string
  341. )
  342. for arg in type_.__args__
  343. )
  344. else:
  345. return False
  346. @overload
  347. def de_optionalize_union_types(type_: str) -> str: ...
  348. @overload
  349. def de_optionalize_union_types(type_: Type[Any]) -> Type[Any]: ...
  350. @overload
  351. def de_optionalize_union_types(
  352. type_: _AnnotationScanType,
  353. ) -> _AnnotationScanType: ...
  354. def de_optionalize_union_types(
  355. type_: _AnnotationScanType,
  356. ) -> _AnnotationScanType:
  357. """Given a type, filter out ``Union`` types that include ``NoneType``
  358. to not include the ``NoneType``.
  359. Contains extra logic to work on non-flattened unions, unions that contain
  360. ``None`` (seen in py38, 37)
  361. """
  362. if is_fwd_ref(type_):
  363. return _de_optionalize_fwd_ref_union_types(type_, False)
  364. elif is_union(type_) and includes_none(type_):
  365. if compat.py39:
  366. typ = set(type_.__args__)
  367. else:
  368. # py38, 37 - unions are not automatically flattened, can contain
  369. # None rather than NoneType
  370. stack_of_unions = deque([type_])
  371. typ = set()
  372. while stack_of_unions:
  373. u_typ = stack_of_unions.popleft()
  374. for elem in u_typ.__args__:
  375. if is_union(elem):
  376. stack_of_unions.append(elem)
  377. else:
  378. typ.add(elem)
  379. typ.discard(None) # type: ignore
  380. typ = {t for t in typ if t is not NoneType and not is_fwd_none(t)}
  381. return make_union_type(*typ)
  382. else:
  383. return type_
  384. @overload
  385. def _de_optionalize_fwd_ref_union_types(
  386. type_: ForwardRef, return_has_none: Literal[True]
  387. ) -> bool: ...
  388. @overload
  389. def _de_optionalize_fwd_ref_union_types(
  390. type_: ForwardRef, return_has_none: Literal[False]
  391. ) -> _AnnotationScanType: ...
  392. def _de_optionalize_fwd_ref_union_types(
  393. type_: ForwardRef, return_has_none: bool
  394. ) -> Union[_AnnotationScanType, bool]:
  395. """return the non-optional type for Optional[], Union[None, ...], x|None,
  396. etc. without de-stringifying forward refs.
  397. unfortunately this seems to require lots of hardcoded heuristics
  398. """
  399. annotation = type_.__forward_arg__
  400. mm = re.match(r"^(.+?)\[(.+)\]$", annotation)
  401. if mm:
  402. g1 = mm.group(1).split(".")[-1]
  403. if g1 == "Optional":
  404. return True if return_has_none else ForwardRef(mm.group(2))
  405. elif g1 == "Union":
  406. if "[" in mm.group(2):
  407. # cases like "Union[Dict[str, int], int, None]"
  408. elements: list[str] = []
  409. current: list[str] = []
  410. ignore_comma = 0
  411. for char in mm.group(2):
  412. if char == "[":
  413. ignore_comma += 1
  414. elif char == "]":
  415. ignore_comma -= 1
  416. elif ignore_comma == 0 and char == ",":
  417. elements.append("".join(current).strip())
  418. current.clear()
  419. continue
  420. current.append(char)
  421. else:
  422. elements = re.split(r",\s*", mm.group(2))
  423. parts = [ForwardRef(elem) for elem in elements if elem != "None"]
  424. if return_has_none:
  425. return len(elements) != len(parts)
  426. else:
  427. return make_union_type(*parts) if parts else Never # type: ignore[return-value] # noqa: E501
  428. else:
  429. return False if return_has_none else type_
  430. pipe_tokens = re.split(r"\s*\|\s*", annotation)
  431. has_none = "None" in pipe_tokens
  432. if return_has_none:
  433. return has_none
  434. if has_none:
  435. anno_str = "|".join(p for p in pipe_tokens if p != "None")
  436. return ForwardRef(anno_str) if anno_str else Never # type: ignore[return-value] # noqa: E501
  437. return type_
  438. def make_union_type(*types: _AnnotationScanType) -> Type[Any]:
  439. """Make a Union type."""
  440. return Union[types] # type: ignore
  441. def includes_none(type_: Any) -> bool:
  442. """Returns if the type annotation ``type_`` allows ``None``.
  443. This function supports:
  444. * forward refs
  445. * unions
  446. * pep593 - Annotated
  447. * pep695 - TypeAliasType (does not support looking into
  448. fw reference of other pep695)
  449. * NewType
  450. * plain types like ``int``, ``None``, etc
  451. """
  452. if is_fwd_ref(type_):
  453. return _de_optionalize_fwd_ref_union_types(type_, True)
  454. if is_union(type_):
  455. return any(includes_none(t) for t in get_args(type_))
  456. if is_pep593(type_):
  457. return includes_none(get_args(type_)[0])
  458. if is_pep695(type_):
  459. return any(includes_none(t) for t in pep695_values(type_))
  460. if is_newtype(type_):
  461. return includes_none(type_.__supertype__)
  462. try:
  463. return type_ in (NoneType, None) or is_fwd_none(type_)
  464. except TypeError:
  465. # if type_ is Column, mapped_column(), etc. the use of "in"
  466. # resolves to ``__eq__()`` which then gives us an expression object
  467. # that can't resolve to boolean. just catch it all via exception
  468. return False
  469. def is_a_type(type_: Any) -> bool:
  470. return (
  471. isinstance(type_, type)
  472. or hasattr(type_, "__origin__")
  473. or type_.__module__ in ("typing", "typing_extensions")
  474. or type(type_).__mro__[0].__module__ in ("typing", "typing_extensions")
  475. )
  476. def is_union(type_: Any) -> TypeGuard[ArgsTypeProtocol]:
  477. return is_origin_of(type_, "Union", "UnionType")
  478. def is_origin_of_cls(
  479. type_: Any, class_obj: Union[Tuple[Type[Any], ...], Type[Any]]
  480. ) -> bool:
  481. """return True if the given type has an __origin__ that shares a base
  482. with the given class"""
  483. origin = get_origin(type_)
  484. if origin is None:
  485. return False
  486. return isinstance(origin, type) and issubclass(origin, class_obj)
  487. def is_origin_of(
  488. type_: Any, *names: str, module: Optional[str] = None
  489. ) -> bool:
  490. """return True if the given type has an __origin__ with the given name
  491. and optional module."""
  492. origin = get_origin(type_)
  493. if origin is None:
  494. return False
  495. return _get_type_name(origin) in names and (
  496. module is None or origin.__module__.startswith(module)
  497. )
  498. def _get_type_name(type_: Type[Any]) -> str:
  499. if compat.py310:
  500. return type_.__name__
  501. else:
  502. typ_name = getattr(type_, "__name__", None)
  503. if typ_name is None:
  504. typ_name = getattr(type_, "_name", None)
  505. return typ_name # type: ignore
  506. class DescriptorProto(Protocol):
  507. def __get__(self, instance: object, owner: Any) -> Any: ...
  508. def __set__(self, instance: Any, value: Any) -> None: ...
  509. def __delete__(self, instance: Any) -> None: ...
  510. _DESC = TypeVar("_DESC", bound=DescriptorProto)
  511. class DescriptorReference(Generic[_DESC]):
  512. """a descriptor that refers to a descriptor.
  513. used for cases where we need to have an instance variable referring to an
  514. object that is itself a descriptor, which typically confuses typing tools
  515. as they don't know when they should use ``__get__`` or not when referring
  516. to the descriptor assignment as an instance variable. See
  517. sqlalchemy.orm.interfaces.PropComparator.prop
  518. """
  519. if TYPE_CHECKING:
  520. def __get__(self, instance: object, owner: Any) -> _DESC: ...
  521. def __set__(self, instance: Any, value: _DESC) -> None: ...
  522. def __delete__(self, instance: Any) -> None: ...
  523. _DESC_co = TypeVar("_DESC_co", bound=DescriptorProto, covariant=True)
  524. class RODescriptorReference(Generic[_DESC_co]):
  525. """a descriptor that refers to a descriptor.
  526. same as :class:`.DescriptorReference` but is read-only, so that subclasses
  527. can define a subtype as the generically contained element
  528. """
  529. if TYPE_CHECKING:
  530. def __get__(self, instance: object, owner: Any) -> _DESC_co: ...
  531. def __set__(self, instance: Any, value: Any) -> NoReturn: ...
  532. def __delete__(self, instance: Any) -> NoReturn: ...
  533. _FN = TypeVar("_FN", bound=Optional[Callable[..., Any]])
  534. class CallableReference(Generic[_FN]):
  535. """a descriptor that refers to a callable.
  536. works around mypy's limitation of not allowing callables assigned
  537. as instance variables
  538. """
  539. if TYPE_CHECKING:
  540. def __get__(self, instance: object, owner: Any) -> _FN: ...
  541. def __set__(self, instance: Any, value: _FN) -> None: ...
  542. def __delete__(self, instance: Any) -> None: ...
  543. class _TypingInstances:
  544. def __getattr__(self, key: str) -> tuple[type, ...]:
  545. types = tuple(
  546. {
  547. t
  548. for t in [
  549. getattr(typing, key, None),
  550. getattr(typing_extensions, key, None),
  551. ]
  552. if t is not None
  553. }
  554. )
  555. if not types:
  556. raise AttributeError(key)
  557. self.__dict__[key] = types
  558. return types
  559. _type_tuples = _TypingInstances()
  560. if TYPE_CHECKING:
  561. _type_instances = typing_extensions
  562. else:
  563. _type_instances = _type_tuples
  564. LITERAL_TYPES = _type_tuples.Literal