您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

807 行
25 KiB

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