_utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. """Bucket of reusable internal utilities.
  2. This should be reduced as much as possible with functions only used in one place, moved to that place.
  3. """
  4. from __future__ import annotations as _annotations
  5. import dataclasses
  6. import keyword
  7. import sys
  8. import warnings
  9. import weakref
  10. from collections import OrderedDict, defaultdict, deque
  11. from collections.abc import Callable, Iterable, Mapping
  12. from collections.abc import Set as AbstractSet
  13. from copy import deepcopy
  14. from functools import cached_property
  15. from inspect import Parameter
  16. from itertools import zip_longest
  17. from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType
  18. from typing import TYPE_CHECKING, Any, Generic, TypeVar, overload
  19. from pydantic_core import MISSING
  20. from typing_extensions import TypeAlias, TypeGuard, deprecated
  21. from pydantic import PydanticDeprecatedSince211
  22. from . import _repr, _typing_extra
  23. from ._import_utils import import_cached_base_model
  24. if TYPE_CHECKING:
  25. # TODO remove type error comments when we drop support for Python 3.9
  26. MappingIntStrAny: TypeAlias = Mapping[int, Any] | Mapping[str, Any] # pyright: ignore[reportGeneralTypeIssues]
  27. AbstractSetIntStr: TypeAlias = AbstractSet[int] | AbstractSet[str] # pyright: ignore[reportGeneralTypeIssues]
  28. from ..main import BaseModel
  29. # these are types that are returned unchanged by deepcopy
  30. IMMUTABLE_NON_COLLECTIONS_TYPES: set[type[Any]] = {
  31. int,
  32. float,
  33. complex,
  34. str,
  35. bool,
  36. bytes,
  37. type,
  38. _typing_extra.NoneType,
  39. FunctionType,
  40. BuiltinFunctionType,
  41. LambdaType,
  42. weakref.ref,
  43. CodeType,
  44. # note: including ModuleType will differ from behaviour of deepcopy by not producing error.
  45. # It might be not a good idea in general, but considering that this function used only internally
  46. # against default values of fields, this will allow to actually have a field with module as default value
  47. ModuleType,
  48. NotImplemented.__class__,
  49. Ellipsis.__class__,
  50. }
  51. # these are types that if empty, might be copied with simple copy() instead of deepcopy()
  52. BUILTIN_COLLECTIONS: set[type[Any]] = {
  53. list,
  54. set,
  55. tuple,
  56. frozenset,
  57. dict,
  58. OrderedDict,
  59. defaultdict,
  60. deque,
  61. }
  62. def can_be_positional(param: Parameter) -> bool:
  63. """Return whether the parameter accepts a positional argument.
  64. ```python {test="skip" lint="skip"}
  65. def func(a, /, b, *, c):
  66. pass
  67. params = inspect.signature(func).parameters
  68. can_be_positional(params['a'])
  69. #> True
  70. can_be_positional(params['b'])
  71. #> True
  72. can_be_positional(params['c'])
  73. #> False
  74. ```
  75. """
  76. return param.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD)
  77. def sequence_like(v: Any) -> bool:
  78. return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque))
  79. def lenient_isinstance(o: Any, class_or_tuple: type[Any] | tuple[type[Any], ...] | None) -> bool: # pragma: no cover
  80. try:
  81. return isinstance(o, class_or_tuple) # type: ignore[arg-type]
  82. except TypeError:
  83. return False
  84. def lenient_issubclass(cls: Any, class_or_tuple: Any) -> bool: # pragma: no cover
  85. try:
  86. return isinstance(cls, type) and issubclass(cls, class_or_tuple)
  87. except TypeError:
  88. if isinstance(cls, _typing_extra.WithArgsTypes):
  89. return False
  90. raise # pragma: no cover
  91. def is_model_class(cls: Any) -> TypeGuard[type[BaseModel]]:
  92. """Returns true if cls is a _proper_ subclass of BaseModel, and provides proper type-checking,
  93. unlike raw calls to lenient_issubclass.
  94. """
  95. BaseModel = import_cached_base_model()
  96. return lenient_issubclass(cls, BaseModel) and cls is not BaseModel
  97. def is_valid_identifier(identifier: str) -> bool:
  98. """Checks that a string is a valid identifier and not a Python keyword.
  99. :param identifier: The identifier to test.
  100. :return: True if the identifier is valid.
  101. """
  102. return identifier.isidentifier() and not keyword.iskeyword(identifier)
  103. KeyType = TypeVar('KeyType')
  104. def deep_update(mapping: dict[KeyType, Any], *updating_mappings: dict[KeyType, Any]) -> dict[KeyType, Any]:
  105. updated_mapping = mapping.copy()
  106. for updating_mapping in updating_mappings:
  107. for k, v in updating_mapping.items():
  108. if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict):
  109. updated_mapping[k] = deep_update(updated_mapping[k], v)
  110. else:
  111. updated_mapping[k] = v
  112. return updated_mapping
  113. def update_not_none(mapping: dict[Any, Any], **update: Any) -> None:
  114. mapping.update({k: v for k, v in update.items() if v is not None})
  115. T = TypeVar('T')
  116. def unique_list(
  117. input_list: list[T] | tuple[T, ...],
  118. *,
  119. name_factory: Callable[[T], str] = str,
  120. ) -> list[T]:
  121. """Make a list unique while maintaining order.
  122. We update the list if another one with the same name is set
  123. (e.g. model validator overridden in subclass).
  124. """
  125. result: list[T] = []
  126. result_names: list[str] = []
  127. for v in input_list:
  128. v_name = name_factory(v)
  129. if v_name not in result_names:
  130. result_names.append(v_name)
  131. result.append(v)
  132. else:
  133. result[result_names.index(v_name)] = v
  134. return result
  135. class ValueItems(_repr.Representation):
  136. """Class for more convenient calculation of excluded or included fields on values."""
  137. __slots__ = ('_items', '_type')
  138. def __init__(self, value: Any, items: AbstractSetIntStr | MappingIntStrAny) -> None:
  139. items = self._coerce_items(items)
  140. if isinstance(value, (list, tuple)):
  141. items = self._normalize_indexes(items, len(value)) # type: ignore
  142. self._items: MappingIntStrAny = items # type: ignore
  143. def is_excluded(self, item: Any) -> bool:
  144. """Check if item is fully excluded.
  145. :param item: key or index of a value
  146. """
  147. return self.is_true(self._items.get(item))
  148. def is_included(self, item: Any) -> bool:
  149. """Check if value is contained in self._items.
  150. :param item: key or index of value
  151. """
  152. return item in self._items
  153. def for_element(self, e: int | str) -> AbstractSetIntStr | MappingIntStrAny | None:
  154. """:param e: key or index of element on value
  155. :return: raw values for element if self._items is dict and contain needed element
  156. """
  157. item = self._items.get(e) # type: ignore
  158. return item if not self.is_true(item) else None
  159. def _normalize_indexes(self, items: MappingIntStrAny, v_length: int) -> dict[int | str, Any]:
  160. """:param items: dict or set of indexes which will be normalized
  161. :param v_length: length of sequence indexes of which will be
  162. >>> self._normalize_indexes({0: True, -2: True, -1: True}, 4)
  163. {0: True, 2: True, 3: True}
  164. >>> self._normalize_indexes({'__all__': True}, 4)
  165. {0: True, 1: True, 2: True, 3: True}
  166. """
  167. normalized_items: dict[int | str, Any] = {}
  168. all_items = None
  169. for i, v in items.items():
  170. if not (isinstance(v, Mapping) or isinstance(v, AbstractSet) or self.is_true(v)):
  171. raise TypeError(f'Unexpected type of exclude value for index "{i}" {v.__class__}')
  172. if i == '__all__':
  173. all_items = self._coerce_value(v)
  174. continue
  175. if not isinstance(i, int):
  176. raise TypeError(
  177. 'Excluding fields from a sequence of sub-models or dicts must be performed index-wise: '
  178. 'expected integer keys or keyword "__all__"'
  179. )
  180. normalized_i = v_length + i if i < 0 else i
  181. normalized_items[normalized_i] = self.merge(v, normalized_items.get(normalized_i))
  182. if not all_items:
  183. return normalized_items
  184. if self.is_true(all_items):
  185. for i in range(v_length):
  186. normalized_items.setdefault(i, ...)
  187. return normalized_items
  188. for i in range(v_length):
  189. normalized_item = normalized_items.setdefault(i, {})
  190. if not self.is_true(normalized_item):
  191. normalized_items[i] = self.merge(all_items, normalized_item)
  192. return normalized_items
  193. @classmethod
  194. def merge(cls, base: Any, override: Any, intersect: bool = False) -> Any:
  195. """Merge a `base` item with an `override` item.
  196. Both `base` and `override` are converted to dictionaries if possible.
  197. Sets are converted to dictionaries with the sets entries as keys and
  198. Ellipsis as values.
  199. Each key-value pair existing in `base` is merged with `override`,
  200. while the rest of the key-value pairs are updated recursively with this function.
  201. Merging takes place based on the "union" of keys if `intersect` is
  202. set to `False` (default) and on the intersection of keys if
  203. `intersect` is set to `True`.
  204. """
  205. override = cls._coerce_value(override)
  206. base = cls._coerce_value(base)
  207. if override is None:
  208. return base
  209. if cls.is_true(base) or base is None:
  210. return override
  211. if cls.is_true(override):
  212. return base if intersect else override
  213. # intersection or union of keys while preserving ordering:
  214. if intersect:
  215. merge_keys = [k for k in base if k in override] + [k for k in override if k in base]
  216. else:
  217. merge_keys = list(base) + [k for k in override if k not in base]
  218. merged: dict[int | str, Any] = {}
  219. for k in merge_keys:
  220. merged_item = cls.merge(base.get(k), override.get(k), intersect=intersect)
  221. if merged_item is not None:
  222. merged[k] = merged_item
  223. return merged
  224. @staticmethod
  225. def _coerce_items(items: AbstractSetIntStr | MappingIntStrAny) -> MappingIntStrAny:
  226. if isinstance(items, Mapping):
  227. pass
  228. elif isinstance(items, AbstractSet):
  229. items = dict.fromkeys(items, ...) # type: ignore
  230. else:
  231. class_name = getattr(items, '__class__', '???')
  232. raise TypeError(f'Unexpected type of exclude value {class_name}')
  233. return items # type: ignore
  234. @classmethod
  235. def _coerce_value(cls, value: Any) -> Any:
  236. if value is None or cls.is_true(value):
  237. return value
  238. return cls._coerce_items(value)
  239. @staticmethod
  240. def is_true(v: Any) -> bool:
  241. return v is True or v is ...
  242. def __repr_args__(self) -> _repr.ReprArgs:
  243. return [(None, self._items)]
  244. if TYPE_CHECKING:
  245. def LazyClassAttribute(name: str, get_value: Callable[[], T]) -> T: ...
  246. else:
  247. class LazyClassAttribute:
  248. """A descriptor exposing an attribute only accessible on a class (hidden from instances).
  249. The attribute is lazily computed and cached during the first access.
  250. """
  251. def __init__(self, name: str, get_value: Callable[[], Any]) -> None:
  252. self.name = name
  253. self.get_value = get_value
  254. @cached_property
  255. def value(self) -> Any:
  256. return self.get_value()
  257. def __get__(self, instance: Any, owner: type[Any]) -> None:
  258. if instance is None:
  259. return self.value
  260. raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only')
  261. Obj = TypeVar('Obj')
  262. def smart_deepcopy(obj: Obj) -> Obj:
  263. """Return type as is for immutable built-in types
  264. Use obj.copy() for built-in empty collections
  265. Use copy.deepcopy() for non-empty collections and unknown objects.
  266. """
  267. if obj is MISSING:
  268. return obj # pyright: ignore[reportReturnType]
  269. obj_type = obj.__class__
  270. if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES:
  271. return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway
  272. try:
  273. if not obj and obj_type in BUILTIN_COLLECTIONS:
  274. # faster way for empty collections, no need to copy its members
  275. return obj if obj_type is tuple else obj.copy() # tuple doesn't have copy method # type: ignore
  276. except (TypeError, ValueError, RuntimeError):
  277. # do we really dare to catch ALL errors? Seems a bit risky
  278. pass
  279. return deepcopy(obj) # slowest way when we actually might need a deepcopy
  280. _SENTINEL = object()
  281. def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool:
  282. """Check that the items of `left` are the same objects as those in `right`.
  283. >>> a, b = object(), object()
  284. >>> all_identical([a, b, a], [a, b, a])
  285. True
  286. >>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical"
  287. False
  288. """
  289. for left_item, right_item in zip_longest(left, right, fillvalue=_SENTINEL):
  290. if left_item is not right_item:
  291. return False
  292. return True
  293. def get_first_not_none(a: Any, b: Any) -> Any:
  294. """Return the first argument if it is not `None`, otherwise return the second argument."""
  295. return a if a is not None else b
  296. @dataclasses.dataclass(frozen=True)
  297. class SafeGetItemProxy:
  298. """Wrapper redirecting `__getitem__` to `get` with a sentinel value as default
  299. This makes is safe to use in `operator.itemgetter` when some keys may be missing
  300. """
  301. # Define __slots__manually for performances
  302. # @dataclasses.dataclass() only support slots=True in python>=3.10
  303. __slots__ = ('wrapped',)
  304. wrapped: Mapping[str, Any]
  305. def __getitem__(self, key: str, /) -> Any:
  306. return self.wrapped.get(key, _SENTINEL)
  307. # required to pass the object to operator.itemgetter() instances due to a quirk of typeshed
  308. # https://github.com/python/mypy/issues/13713
  309. # https://github.com/python/typeshed/pull/8785
  310. # Since this is typing-only, hide it in a typing.TYPE_CHECKING block
  311. if TYPE_CHECKING:
  312. def __contains__(self, key: str, /) -> bool:
  313. return self.wrapped.__contains__(key)
  314. _ModelT = TypeVar('_ModelT', bound='BaseModel')
  315. _RT = TypeVar('_RT')
  316. class deprecated_instance_property(Generic[_ModelT, _RT]):
  317. """A decorator exposing the decorated class method as a property, with a warning on instance access.
  318. This decorator takes a class method defined on the `BaseModel` class and transforms it into
  319. an attribute. The attribute can be accessed on both the class and instances of the class. If accessed
  320. via an instance, a deprecation warning is emitted stating that instance access will be removed in V3.
  321. """
  322. def __init__(self, fget: Callable[[type[_ModelT]], _RT], /) -> None:
  323. # Note: fget should be a classmethod:
  324. self.fget = fget
  325. @overload
  326. def __get__(self, instance: None, objtype: type[_ModelT]) -> _RT: ...
  327. @overload
  328. @deprecated(
  329. 'Accessing this attribute on the instance is deprecated, and will be removed in Pydantic V3. '
  330. 'Instead, you should access this attribute from the model class.',
  331. category=None,
  332. )
  333. def __get__(self, instance: _ModelT, objtype: type[_ModelT]) -> _RT: ...
  334. def __get__(self, instance: _ModelT | None, objtype: type[_ModelT]) -> _RT:
  335. if instance is not None:
  336. # fmt: off
  337. attr_name = (
  338. self.fget.__name__
  339. if sys.version_info >= (3, 10)
  340. else self.fget.__func__.__name__ # pyright: ignore[reportFunctionMemberAccess]
  341. )
  342. # fmt: on
  343. warnings.warn(
  344. f'Accessing the {attr_name!r} attribute on the instance is deprecated. '
  345. 'Instead, you should access this attribute from the model class.',
  346. category=PydanticDeprecatedSince211,
  347. stacklevel=2,
  348. )
  349. return self.fget.__get__(instance, objtype)()