_utils.py 15 KB

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