Coverage for pydantic / _internal / _utils.py: 100.00%

64 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""Bucket of reusable internal utilities. 

2 

3This should be reduced as much as possible with functions only used in one place, moved to that place. 

4""" 

5 

6from __future__ import annotations as _annotations 1abcdefghijklsmnopqr

7 

8import dataclasses 1abcdefghijklsmnopqr

9import keyword 1abcdefghijklsmnopqr

10import weakref 1abcdefghijklsmnopqr

11from collections import OrderedDict, defaultdict, deque 1abcdefghijklsmnopqr

12from collections.abc import Callable, Iterable, Mapping 1abcdefghijklsmnopqr

13from copy import deepcopy 1abcdefghijklsmnopqr

14from functools import cached_property 1abcdefghijklsmnopqr

15from inspect import Parameter 1abcdefghijklsmnopqr

16from itertools import zip_longest 1abcdefghijklsmnopqr

17from types import BuiltinFunctionType, CodeType, FunctionType, LambdaType, ModuleType, NoneType 1abcdefghijklsmnopqr

18from typing import TYPE_CHECKING, Any, TypeGuard, TypeVar 1abcdefghijklsmnopqr

19 

20from pydantic_core import MISSING, PydanticUndefined 1abcdefghijklsmnopqr

21 

22from . import _typing_extra 1abcdefghijklsmnopqr

23from ._import_utils import import_cached_base_model 1abcdefghijklsmnopqr

24 

25if TYPE_CHECKING: 1abcdefghijklsmnopqr

26 from ..main import BaseModel 

27 

28 

29# these are types that are returned unchanged by deepcopy 

30IMMUTABLE_NON_COLLECTIONS_TYPES: set[type[Any]] = { 1abcdefghijklsmnopqr

31 int, 

32 float, 

33 complex, 

34 str, 

35 bool, 

36 bytes, 

37 type, 

38 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 one to actually have a field with module as default value 

47 ModuleType, 

48 NotImplemented.__class__, 

49 Ellipsis.__class__, 

50} 

51 

52# these are types that if empty, might be copied with simple copy() instead of deepcopy() 

53BUILTIN_COLLECTIONS: set[type[Any]] = { 1abcdefghijklsmnopqr

54 list, 

55 set, 

56 tuple, 

57 frozenset, 

58 dict, 

59 OrderedDict, 

60 defaultdict, 

61 deque, 

62} 

63 

64 

65def can_be_positional(param: Parameter) -> bool: 1abcdefghijklsmnopqr

66 """Return whether the parameter accepts a positional argument. 

67 

68 ```python {test="skip" lint="skip"} 

69 def func(a, /, b, *, c): 

70 pass 

71 

72 params = inspect.signature(func).parameters 

73 can_be_positional(params['a']) 

74 #> True 

75 can_be_positional(params['b']) 

76 #> True 

77 can_be_positional(params['c']) 

78 #> False 

79 ``` 

80 """ 

81 return param.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD) 1abcdefghijklsmnopqr

82 

83 

84def lenient_issubclass(cls: Any, class_or_tuple: Any) -> bool: # pragma: no cover 1abcdefghijklsmnopqr

85 try: 1abcdefghijklsmnopqr

86 return isinstance(cls, type) and issubclass(cls, class_or_tuple) 1abcdefghijklsmnopqr

87 except TypeError: 

88 if isinstance(cls, _typing_extra.WithArgsTypes): 

89 return False 

90 raise # pragma: no cover 

91 

92 

93def is_model_class(cls: Any) -> TypeGuard[type[BaseModel]]: 1abcdefghijklsmnopqr

94 """Returns true if cls is a _proper_ subclass of BaseModel, and provides proper type-checking, 

95 unlike raw calls to lenient_issubclass. 

96 """ 

97 BaseModel = import_cached_base_model() 1abcdefghijklsmnopqr

98 

99 return lenient_issubclass(cls, BaseModel) and cls is not BaseModel 1abcdefghijklsmnopqr

100 

101 

102def is_valid_identifier(identifier: str) -> bool: 1abcdefghijklsmnopqr

103 """Checks that a string is a valid identifier and not a Python keyword. 

104 :param identifier: The identifier to test. 

105 :return: True if the identifier is valid. 

106 """ 

107 return identifier.isidentifier() and not keyword.iskeyword(identifier) 1abcdefghijklmnopqr

108 

109 

110def update_not_none(mapping: dict[Any, Any], **update: Any) -> None: 1abcdefghijklsmnopqr

111 mapping.update({k: v for k, v in update.items() if v is not None}) 1abcdefghijklmnopqr

112 

113 

114T = TypeVar('T') 1abcdefghijklsmnopqr

115 

116 

117if TYPE_CHECKING: 1abcdefghijklsmnopqr

118 

119 def LazyClassAttribute(name: str, get_value: Callable[[], T]) -> T: ... 

120 

121else: 

122 

123 class LazyClassAttribute: 1abcdefghijklsmnopqr

124 """A descriptor exposing an attribute only accessible on a class (hidden from instances). 

