25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

752 lines
24 KiB

  1. import warnings
  2. import weakref
  3. from collections import OrderedDict, defaultdict, deque
  4. from copy import deepcopy
  5. from itertools import islice, zip_longest
  6. from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType
  7. from typing import (
  8. TYPE_CHECKING,
  9. AbstractSet,
  10. Any,
  11. Callable,
  12. Collection,
  13. Dict,
  14. Generator,
  15. Iterable,
  16. Iterator,
  17. List,
  18. Mapping,
  19. Optional,
  20. Set,
  21. Tuple,
  22. Type,
  23. TypeVar,
  24. Union,
  25. )
  26. from typing_extensions import Annotated
  27. from .errors import ConfigError
  28. from .typing import (
  29. NoneType,
  30. WithArgsTypes,
  31. all_literal_values,
  32. display_as_type,
  33. get_args,
  34. get_origin,
  35. is_literal_type,
  36. is_union,
  37. )
  38. from .version import version_info
  39. if TYPE_CHECKING:
  40. from inspect import Signature
  41. from pathlib import Path
  42. from .config import BaseConfig
  43. from .dataclasses import Dataclass
  44. from .fields import ModelField
  45. from .main import BaseModel
  46. from .typing import AbstractSetIntStr, DictIntStrAny, IntStr, MappingIntStrAny, ReprArgs
  47. __all__ = (
  48. 'import_string',
  49. 'sequence_like',
  50. 'validate_field_name',
  51. 'lenient_isinstance',
  52. 'lenient_issubclass',
  53. 'in_ipython',
  54. 'deep_update',
  55. 'update_not_none',
  56. 'almost_equal_floats',
  57. 'get_model',
  58. 'to_camel',
  59. 'is_valid_field',
  60. 'smart_deepcopy',
  61. 'PyObjectStr',
  62. 'Representation',
  63. 'GetterDict',
  64. 'ValueItems',
  65. 'version_info', # required here to match behaviour in v1.3
  66. 'ClassAttribute',
  67. 'path_type',
  68. 'ROOT_KEY',
  69. 'get_unique_discriminator_alias',
  70. 'get_discriminator_alias_and_values',
  71. )
  72. ROOT_KEY = '__root__'
  73. # these are types that are returned unchanged by deepcopy
  74. IMMUTABLE_NON_COLLECTIONS_TYPES: Set[Type[Any]] = {
  75. int,
  76. float,
  77. complex,
  78. str,
  79. bool,
  80. bytes,
  81. type,
  82. NoneType,
  83. FunctionType,
  84. BuiltinFunctionType,
  85. LambdaType,
  86. weakref.ref,
  87. CodeType,
  88. # note: including ModuleType will differ from behaviour of deepcopy by not producing error.
  89. # It might be not a good idea in general, but considering that this function used only internally
  90. # against default values of fields, this will allow to actually have a field with module as default value
  91. ModuleType,
  92. NotImplemented.__class__,
  93. Ellipsis.__class__,
  94. }
  95. # these are types that if empty, might be copied with simple copy() instead of deepcopy()
  96. BUILTIN_COLLECTIONS: Set[Type[Any]] = {
  97. list,
  98. set,
  99. tuple,
  100. frozenset,
  101. dict,
  102. OrderedDict,
  103. defaultdict,
  104. deque,
  105. }
  106. def import_string(dotted_path: str) -> Any:
  107. """
  108. Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the
  109. last name in the path. Raise ImportError if the import fails.
  110. """
  111. from importlib import import_module
  112. try:
  113. module_path, class_name = dotted_path.strip(' ').rsplit('.', 1)
  114. except ValueError as e:
  115. raise ImportError(f'"{dotted_path}" doesn\'t look like a module path') from e
  116. module = import_module(module_path)
  117. try:
  118. return getattr(module, class_name)
  119. except AttributeError as e:
  120. raise ImportError(f'Module "{module_path}" does not define a "{class_name}" attribute') from e
  121. def truncate(v: Union[str], *, max_len: int = 80) -> str:
  122. """
  123. Truncate a value and add a unicode ellipsis (three dots) to the end if it was too long
  124. """
  125. warnings.warn('`truncate` is no-longer used by pydantic and is deprecated', DeprecationWarning)
  126. if isinstance(v, str) and len(v) > (max_len - 2):
  127. # -3 so quote + string + … + quote has correct length
  128. return (v[: (max_len - 3)] + '…').__repr__()
  129. try:
  130. v = v.__repr__()
  131. except TypeError:
  132. v = v.__class__.__repr__(v) # in case v is a type
  133. if len(v) > max_len:
  134. v = v[: max_len - 1] + '…'
  135. return v
  136. def sequence_like(v: Any) -> bool:
  137. return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque))
  138. def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None:
  139. """
  140. Ensure that the field's name does not shadow an existing attribute of the model.
  141. """
  142. for base in bases:
  143. if getattr(base, field_name, None):
  144. raise NameError(
  145. f'Field name "{field_name}" shadows a BaseModel attribute; '
  146. f'use a different field name with "alias=\'{field_name}\'".'
  147. )
  148. def lenient_isinstance(o: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...], None]) -> bool:
  149. try:
  150. return isinstance(o, class_or_tuple) # type: ignore[arg-type]
  151. except TypeError:
  152. return False
  153. def lenient_issubclass(cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...], None]) -> bool:
  154. try:
  155. return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type]
  156. except TypeError:
  157. if isinstance(cls, WithArgsTypes):
  158. return False
  159. raise # pragma: no cover
  160. def in_ipython() -> bool:
  161. """
  162. Check whether we're in an ipython environment, including jupyter notebooks.
  163. """
  164. try:
  165. eval('__IPYTHON__')
  166. except NameError:
  167. return False
  168. else: # pragma: no cover
  169. return True
  170. KeyType = TypeVar('KeyType')
  171. def deep_update(mapping: Dict[KeyType, Any], *updating_mappings: Dict[KeyType, Any]) -> Dict[KeyType, Any]:
  172. updated_mapping = mapping.copy()
  173. for updating_mapping in updating_mappings:
  174. for k, v in updating_mapping.items():
  175. if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict):
  176. updated_mapping[k] = deep_update(updated_mapping[k], v)
  177. else:
  178. updated_mapping[k] = v
  179. return updated_mapping
  180. def update_not_none(mapping: Dict[Any, Any], **update: Any) -> None:
  181. mapping.update({k: v for k, v in update.items() if v is not None})
  182. def almost_equal_floats(value_1: float, value_2: float, *, delta: float = 1e-8) -> bool:
  183. """
  184. Return True if two floats are almost equal
  185. """
  186. return abs(value_1 - value_2) <= delta
  187. def generate_model_signature(
  188. init: Callable[..., None], fields: Dict[str, 'ModelField'], config: Type['BaseConfig']
  189. ) -> 'Signature':
  190. """
  191. Generate signature for model based on its fields
  192. """
  193. from inspect import Parameter, Signature, signature
  194. from .config import Extra
  195. present_params = signature(init).parameters.values()
  196. merged_params: Dict[str, Parameter] = {}
  197. var_kw = None
  198. use_var_kw = False
  199. for param in islice(present_params, 1, None): # skip self arg
  200. if param.kind is param.VAR_KEYWORD:
  201. var_kw = param
  202. continue
  203. merged_params[param.name] = param
  204. if var_kw: # if custom init has no var_kw, fields which are not declared in it cannot be passed through
  205. allow_names = config.allow_population_by_field_name
  206. for field_name, field in fields.items():
  207. param_name = field.alias
  208. if field_name in merged_params or param_name in merged_params:
  209. continue
  210. elif not param_name.isidentifier():
  211. if allow_names and field_name.isidentifier():
  212. param_name = field_name
  213. else:
  214. use_var_kw = True
  215. continue
  216. # TODO: replace annotation with actual expected types once #1055 solved
  217. kwargs = {'default': field.default} if not field.required else {}
  218. merged_params[param_name] = Parameter(
  219. param_name, Parameter.KEYWORD_ONLY, annotation=field.outer_type_, **kwargs
  220. )
  221. if config.extra is Extra.allow:
  222. use_var_kw = True
  223. if var_kw and use_var_kw:
  224. # Make sure the parameter for extra kwargs
  225. # does not have the same name as a field
  226. default_model_signature = [
  227. ('__pydantic_self__', Parameter.POSITIONAL_OR_KEYWORD),
  228. ('data', Parameter.VAR_KEYWORD),
  229. ]
  230. if [(p.name, p.kind) for p in present_params] == default_model_signature:
  231. # if this is the standard model signature, use extra_data as the extra args name
  232. var_kw_name = 'extra_data'
  233. else:
  234. # else start from var_kw
  235. var_kw_name = var_kw.name
  236. # generate a name that's definitely unique
  237. while var_kw_name in fields:
  238. var_kw_name += '_'
  239. merged_params[var_kw_name] = var_kw.replace(name=var_kw_name)
  240. return Signature(parameters=list(merged_params.values()), return_annotation=None)
  241. def get_model(obj: Union[Type['BaseModel'], Type['Dataclass']]) -> Type['BaseModel']:
  242. from .main import BaseModel
  243. try:
  244. model_cls = obj.__pydantic_model__ # type: ignore
  245. except AttributeError:
  246. model_cls = obj
  247. if not issubclass(model_cls, BaseModel):
  248. raise TypeError('Unsupported type, must be either BaseModel or dataclass')
  249. return model_cls
  250. def to_camel(string: str) -> str:
  251. return ''.join(word.capitalize() for word in string.split('_'))
  252. T = TypeVar('T')
  253. def unique_list(
  254. input_list: Union[List[T], Tuple[T, ...]],
  255. *,
  256. name_factory: Callable[[T], str] = str,
  257. ) -> List[T]:
  258. """
  259. Make a list unique while maintaining order.
  260. We update the list if another one with the same name is set
  261. (e.g. root validator overridden in subclass)
  262. """
  263. result: List[T] = []
  264. result_names: List[str] = []
  265. for v in input_list:
  266. v_name = name_factory(v)
  267. if v_name not in result_names:
  268. result_names.append(v_name)
  269. result.append(v)
  270. else:
  271. result[result_names.index(v_name)] = v
  272. return result
  273. class PyObjectStr(str):
  274. """
  275. String class where repr doesn't include quotes. Useful with Representation when you want to return a string
  276. representation of something that valid (or pseudo-valid) python.
  277. """
  278. def __repr__(self) -> str:
  279. return str(self)
  280. class Representation:
  281. """
  282. Mixin to provide __str__, __repr__, and __pretty__ methods. See #884 for more details.
  283. __pretty__ is used by [devtools](https://python-devtools.helpmanual.io/) to provide human readable representations
  284. of objects.
  285. """
  286. __slots__: Tuple[str, ...] = tuple()
  287. def __repr_args__(self) -> 'ReprArgs':
  288. """
  289. Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
  290. Can either return:
  291. * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
  292. * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
  293. """
  294. attrs = ((s, getattr(self, s)) for s in self.__slots__)
  295. return [(a, v) for a, v in attrs if v is not None]
  296. def __repr_name__(self) -> str:
  297. """
  298. Name of the instance's class, used in __repr__.
  299. """
  300. return self.__class__.__name__
  301. def __repr_str__(self, join_str: str) -> str:
  302. return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__())
  303. def __pretty__(self, fmt: Callable[[Any], Any], **kwargs: Any) -> Generator[Any, None, None]:
  304. """
  305. Used by devtools (https://python-devtools.helpmanual.io/) to provide a human readable representations of objects
  306. """
  307. yield self.__repr_name__() + '('
  308. yield 1
  309. for name, value in self.__repr_args__():
  310. if name is not None:
  311. yield name + '='
  312. yield fmt(value)
  313. yield ','
  314. yield 0
  315. yield -1
  316. yield ')'
  317. def __str__(self) -> str:
  318. return self.__repr_str__(' ')
  319. def __repr__(self) -> str:
  320. return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
  321. class GetterDict(Representation):
  322. """
  323. Hack to make object's smell just enough like dicts for validate_model.
  324. We can't inherit from Mapping[str, Any] because it upsets cython so we have to implement all methods ourselves.
  325. """
  326. __slots__ = ('_obj',)
  327. def __init__(self, obj: Any):
  328. self._obj = obj
  329. def __getitem__(self, key: str) -> Any:
  330. try:
  331. return getattr(self._obj, key)
  332. except AttributeError as e:
  333. raise KeyError(key) from e
  334. def get(self, key: Any, default: Any = None) -> Any:
  335. return getattr(self._obj, key, default)
  336. def extra_keys(self) -> Set[Any]:
  337. """
  338. We don't want to get any other attributes of obj if the model didn't explicitly ask for them
  339. """
  340. return set()
  341. def keys(self) -> List[Any]:
  342. """
  343. Keys of the pseudo dictionary, uses a list not set so order information can be maintained like python
  344. dictionaries.
  345. """
  346. return list(self)
  347. def values(self) -> List[Any]:
  348. return [self[k] for k in self]
  349. def items(self) -> Iterator[Tuple[str, Any]]:
  350. for k in self:
  351. yield k, self.get(k)
  352. def __iter__(self) -> Iterator[str]:
  353. for name in dir(self._obj):
  354. if not name.startswith('_'):
  355. yield name
  356. def __len__(self) -> int:
  357. return sum(1 for _ in self)
  358. def __contains__(self, item: Any) -> bool:
  359. return item in self.keys()
  360. def __eq__(self, other: Any) -> bool:
  361. return dict(self) == dict(other.items())
  362. def __repr_args__(self) -> 'ReprArgs':
  363. return [(None, dict(self))]
  364. def __repr_name__(self) -> str:
  365. return f'GetterDict[{display_as_type(self._obj)}]'
  366. class ValueItems(Representation):
  367. """
  368. Class for more convenient calculation of excluded or included fields on values.
  369. """
  370. __slots__ = ('_items', '_type')
  371. def __init__(self, value: Any, items: Union['AbstractSetIntStr', 'MappingIntStrAny']) -> None:
  372. items = self._coerce_items(items)
  373. if isinstance(value, (list, tuple)):
  374. items = self._normalize_indexes(items, len(value))
  375. self._items: 'MappingIntStrAny' = items
  376. def is_excluded(self, item: Any) -> bool:
  377. """
  378. Check if item is fully excluded.
  379. :param item: key or index of a value
  380. """
  381. return self.is_true(self._items.get(item))
  382. def is_included(self, item: Any) -> bool:
  383. """
  384. Check if value is contained in self._items
  385. :param item: key or index of value
  386. """
  387. return item in self._items
  388. def for_element(self, e: 'IntStr') -> Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']]:
  389. """
  390. :param e: key or index of element on value
  391. :return: raw values for element if self._items is dict and contain needed element
  392. """
  393. item = self._items.get(e)
  394. return item if not self.is_true(item) else None
  395. def _normalize_indexes(self, items: 'MappingIntStrAny', v_length: int) -> 'DictIntStrAny':
  396. """
  397. :param items: dict or set of indexes which will be normalized
  398. :param v_length: length of sequence indexes of which will be
  399. >>> self._normalize_indexes({0: True, -2: True, -1: True}, 4)
  400. {0: True, 2: True, 3: True}
  401. >>> self._normalize_indexes({'__all__': True}, 4)
  402. {0: True, 1: True, 2: True, 3: True}
  403. """
  404. normalized_items: 'DictIntStrAny' = {}
  405. all_items = None
  406. for i, v in items.items():
  407. if not (isinstance(v, Mapping) or isinstance(v, AbstractSet) or self.is_true(v)):
  408. raise TypeError(f'Unexpected type of exclude value for index "{i}" {v.__class__}')
  409. if i == '__all__':
  410. all_items = self._coerce_value(v)
  411. continue
  412. if not isinstance(i, int):
  413. raise TypeError(
  414. 'Excluding fields from a sequence of sub-models or dicts must be performed index-wise: '
  415. 'expected integer keys or keyword "__all__"'
  416. )
  417. normalized_i = v_length + i if i < 0 else i
  418. normalized_items[normalized_i] = self.merge(v, normalized_items.get(normalized_i))
  419. if not all_items:
  420. return normalized_items
  421. if self.is_true(all_items):
  422. for i in range(v_length):
  423. normalized_items.setdefault(i, ...)
  424. return normalized_items
  425. for i in range(v_length):
  426. normalized_item = normalized_items.setdefault(i, {})
  427. if not self.is_true(normalized_item):
  428. normalized_items[i] = self.merge(all_items, normalized_item)
  429. return normalized_items
  430. @classmethod
  431. def merge(cls, base: Any, override: Any, intersect: bool = False) -> Any:
  432. """
  433. Merge a ``base`` item with an ``override`` item.
  434. Both ``base`` and ``override`` are converted to dictionaries if possible.
  435. Sets are converted to dictionaries with the sets entries as keys and
  436. Ellipsis as values.
  437. Each key-value pair existing in ``base`` is merged with ``override``,
  438. while the rest of the key-value pairs are updated recursively with this function.
  439. Merging takes place based on the "union" of keys if ``intersect`` is
  440. set to ``False`` (default) and on the intersection of keys if
  441. ``intersect`` is set to ``True``.
  442. """
  443. override = cls._coerce_value(override)
  444. base = cls._coerce_value(base)
  445. if override is None:
  446. return base
  447. if cls.is_true(base) or base is None:
  448. return override
  449. if cls.is_true(override):
  450. return base if intersect else override
  451. # intersection or union of keys while preserving ordering:
  452. if intersect:
  453. merge_keys = [k for k in base if k in override] + [k for k in override if k in base]
  454. else:
  455. merge_keys = list(base) + [k for k in override if k not in base]
  456. merged: 'DictIntStrAny' = {}
  457. for k in merge_keys:
  458. merged_item = cls.merge(base.get(k), override.get(k), intersect=intersect)
  459. if merged_item is not None:
  460. merged[k] = merged_item
  461. return merged
  462. @staticmethod
  463. def _coerce_items(items: Union['AbstractSetIntStr', 'MappingIntStrAny']) -> 'MappingIntStrAny':
  464. if isinstance(items, Mapping):
  465. pass
  466. elif isinstance(items, AbstractSet):
  467. items = dict.fromkeys(items, ...)
  468. else:
  469. class_name = getattr(items, '__class__', '???')
  470. raise TypeError(f'Unexpected type of exclude value {class_name}')
  471. return items
  472. @classmethod
  473. def _coerce_value(cls, value: Any) -> Any:
  474. if value is None or cls.is_true(value):
  475. return value
  476. return cls._coerce_items(value)
  477. @staticmethod
  478. def is_true(v: Any) -> bool:
  479. return v is True or v is ...
  480. def __repr_args__(self) -> 'ReprArgs':
  481. return [(None, self._items)]
  482. class ClassAttribute:
  483. """
  484. Hide class attribute from its instances
  485. """
  486. __slots__ = (
  487. 'name',
  488. 'value',
  489. )
  490. def __init__(self, name: str, value: Any) -> None:
  491. self.name = name
  492. self.value = value
  493. def __get__(self, instance: Any, owner: Type[Any]) -> None:
  494. if instance is None:
  495. return self.value
  496. raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only')
  497. path_types = {
  498. 'is_dir': 'directory',
  499. 'is_file': 'file',
  500. 'is_mount': 'mount point',
  501. 'is_symlink': 'symlink',
  502. 'is_block_device': 'block device',
  503. 'is_char_device': 'char device',
  504. 'is_fifo': 'FIFO',
  505. 'is_socket': 'socket',
  506. }
  507. def path_type(p: 'Path') -> str:
  508. """
  509. Find out what sort of thing a path is.
  510. """
  511. assert p.exists(), 'path does not exist'
  512. for method, name in path_types.items():
  513. if getattr(p, method)():
  514. return name
  515. return 'unknown'
  516. Obj = TypeVar('Obj')
  517. def smart_deepcopy(obj: Obj) -> Obj:
  518. """
  519. Return type as is for immutable built-in types
  520. Use obj.copy() for built-in empty collections
  521. Use copy.deepcopy() for non-empty collections and unknown objects
  522. """
  523. obj_type = obj.__class__
  524. if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES:
  525. return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway
  526. elif not obj and obj_type in BUILTIN_COLLECTIONS:
  527. # faster way for empty collections, no need to copy its members
  528. return obj if obj_type is tuple else obj.copy() # type: ignore # tuple doesn't have copy method
  529. return deepcopy(obj) # slowest way when we actually might need a deepcopy
  530. def is_valid_field(name: str) -> bool:
  531. if not name.startswith('_'):
  532. return True
  533. return ROOT_KEY == name
  534. def is_valid_private_name(name: str) -> bool:
  535. return not is_valid_field(name) and name not in {
  536. '__annotations__',
  537. '__classcell__',
  538. '__doc__',
  539. '__module__',
  540. '__orig_bases__',
  541. '__qualname__',
  542. }
  543. _EMPTY = object()
  544. def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool:
  545. """
  546. Check that the items of `left` are the same objects as those in `right`.
  547. >>> a, b = object(), object()
  548. >>> all_identical([a, b, a], [a, b, a])
  549. True
  550. >>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical"
  551. False
  552. """
  553. for left_item, right_item in zip_longest(left, right, fillvalue=_EMPTY):
  554. if left_item is not right_item:
  555. return False
  556. return True
  557. def get_unique_discriminator_alias(all_aliases: Collection[str], discriminator_key: str) -> str:
  558. """Validate that all aliases are the same and if that's the case return the alias"""
  559. unique_aliases = set(all_aliases)
  560. if len(unique_aliases) > 1:
  561. raise ConfigError(
  562. f'Aliases for discriminator {discriminator_key!r} must be the same (got {", ".join(sorted(all_aliases))})'
  563. )
  564. return unique_aliases.pop()
  565. def get_discriminator_alias_and_values(tp: Any, discriminator_key: str) -> Tuple[str, Tuple[str, ...]]:
  566. """
  567. Get alias and all valid values in the `Literal` type of the discriminator field
  568. `tp` can be a `BaseModel` class or directly an `Annotated` `Union` of many.
  569. """
  570. is_root_model = getattr(tp, '__custom_root_type__', False)
  571. if get_origin(tp) is Annotated:
  572. tp = get_args(tp)[0]
  573. if hasattr(tp, '__pydantic_model__'):
  574. tp = tp.__pydantic_model__
  575. if is_union(get_origin(tp)):
  576. alias, all_values = _get_union_alias_and_all_values(tp, discriminator_key)
  577. return alias, tuple(v for values in all_values for v in values)
  578. elif is_root_model:
  579. union_type = tp.__fields__[ROOT_KEY].type_
  580. alias, all_values = _get_union_alias_and_all_values(union_type, discriminator_key)
  581. if len(set(all_values)) > 1:
  582. raise ConfigError(
  583. f'Field {discriminator_key!r} is not the same for all submodels of {display_as_type(tp)!r}'
  584. )
  585. return alias, all_values[0]
  586. else:
  587. try:
  588. t_discriminator_type = tp.__fields__[discriminator_key].type_
  589. except AttributeError as e:
  590. raise TypeError(f'Type {tp.__name__!r} is not a valid `BaseModel` or `dataclass`') from e
  591. except KeyError as e:
  592. raise ConfigError(f'Model {tp.__name__!r} needs a discriminator field for key {discriminator_key!r}') from e
  593. if not is_literal_type(t_discriminator_type):
  594. raise ConfigError(f'Field {discriminator_key!r} of model {tp.__name__!r} needs to be a `Literal`')
  595. return tp.__fields__[discriminator_key].alias, all_literal_values(t_discriminator_type)
  596. def _get_union_alias_and_all_values(
  597. union_type: Type[Any], discriminator_key: str
  598. ) -> Tuple[str, Tuple[Tuple[str, ...], ...]]:
  599. zipped_aliases_values = [get_discriminator_alias_and_values(t, discriminator_key) for t in get_args(union_type)]
  600. # unzip: [('alias_a',('v1', 'v2)), ('alias_b', ('v3',))] => [('alias_a', 'alias_b'), (('v1', 'v2'), ('v3',))]
  601. all_aliases, all_values = zip(*zipped_aliases_values)
  602. return get_unique_discriminator_alias(all_aliases, discriminator_key), all_values