125 

126 The attribute is lazily computed and cached during the first access. 

127 """ 

128 

129 def __init__(self, name: str, get_value: Callable[[], Any]) -> None: 1abcdefghijklsmnopqr

130 self.name = name 1abcdefghijklsmnopqr

131 self.get_value = get_value 1abcdefghijklsmnopqr

132 

133 @cached_property 1abcdefghijklsmnopqr

134 def value(self) -> Any: 1abcdefghijklsmnopqr

135 return self.get_value() 1abcdefghijklmnopqr

136 

137 def __get__(self, instance: Any, owner: type[Any]) -> Any: 1abcdefghijklsmnopqr

138 if instance is None: 1abcdefghijklmnopqr

139 return self.value 1abcdefghijklmnopqr

140 raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only') 1abcdefghijklmnopqr

141 

142 

143Obj = TypeVar('Obj') 1abcdefghijklsmnopqr

144 

145 

146def smart_deepcopy(obj: Obj) -> Obj: 1abcdefghijklsmnopqr

147 """Return type as is for immutable built-in types 

148 Use obj.copy() for built-in empty collections 

149 Use copy.deepcopy() for non-empty collections and unknown objects. 

150 """ 

151 if obj is MISSING or obj is PydanticUndefined: 1abcdefghijklmnopqr

152 return obj # pyright: ignore[reportReturnType] 1abcdefghijklmnopqr

153 obj_type = obj.__class__ 1abcdefghijklmnopqr

154 if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES: 1abcdefghijklmnopqr

155 return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway 1abcdefghijklmnopqr

156 try: 1abcdefghijklmnopqr

157 if not obj and obj_type in BUILTIN_COLLECTIONS: 1abcdefghijklmnopqr

158 # faster way for empty collections, no need to copy its members 

159 return obj if obj_type is tuple else obj.copy() # tuple doesn't have copy method # type: ignore 1abcdefghijklmnopqr

160 except (TypeError, ValueError, RuntimeError): 1abcdefghijklmnopqr

161 # do we really dare to catch ALL errors? Seems a bit risky 

162 pass 1abcdefghijklmnopqr

163 

164 return deepcopy(obj) # slowest way when we actually might need a deepcopy 1abcdefghijklmnopqr

165 

166 

167_SENTINEL = object() 1abcdefghijklsmnopqr

168 

169 

170def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool: 1abcdefghijklsmnopqr

171 """Check that the items of `left` are the same objects as those in `right`. 

172 

173 >>> a, b = object(), object() 

174 >>> all_identical([a, b, a], [a, b, a]) 

175 True 

176 >>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical" 

177 False 

178 """ 

179 for left_item, right_item in zip_longest(left, right, fillvalue=_SENTINEL): 1abcdefghijklsmnopqr

180 if left_item is not right_item: 1abcdefghijklsmnopqr

181 return False 1abcdefghijklsmnopqr

182 return True 1abcdefghijklsmnopqr

183 

184 

185def get_first_not_none(a: Any, b: Any) -> Any: 1abcdefghijklsmnopqr

186 """Return the first argument if it is not `None`, otherwise return the second argument.""" 

187 return a if a is not None else b 1abcdefghijklmnopqr

188 

189 

190@dataclasses.dataclass(frozen=True, slots=True) 1abcdefghijklsmnopqr

191class SafeGetItemProxy: 1abcdefghijklsmnopqr

192 """Wrapper redirecting `__getitem__` to `get` with a sentinel value as default 

193 

194 This makes it safe to use in `operator.itemgetter` when some keys may be missing 

195 """ 

196 

197 wrapped: Mapping[str, Any] 1abcdefghijklsmnopqr

198 

199 def __getitem__(self, key: str, /) -> Any: 1abcdefghijklsmnopqr

200 return self.wrapped.get(key, _SENTINEL) 1abcdefghijklmnopqr

201 

202 # required to pass the object to operator.itemgetter() instances due to a quirk of typeshed 

203 # https://github.com/python/mypy/issues/13713 

204 # https://github.com/python/typeshed/pull/8785 

205 # Since this is typing-only, hide it in a typing.TYPE_CHECKING block 

206 if TYPE_CHECKING: 1abcdefghijklsmnopqr

207 

208 def __contains__(self, key: str, /) -> bool: 

209 return self.wrapped.__contains__(key)