Coverage for pydantic / _internal / _decorators.py: 97.96%

316 statements  

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

1"""Logic related to validators applied to models etc. via the `@field_validator` and `@model_validator` decorators.""" 

2 

3from __future__ import annotations as _annotations 1abghijcdklmnsefopqr

4 

5import types 1abghijcdklmnsefopqr

6from collections import deque 1abghijcdklmnsefopqr

7from collections.abc import Callable, Iterable 1abghijcdklmnsefopqr

8from copy import copy 1abghijcdklmnsefopqr

9from dataclasses import dataclass, field 1abghijcdklmnsefopqr

10from functools import cached_property, partial, partialmethod 1abghijcdklmnsefopqr

11from inspect import Parameter, Signature, isdatadescriptor, ismethoddescriptor 1abghijcdklmnsefopqr

12from itertools import islice 1abghijcdklmnsefopqr

13from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, Self, TypeAlias, TypeVar 1abghijcdklmnsefopqr

14 

15from pydantic_core import PydanticUndefined, PydanticUndefinedType, core_schema 1abghijcdklmnsefopqr

16from typing_extensions import TypeForm, is_typeddict 1abghijcdklmnsefopqr

17 

18from ..errors import PydanticUserError 1abghijcdklmnsefopqr

19from . import _type_refs 1abghijcdklmnsefopqr

20from ._namespace_utils import GlobalsNamespace, MappingNamespace 1abghijcdklmnsefopqr

21from ._typing_extra import get_function_type_hints, signature_no_eval 1abghijcdklmnsefopqr

22from ._utils import can_be_positional 1abghijcdklmnsefopqr

23 

24if TYPE_CHECKING: 1abghijcdklmnsefopqr

25 from ..fields import ComputedFieldInfo 

26 from ..functional_validators import FieldValidatorModes 

27 from ._config import ConfigWrapper 

28 

29 

30@dataclass(slots=True) 1abghijcdklmnsefopqr

31class FieldValidatorDecoratorInfo: 1abghijcdklmnsefopqr

32 """A container for data from `@field_validator` so that we can access it 

33 while building the pydantic-core schema. 

34 

35 Attributes: 

36 decorator_repr: A class variable representing the decorator string, '@field_validator'. 

37 fields: A tuple of field names the validator should be called on. 

38 mode: The proposed validator mode. 

39 check_fields: Whether to check that the fields actually exist on the model. 

40 json_schema_input_type: The input type of the function. This is only used to generate 

41 the appropriate JSON Schema (in validation mode) and can only specified 

42 when `mode` is either `'before'`, `'plain'` or `'wrap'`. 

43 """ 

44 

45 decorator_repr: ClassVar[str] = '@field_validator' 1abghijcdklmnsefopqr

46 

47 fields: tuple[str, ...] 1abghijcdklmnsefopqr

48 mode: FieldValidatorModes 1abghijcdklmnsefopqr

49 check_fields: bool | None 1abghijcdklmnsefopqr

50 json_schema_input_type: Any 1abghijcdklmnsefopqr

51 

52 

53@dataclass(slots=True) 1abghijcdklmnsefopqr

54class FieldSerializerDecoratorInfo: 1abghijcdklmnsefopqr

55 """A container for data from `@field_serializer` so that we can access it 

56 while building the pydantic-core schema. 

57 

58 Attributes: 

59 decorator_repr: A class variable representing the decorator string, '@field_serializer'. 

60 fields: A tuple of field names the serializer should be called on. 

61 mode: The proposed serializer mode. 

62 return_type: The type of the serializer's return value. 

63 when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, 

64 and `'json-unless-none'`. 

65 check_fields: Whether to check that the fields actually exist on the model. 

66 """ 

67 

68 decorator_repr: ClassVar[str] = '@field_serializer' 1abghijcdklmnsefopqr

69 fields: tuple[str, ...] 1abghijcdklmnsefopqr

70 mode: Literal['plain', 'wrap'] 1abghijcdklmnsefopqr

71 return_type: TypeForm[Any] 1abghijcdklmnsefopqr

72 when_used: core_schema.WhenUsed 1abghijcdklmnsefopqr

73 check_fields: bool | None 1abghijcdklmnsefopqr

74 

75 

76@dataclass(slots=True) 1abghijcdklmnsefopqr

77class ModelSerializerDecoratorInfo: 1abghijcdklmnsefopqr

78 """A container for data from `@model_serializer` so that we can access it 

79 while building the pydantic-core schema. 

80 

81 Attributes: 

82 decorator_repr: A class variable representing the decorator string, '@model_serializer'. 

83 mode: The proposed serializer mode. 

84 return_type: The type of the serializer's return value. 

85 when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, 

86 and `'json-unless-none'`. 

87 """ 

88 

89 decorator_repr: ClassVar[str] = '@model_serializer' 1abghijcdklmnsefopqr

90 mode: Literal['plain', 'wrap'] 1abghijcdklmnsefopqr

91 return_type: TypeForm[Any] 1abghijcdklmnsefopqr

92 when_used: core_schema.WhenUsed 1abghijcdklmnsefopqr

93 

94 

95@dataclass(slots=True) 1abghijcdklmnsefopqr

96class ModelValidatorDecoratorInfo: 1abghijcdklmnsefopqr

97 """A container for data from `@model_validator` so that we can access it 

98 while building the pydantic-core schema. 

99 

100 Attributes: 

101 decorator_repr: A class variable representing the decorator string, '@model_validator'. 

102 mode: The proposed serializer mode. 

103 """ 

104 

105 decorator_repr: ClassVar[str] = '@model_validator' 1abghijcdklmnsefopqr

106 mode: Literal['wrap', 'before', 'after'] 1abghijcdklmnsefopqr

107 

108 

109DecoratorInfo: TypeAlias = 'FieldValidatorDecoratorInfo | FieldSerializerDecoratorInfo | ModelSerializerDecoratorInfo | ModelValidatorDecoratorInfo | ComputedFieldInfo' 1abghijcdklmnsefopqr

110 

111ReturnType = TypeVar('ReturnType') 1abghijcdklmnsefopqr

112DecoratedType: TypeAlias = ( 1abghijcdklmnsefopqr

113 'classmethod[Any, Any, ReturnType] | staticmethod[Any, ReturnType] | Callable[..., ReturnType] | property' 

114) 

115 

116 

117@dataclass # can't use slots here since we set attributes on `__post_init__` 1abghijcdklmnsefopqr

118class PydanticDescriptorProxy(Generic[ReturnType]): 1abghijcdklmnsefopqr

119 """Wrap a classmethod, staticmethod, property or unbound function 

120 and act as a descriptor that allows us to detect decorated items 

121 from the class' attributes. 

122 

123 This class' __get__ returns the wrapped item's __get__ result, 

124 which makes it transparent for classmethods and staticmethods. 

125 

126 Attributes: 

127 wrapped: The decorator that has to be wrapped. 

128 decorator_info: The decorator info. 

129 """ 

130 

131 wrapped: DecoratedType[ReturnType] 1abghijcdklmnsefopqr

132 decorator_info: DecoratorInfo 1abghijcdklmnsefopqr

133 

134 def __post_init__(self): 1abghijcdklmnsefopqr

135 for attr in 'setter', 'deleter': 1abghijcdklmnsefopqr

136 if hasattr(self.wrapped, attr): 1abghijcdklmnsefopqr

137 f = partial(self._call_wrapped_attr, name=attr) 1abghijcdklmnefopqr

138 setattr(self, attr, f) 1abghijcdklmnefopqr

139 

140 def _call_wrapped_attr(self, func: Callable[[Any], None], *, name: str) -> PydanticDescriptorProxy[ReturnType]: 1abghijcdklmnsefopqr

141 self.wrapped = getattr(self.wrapped, name)(func) 1abghijcdklmnefopqr

142 if isinstance(self.wrapped, property): 142 ↛ 148line 142 didn't jump to line 148 because the condition on line 142 was always true1abghijcdklmnefopqr

143 # update ComputedFieldInfo.wrapped_property 

144 from ..fields import ComputedFieldInfo 1abghijcdklmnefopqr

145 

146 if isinstance(self.decorator_info, ComputedFieldInfo): 146 ↛ 148line 146 didn't jump to line 148 because the condition on line 146 was always true1abghijcdklmnefopqr

147 self.decorator_info.wrapped_property = self.wrapped 1abghijcdklmnefopqr

148 return self 1abghijcdklmnefopqr

149 

150 def __get__(self, obj: object | None, obj_type: type[object] | None = None) -> PydanticDescriptorProxy[ReturnType]: 1abghijcdklmnsefopqr

151 try: 1abghijcdklmnsefopqr

152 return self.wrapped.__get__(obj, obj_type) # pyright: ignore[reportReturnType] 1abghijcdklmnsefopqr

153 except AttributeError: 1abcdef

154 # not a descriptor, e.g. a partial object 

155 return self.wrapped # type: ignore[return-value] 1abcdef

156 

157 def __set_name__(self, instance: Any, name: str) -> None: 1abghijcdklmnsefopqr

158 if hasattr(self.wrapped, '__set_name__'): 1abghijcdklmnsefopqr

159 self.wrapped.__set_name__(instance, name) # pyright: ignore[reportFunctionMemberAccess] 1abghijcdklmnefopqr

160 

161 def __getattr__(self, name: str, /) -> Any: 1abghijcdklmnsefopqr

162 """Forward checks for __isabstractmethod__ and such.""" 

163 return getattr(self.wrapped, name) 1abghijcdklmnsefopqr

164 

165 

166DecoratorInfoType = TypeVar('DecoratorInfoType', bound=DecoratorInfo) 1abghijcdklmnsefopqr

167 

168 

169@dataclass(slots=True) 1abghijcdklmnsefopqr

170class Decorator(Generic[DecoratorInfoType]): 1abghijcdklmnsefopqr

171 """A generic container class to join together the decorator metadata 

172 (metadata from decorator itself, which we have when the 

173 decorator is called but not when we are building the core-schema) 

174 and the bound function (which we have after the class itself is created). 

175 

176 Attributes: 

177 cls_ref: The class ref. 

178 cls_var_name: The decorated function name. 

179 func: The decorated function. 

180 info: The decorator info. 

181 """ 

182 

183 cls_ref: str 1abghijcdklmnsefopqr

184 cls_var_name: str 1abghijcdklmnsefopqr

185 func: Callable[..., Any] 1abghijcdklmnsefopqr

186 info: DecoratorInfoType 1abghijcdklmnsefopqr

187 

188 @staticmethod 1abghijcdklmnsefopqr

189 def build( 1abghijcdklmnsefopqr

190 cls_: Any, 

191 *, 

192 cls_var_name: str, 

193 cls_ref: str, 

194 info: DecoratorInfoType, 

195 ) -> Decorator[DecoratorInfoType]: 

196 """Build a new decorator. 

197 

198 Args: 

199 cls_: The class. 

200 cls_ref: The type ref of the class. 

201 cls_var_name: The decorated function name. 

202 info: The decorator info. 

203 

204 Returns: 

205 The new decorator instance. 

206 """ 

207 func = get_attribute_from_bases(cls_, cls_var_name) 1abghijcdklmnsefopqr

208 func = unwrap_wrapped_function(func, unwrap_partial=False) 1abghijcdklmnsefopqr

209 if not callable(func): 1abghijcdklmnsefopqr

210 # TODO most likely this branch can be removed when we drop support for Python 3.12: 

211 # This branch will get hit for classmethod properties 

212 attribute = get_attribute_from_base_dicts(cls_, cls_var_name) # prevents the binding call to `__get__` 1abcdef

213 if isinstance(attribute, PydanticDescriptorProxy): 213 ↛ 215line 213 didn't jump to line 215 because the condition on line 213 was always true1abcdef

214 func = unwrap_wrapped_function(attribute.wrapped) 1abcdef

215 return Decorator( 1abghijcdklmnsefopqr

216 cls_ref=cls_ref, 

217 cls_var_name=cls_var_name, 

218 func=func, 

219 info=info, 

220 ) 

221 

222 def bind_to_cls(self, cls: Any, cls_ref: str) -> Decorator[DecoratorInfoType]: 1abghijcdklmnsefopqr

223 """Bind the decorator to a class. 

224 

225 Args: 

226 cls: the class. 

227 cls_ref: The type ref of the class. 

228 

229 Returns: 

230 The new decorator instance. 

231 """ 

232 return self.build( 1abghijcdklmnefopqr

233 cls, 

234 cls_ref=cls_ref, 

235 cls_var_name=self.cls_var_name, 

236 info=copy(self.info), 

237 ) 

238 

239 

240def get_bases(tp: type[Any]) -> tuple[type[Any], ...]: 1abghijcdklmnsefopqr

241 """Get the base classes of a class or typeddict. 

242 

243 Args: 

244 tp: The type or class to get the bases. 

245 

246 Returns: 

247 The base classes. 

248 """ 

249 if is_typeddict(tp): 1abghijcdklmnefopqr

250 return tp.__orig_bases__ # type: ignore 1abghijcdklmnefopqr

251 try: 1abghijcdklmnefopqr

252 return tp.__bases__ 1abghijcdklmnefopqr

253 except AttributeError: 1abghijcdklmnefopqr

254 return () 1abghijcdklmnefopqr

255 

256 

257def mro(tp: type[Any]) -> tuple[type[Any], ...]: 1abghijcdklmnsefopqr

258 """Calculate the Method Resolution Order of bases using the C3 algorithm. 

259 

260 See https://www.python.org/download/releases/2.3/mro/ 

261 """ 

262 # try to use the existing mro, for performance mainly 

263 # but also because it helps verify the implementation below 

264 if not is_typeddict(tp): 1abghijcdklmnsefopqr

265 try: 1abghijcdklmnsefopqr

266 return tp.__mro__ 1abghijcdklmnsefopqr

267 except AttributeError: 1abghijcdklmnefopqr

268 # GenericAlias and some other cases 

269 pass 1abghijcdklmnefopqr

270 

271 bases = get_bases(tp) 1abghijcdklmnefopqr

272 return (tp,) + mro_for_bases(bases) 1abghijcdklmnefopqr

273 

274 

275def mro_for_bases(bases: tuple[type[Any], ...]) -> tuple[type[Any], ...]: 1abghijcdklmnsefopqr

276 def merge_seqs(seqs: list[deque[type[Any]]]) -> Iterable[type[Any]]: 1abghijcdklmnsefopqr

277 while True: 1abghijcdklmnsefopqr

278 non_empty = [seq for seq in seqs if seq] 1abghijcdklmnsefopqr

279 if not non_empty: 1abghijcdklmnsefopqr

280 # Nothing left to process, we're done. 

281 return 1abghijcdklmnsefopqr

282 candidate: type[Any] | None = None 1abghijcdklmnsefopqr

283 for seq in non_empty: # Find merge candidates among seq heads. 283 ↛ 291line 283 didn't jump to line 291 because the loop on line 283 didn't complete1abghijcdklmnsefopqr

284 candidate = seq[0] 1abghijcdklmnsefopqr

285 not_head = [s for s in non_empty if candidate in islice(s, 1, None)] 1abghijcdklmnsefopqr

286 if not_head: 1abghijcdklmnsefopqr

287 # Reject the candidate. 

288 candidate = None 1abghijcdklmnefopqr

289 else: 

290 break 1abghijcdklmnsefopqr

291 if not candidate: 291 ↛ 292line 291 didn't jump to line 292 because the condition on line 291 was never true1abghijcdklmnsefopqr

292 raise TypeError('Inconsistent hierarchy, no C3 MRO is possible') 

293 yield candidate 1abghijcdklmnsefopqr

294 for seq in non_empty: 1abghijcdklmnsefopqr

295 # Remove candidate. 

296 if seq[0] == candidate: 1abghijcdklmnsefopqr

297 seq.popleft() 1abghijcdklmnsefopqr

298 

299 seqs = [deque(mro(base)) for base in bases] + [deque(bases)] 1abghijcdklmnsefopqr

300 return tuple(merge_seqs(seqs)) 1abghijcdklmnsefopqr

301 

302 

303_sentinel = object() 1abghijcdklmnsefopqr

304 

305 

306def get_attribute_from_bases(tp: type[Any] | tuple[type[Any], ...], name: str) -> Any: 1abghijcdklmnsefopqr

307 """Get the attribute from the next class in the MRO that has it, 

308 aiming to simulate calling the method on the actual class. 

309 

310 The reason for iterating over the mro instead of just getting 

311 the attribute (which would do that for us) is to support TypedDict, 

312 which lacks a real __mro__, but can have a virtual one constructed 

313 from its bases (as done here). 

314 

315 Args: 

316 tp: The type or class to search for the attribute. If a tuple, this is treated as a set of base classes. 

317 name: The name of the attribute to retrieve. 

318 

319 Returns: 

320 Any: The attribute value, if found. 

321 

322 Raises: 

323 AttributeError: If the attribute is not found in any class in the MRO. 

324 """ 

325 if isinstance(tp, tuple): 1abghijcdklmnsefopqr

326 for base in mro_for_bases(tp): 1abghijcdklmnsefopqr

327 attribute = base.__dict__.get(name, _sentinel) 1abghijcdklmnsefopqr

328 if attribute is not _sentinel: 1abghijcdklmnsefopqr

329 attribute_get = getattr(attribute, '__get__', None) 1abghijcdklmnsefopqr

330 if attribute_get is not None: 1abghijcdklmnsefopqr

331 return attribute_get(None, tp) 1abghijcdklmnefopqr

332 return attribute 1abghijcdklmnsefopqr

333 raise AttributeError(f'{name} not found in {tp}') 1abghijcdklmnefopqr

334 else: 

335 try: 1abghijcdklmnsefopqr

336 return getattr(tp, name) 1abghijcdklmnsefopqr

337 except AttributeError: 1abghijcdklmnefopqr

338 return get_attribute_from_bases(mro(tp), name) 1abghijcdklmnefopqr

339 

340 

341def get_attribute_from_base_dicts(tp: type[Any], name: str) -> Any: 1abghijcdklmnsefopqr

342 """Get an attribute out of the `__dict__` following the MRO. 

343 This prevents the call to `__get__` on the descriptor, and allows 

344 us to get the original function for classmethod properties. 

345 

346 Args: 

347 tp: The type or class to search for the attribute. 

348 name: The name of the attribute to retrieve. 

349 

350 Returns: 

351 Any: The attribute value, if found. 

352 

353 Raises: 

354 KeyError: If the attribute is not found in any class's `__dict__` in the MRO. 

355 """ 

356 for base in reversed(mro(tp)): 356 ↛ 359line 356 didn't jump to line 359 because the loop on line 356 didn't complete1abcdef

357 if name in base.__dict__: 1abcdef

358 return base.__dict__[name] 1abcdef

359 return tp.__dict__[name] # raise the error 

360 

361 

362@dataclass(slots=True) 1abghijcdklmnsefopqr

363class DecoratorInfos: 1abghijcdklmnsefopqr

364 """Mapping of name in the class namespace to decorator info. 

365 

366 note that the name in the class namespace is the function or attribute name 

367 not the field name! 

368 """ 

369 

370 field_validators: dict[str, Decorator[FieldValidatorDecoratorInfo]] = field(default_factory=dict) 1abghijcdklmnsefopqr

371 field_serializers: dict[str, Decorator[FieldSerializerDecoratorInfo]] = field(default_factory=dict) 1abghijcdklmnsefopqr

372 model_serializers: dict[str, Decorator[ModelSerializerDecoratorInfo]] = field(default_factory=dict) 1abghijcdklmnsefopqr

373 model_validators: dict[str, Decorator[ModelValidatorDecoratorInfo]] = field(default_factory=dict) 1abghijcdklmnsefopqr

374 computed_fields: dict[str, Decorator[ComputedFieldInfo]] = field(default_factory=dict) 1abghijcdklmnsefopqr

375 

376 @classmethod 1abghijcdklmnsefopqr

377 def build( 1abghijcdklmnsefopqr

378 cls, 

379 typ: type[Any], 

380 # Default to `True` for backwards compatibility: 

381 replace_wrapped_methods: bool = True, 

382 ) -> Self: 

383 """Build a `DecoratorInfos` instance for the given model, dataclass or `TypedDict` type. 

384 

385 Decorators from parent classes are included, including "bare" classes (e.g. if `typ` 

386 is a Pydantic model, non Pydantic parent model classes are also taken into account). 

387 The collection of the decorators happens by respecting the MRO. 

388 

389 If one of the bases has an `__pydantic_decorators__` attribute set, it is assumed to be 

390 a `DecoratorInfos` instance and is used as-is. The `__pydantic_decorators__` attribute 

391 is *not* being set on the provided `typ`. 

392 

393 Args: 

394 typ: The model, dataclass or `TypedDict` type to use when building the `DecoratorInfos` instance. 

395 replace_wrapped_methods: Whether to replace the decorator's wrapped methods on `typ`. 

396 This is useful e.g. for field validators which are initially class methods. This should 

397 only be set to `True` if `typ` is a Pydantic model or dataclass (otherwise this results 

398 in mutations of classes Pydantic doesn't "own"). 

399 """ 

400 # reminder: dicts are ordered and replacement does not alter the order 

401 res = cls() 1abghijcdklmnsefopqr

402 

403 type_ref: str | None = None 1abghijcdklmnsefopqr

404 

405 def cls_ref() -> str: 1abghijcdklmnsefopqr

406 # The type ref is only required if at least one decorator is collected, 

407 # so only compute it lazily (and only once): 

408 nonlocal type_ref 

409 if type_ref is None: 1abghijcdklmnsefopqr

410 type_ref = _type_refs.any_class_type_ref(typ) 1abghijcdklmnsefopqr

411 return type_ref 1abghijcdklmnsefopqr

412 

413 # Iterate over the bases, without the actual `typ`. 

414 # `1:-1` because we don't need to include `object`/`TypedDict`: 

415 for base in reversed(mro(typ)[1:-1]): 1abghijcdklmnsefopqr

416 existing: DecoratorInfos | None = base.__dict__.get('__pydantic_decorators__') 1abghijcdklmnsefopqr

417 if existing is None: 1abghijcdklmnsefopqr

418 existing, _ = _decorator_infos_for_class( 1abghijcdklmnsefopqr

419 base, 

420 # The class refs of the built decorators are irrelevant here, as `bind_to_cls()` 

421 # below rebinds every decorator to `typ` with the correct ref: 

422 cls_ref=lambda: '', 

423 collect_to_replace=False, 

424 ) 

425 res.field_validators.update( 1abghijcdklmnsefopqr

426 {k: v.bind_to_cls(typ, cls_ref()) for k, v in existing.field_validators.items()} 

427 ) 

428 res.field_serializers.update( 1abghijcdklmnsefopqr

429 {k: v.bind_to_cls(typ, cls_ref()) for k, v in existing.field_serializers.items()} 

430 ) 

431 res.model_serializers.update( 1abghijcdklmnsefopqr

432 {k: v.bind_to_cls(typ, cls_ref()) for k, v in existing.model_serializers.items()} 

433 ) 

434 res.model_validators.update( 1abghijcdklmnsefopqr

435 {k: v.bind_to_cls(typ, cls_ref()) for k, v in existing.model_validators.items()} 

436 ) 

437 res.computed_fields.update({k: v.bind_to_cls(typ, cls_ref()) for k, v in existing.computed_fields.items()}) 1abghijcdklmnsefopqr

438 

439 decorator_infos, to_replace = _decorator_infos_for_class(typ, cls_ref=cls_ref, collect_to_replace=True) 1abghijcdklmnsefopqr

440 

441 res.field_validators.update(decorator_infos.field_validators) 1abghijcdklmnsefopqr

442 res.field_serializers.update(decorator_infos.field_serializers) 1abghijcdklmnsefopqr

443 res.model_serializers.update(decorator_infos.model_serializers) 1abghijcdklmnsefopqr

444 res.model_validators.update(decorator_infos.model_validators) 1abghijcdklmnsefopqr

445 res.computed_fields.update(decorator_infos.computed_fields) 1abghijcdklmnsefopqr

446 

447 if replace_wrapped_methods and to_replace: 1abghijcdklmnsefopqr

448 for name, value in to_replace: 1abghijcdklmnsefopqr

449 setattr(typ, name, value) 1abghijcdklmnsefopqr

450 

451 res._validate() 1abghijcdklmnsefopqr

452 return res 1abghijcdklmnsefopqr

453 

454 def _validate(self) -> None: 1abghijcdklmnsefopqr

455 seen: set[str] = set() 1abghijcdklmnsefopqr

456 for field_ser in self.field_serializers.values(): 1abghijcdklmnsefopqr

457 for f_name in field_ser.info.fields: 1abghijcdklmnefopqr

458 if f_name in seen: 1abghijcdklmnefopqr

459 raise PydanticUserError( 1abghijcdklmnefopqr

460 f'Multiple field serializer functions were defined for field {f_name!r}, this is not allowed.', 

461 code='multiple-field-serializers', 

462 ) 

463 seen.add(f_name) 1abghijcdklmnefopqr

464 

465 def update_from_config(self, config_wrapper: ConfigWrapper) -> None: 1abghijcdklmnsefopqr

466 """Update the decorator infos from the configuration of the class they are attached to.""" 

467 for name, computed_field_dec in self.computed_fields.items(): 1abghijcdklmnsefopqr

468 computed_field_dec.info._update_from_config(config_wrapper, name) 1abghijcdklmnefopqr

469 

470 

471def _decorator_infos_for_class( 1abghijcdklmnsefopqr

472 typ: type[Any], 

473 *, 

474 cls_ref: Callable[[], str], 

475 collect_to_replace: bool, 

476) -> tuple[DecoratorInfos, list[tuple[str, Any]]]: 

477 """Collect a `DecoratorInfos` for class, without looking into bases.""" 

478 res = DecoratorInfos() 1abghijcdklmnsefopqr

479 to_replace: list[tuple[str, Any]] = [] 1abghijcdklmnsefopqr

480 

481 # Iterate on the vars with a copy to avoid changes in dictionary size during iteration. 

482 # This can happen if a concurrent thread has Pydantic processing the same `typ` (e.g. two 

483 # concurrent threads doing `TypeAdapter(SomeClassType)`), and such thread reads annotations 

484 # for the first time during the iteration here in the other thread (since 3.14, reading annotations 

485 # can set attributes such as `__annotations_cache__` or `__annotate_func__` to the type). 

486 for var_name, var_value in vars(typ).copy().items(): 1abghijcdklmnsefopqr

487 if isinstance(var_value, PydanticDescriptorProxy): 1abghijcdklmnsefopqr

488 info = var_value.decorator_info 1abghijcdklmnsefopqr

489 if isinstance(info, FieldValidatorDecoratorInfo): 1abghijcdklmnsefopqr

490 res.field_validators[var_name] = Decorator.build( 1abghijcdklmnsefopqr

491 typ, cls_ref=cls_ref(), cls_var_name=var_name, info=info 

492 ) 

493 elif isinstance(info, FieldSerializerDecoratorInfo): 1abghijcdklmnefopqr

494 res.field_serializers[var_name] = Decorator.build( 1abghijcdklmnefopqr

495 typ, cls_ref=cls_ref(), cls_var_name=var_name, info=info 

496 ) 

497 elif isinstance(info, ModelValidatorDecoratorInfo): 1abghijcdklmnefopqr

498 res.model_validators[var_name] = Decorator.build( 1abghijcdklmnefopqr

499 typ, cls_ref=cls_ref(), cls_var_name=var_name, info=info 

500 ) 

501 elif isinstance(info, ModelSerializerDecoratorInfo): 1abghijcdklmnefopqr

502 res.model_serializers[var_name] = Decorator.build( 1abghijcdklmnefopqr

503 typ, cls_ref=cls_ref(), cls_var_name=var_name, info=info 

504 ) 

505 else: 

506 from ..fields import ComputedFieldInfo 1abghijcdklmnefopqr

507 

508 assert isinstance(info, ComputedFieldInfo) 1abghijcdklmnefopqr

509 res.computed_fields[var_name] = Decorator.build( 1abghijcdklmnefopqr

510 typ, cls_ref=cls_ref(), cls_var_name=var_name, info=info 

511 ) 

512 if collect_to_replace: 1abghijcdklmnsefopqr

513 to_replace.append((var_name, var_value.wrapped)) 1abghijcdklmnsefopqr

514 

515 return res, to_replace 1abghijcdklmnsefopqr

516 

517 

518def inspect_validator( 1abghijcdklmnsefopqr

519 validator: Callable[..., Any], *, mode: FieldValidatorModes, type: Literal['field', 'model'] 

520) -> bool: 

521 """Look at a field or model validator function and determine whether it takes an info argument. 

522 

523 An error is raised if the function has an invalid signature. 

524 

525 Args: 

526 validator: The validator function to inspect. 

527 mode: The proposed validator mode. 

528 type: The type of validator, either 'field' or 'model'. 

529 

530 Returns: 

531 Whether the validator takes an info argument. 

532 """ 

533 try: 1abghijcdklmnsefopqr

534 sig = signature_no_eval(validator) 1abghijcdklmnsefopqr

535 except (ValueError, TypeError): 1abghijcdklmnefopqr

536 # `inspect.signature` might not be able to infer a signature, e.g. with C objects. 

537 # In this case, we assume no info argument is present: 

538 return False 1abghijcdklmnefopqr

539 n_positional = count_positional_required_params(sig) 1abghijcdklmnsefopqr

540 if mode == 'wrap': 1abghijcdklmnsefopqr

541 if n_positional == 3: 1abghijcdklmnefopqr

542 return True 1abghijcdklmnefopqr

543 elif n_positional == 2: 1abghijcdklmnefopqr

544 return False 1abghijcdklmnefopqr

545 else: 

546 assert mode in {'before', 'after', 'plain'}, f"invalid mode: {mode!r}, expected 'before', 'after' or 'plain" 1abghijcdklmnsefopqr

547 if n_positional == 2: 1abghijcdklmnsefopqr

548 return True 1abghijcdklmnefopqr

549 elif n_positional == 1: 1abghijcdklmnsefopqr

550 return False 1abghijcdklmnsefopqr

551 

552 raise PydanticUserError( 1abghijcdklmnefopqr

553 f'Unrecognized {type} validator function signature for {validator} with `mode={mode}`: {sig}', 

554 code='validator-signature', 

555 ) 

556 

557 

558def inspect_field_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> tuple[bool, bool]: 1abghijcdklmnsefopqr

559 """Look at a field serializer function and determine if it is a field serializer, 

560 and whether it takes an info argument. 

561 

562 An error is raised if the function has an invalid signature. 

563 

564 Args: 

565 serializer: The serializer function to inspect. 

566 mode: The serializer mode, either 'plain' or 'wrap'. 

567 

568 Returns: 

569 Tuple of (is_field_serializer, info_arg). 

570 """ 

571 try: 1abghijcdklmnefopqr

572 sig = signature_no_eval(serializer) 1abghijcdklmnefopqr

573 except (ValueError, TypeError): 1abghijcdklmnefopqr

574 # `inspect.signature` might not be able to infer a signature, e.g. with C objects. 

575 # In this case, we assume no info argument is present and this is not a method: 

576 return (False, False) 1abghijcdklmnefopqr

577 

578 first = next(iter(sig.parameters.values()), None) 1abghijcdklmnefopqr

579 is_field_serializer = first is not None and first.name == 'self' 1abghijcdklmnefopqr

580 

581 n_positional = count_positional_required_params(sig) 1abghijcdklmnefopqr

582 if is_field_serializer: 1abghijcdklmnefopqr

583 # -1 to correct for self parameter 

584 info_arg = _serializer_info_arg(mode, n_positional - 1) 1abghijcdklmnefopqr

585 else: 

586 info_arg = _serializer_info_arg(mode, n_positional) 1abghijcdklmnefopqr

587 

588 if info_arg is None: 1abghijcdklmnefopqr

589 raise PydanticUserError( 1abghijcdklmnefopqr

590 f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}', 

591 code='field-serializer-signature', 

592 ) 

593 

594 return is_field_serializer, info_arg 1abghijcdklmnefopqr

595 

596 

597def inspect_annotated_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool: 1abghijcdklmnsefopqr

598 """Look at a serializer function used via `Annotated` and determine whether it takes an info argument. 

599 

600 An error is raised if the function has an invalid signature. 

601 

602 Args: 

603 serializer: The serializer function to check. 

604 mode: The serializer mode, either 'plain' or 'wrap'. 

605 

606 Returns: 

607 info_arg 

608 """ 

609 try: 1abghijcdklmnefopqr

610 sig = signature_no_eval(serializer) 1abghijcdklmnefopqr

611 except (ValueError, TypeError): 1abghijcdklmnefopqr

612 # `inspect.signature` might not be able to infer a signature, e.g. with C objects. 

613 # In this case, we assume no info argument is present: 

614 return False 1abghijcdklmnefopqr

615 info_arg = _serializer_info_arg(mode, count_positional_required_params(sig)) 1abghijcdklmnefopqr

616 if info_arg is None: 1abghijcdklmnefopqr

617 raise PydanticUserError( 1abghijcdklmnefopqr

618 f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}', 

619 code='field-serializer-signature', 

620 ) 

621 else: 

622 return info_arg 1abghijcdklmnefopqr

623 

624 

625def inspect_model_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool: 1abghijcdklmnsefopqr

626 """Look at a model serializer function and determine whether it takes an info argument. 

627 

628 An error is raised if the function has an invalid signature. 

629 

630 Args: 

631 serializer: The serializer function to check. 

632 mode: The serializer mode, either 'plain' or 'wrap'. 

633 

634 Returns: 

635 `info_arg` - whether the function expects an info argument. 

636 """ 

637 if isinstance(serializer, (staticmethod, classmethod)) or not is_instance_method_from_sig(serializer): 1abghijcdklmnefopqr

638 raise PydanticUserError( 1abghijcdklmnefopqr

639 '`@model_serializer` must be applied to instance methods', code='model-serializer-instance-method' 

640 ) 

641 

642 sig = signature_no_eval(serializer) 1abghijcdklmnefopqr

643 info_arg = _serializer_info_arg(mode, count_positional_required_params(sig)) 1abghijcdklmnefopqr

644 if info_arg is None: 1abghijcdklmnefopqr

645 raise PydanticUserError( 1abghijcdklmnefopqr

646 f'Unrecognized model_serializer function signature for {serializer} with `mode={mode}`:{sig}', 

647 code='model-serializer-signature', 

648 ) 

649 else: 

650 return info_arg 1abghijcdklmnefopqr

651 

652 

653def _serializer_info_arg(mode: Literal['plain', 'wrap'], n_positional: int) -> bool | None: 1abghijcdklmnsefopqr

654 if mode == 'plain': 1abghijcdklmnefopqr

655 if n_positional == 1: 1abghijcdklmnefopqr

656 # (input_value: Any, /) -> Any 

657 return False 1abghijcdklmnefopqr

658 elif n_positional == 2: 1abghijcdklmnefopqr

659 # (model: Any, input_value: Any, /) -> Any 

660 return True 1abghijcdklmnefopqr

661 else: 

662 assert mode == 'wrap', f"invalid mode: {mode!r}, expected 'plain' or 'wrap'" 1abghijcdklmnefopqr

663 if n_positional == 2: 1abghijcdklmnefopqr

664 # (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any 

665 return False 1abghijcdklmnefopqr

666 elif n_positional == 3: 1abghijcdklmnefopqr

667 # (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any 

668 return True 1abghijcdklmnefopqr

669 

670 return None 1abghijcdklmnefopqr

671 

672 

673AnyDecoratorCallable: TypeAlias = ( 1abghijcdklmnsefopqr

674 'classmethod[Any, Any, Any] | staticmethod[Any, Any] | partialmethod[Any] | Callable[..., Any]' 

675) 

676 

677 

678def is_instance_method_from_sig(function: AnyDecoratorCallable) -> bool: 1abghijcdklmnsefopqr

679 """Whether the function is an instance method. 

680 

681 It will consider a function as instance method if the first parameter of 

682 function is `self`. 

683 

684 Args: 

685 function: The function to check. 

686 

687 Returns: 

688 `True` if the function is an instance method, `False` otherwise. 

689 """ 

690 sig = signature_no_eval(unwrap_wrapped_function(function)) 1abghijcdklmnsefopqr

691 first = next(iter(sig.parameters.values()), None) 1abghijcdklmnsefopqr

692 if first and first.name == 'self': 1abghijcdklmnsefopqr

693 return True 1abghijcdklmnefopqr

694 return False 1abghijcdklmnsefopqr

695 

696 

697def ensure_classmethod_based_on_signature(function: AnyDecoratorCallable) -> Any: 1abghijcdklmnsefopqr

698 """Apply the `@classmethod` decorator on the function. 

699 

700 Args: 

701 function: The function to apply the decorator on. 

702 

703 Return: 

704 The `@classmethod` decorator applied function. 

705 """ 

706 if not isinstance( 1abghijcdklmnsefopqr

707 unwrap_wrapped_function(function, unwrap_class_static_method=False), classmethod 

708 ) and _is_classmethod_from_sig(function): 

709 return classmethod(function) # type: ignore[arg-type] 1abghijcdklmnsefopqr

710 return function 1abghijcdklmnsefopqr

711 

712 

713def _is_classmethod_from_sig(function: AnyDecoratorCallable) -> bool: 1abghijcdklmnsefopqr

714 sig = signature_no_eval(unwrap_wrapped_function(function)) 1abghijcdklmnsefopqr

715 first = next(iter(sig.parameters.values()), None) 1abghijcdklmnsefopqr

716 if first and first.name == 'cls': 1abghijcdklmnsefopqr

717 return True 1abghijcdklmnsefopqr

718 return False 1abghijcdklmnsefopqr

719 

720 

721def unwrap_wrapped_function( 1abghijcdklmnsefopqr

722 func: Any, 

723 *, 

724 unwrap_partial: bool = True, 

725 unwrap_class_static_method: bool = True, 

726) -> Any: 

727 """Recursively unwraps a wrapped function until the underlying function is reached. 

728 This handles property, functools.partial, functools.partialmethod, staticmethod, and classmethod. 

729 

730 Args: 

731 func: The function to unwrap. 

732 unwrap_partial: If True (default), unwrap partial and partialmethod decorators. 

733 unwrap_class_static_method: If True (default), also unwrap classmethod and staticmethod 

734 decorators. If False, only unwrap partial and partialmethod decorators. 

735 

736 Returns: 

737 The underlying function of the wrapped function. 

738 """ 

739 # Define the types we want to check against as a single tuple. 

740 unwrap_types = ( 1abghijcdklmnsefopqr

741 (property, cached_property) 

742 + ((partial, partialmethod) if unwrap_partial else ()) 

743 + ((staticmethod, classmethod) if unwrap_class_static_method else ()) 

744 ) 

745 

746 while isinstance(func, unwrap_types): 1abghijcdklmnsefopqr

747 if unwrap_class_static_method and isinstance(func, (classmethod, staticmethod)): 1abghijcdklmnefopqr

748 func = func.__func__ 1abghijcdklmnefopqr

749 elif isinstance(func, (partial, partialmethod)): 1abghijcdklmnefopqr

750 func = func.func 1abghijcdklmnefopqr

751 elif isinstance(func, property): 1abghijcdklmnefopqr

752 func = func.fget # arbitrary choice, convenient for computed fields 1abghijcdklmnefopqr

753 else: 

754 # Make coverage happy as it can only get here in the last possible case 

755 assert isinstance(func, cached_property) 1abghijcdklmnefopqr

756 func = func.func # type: ignore 1abghijcdklmnefopqr

757 

758 return func 1abghijcdklmnsefopqr

759 

760 

761_function_like = ( 1abghijcdklmnsefopqr

762 partial, 

763 partialmethod, 

764 types.FunctionType, 

765 types.BuiltinFunctionType, 

766 types.MethodType, 

767 types.WrapperDescriptorType, 

768 types.MethodWrapperType, 

769 types.MemberDescriptorType, 

770) 

771 

772 

773def get_callable_return_type( 1abghijcdklmnsefopqr

774 callable_obj: Any, 

775 globalns: GlobalsNamespace | None = None, 

776 localns: MappingNamespace | None = None, 

777) -> Any | PydanticUndefinedType: 

778 """Get the callable return type. 

779 

780 Args: 

781 callable_obj: The callable to analyze. 

782 globalns: The globals namespace to use during type annotation evaluation. 

783 localns: The locals namespace to use during type annotation evaluation. 

784 

785 Returns: 

786 The function return type. 

787 """ 

788 if isinstance(callable_obj, type): 1abghijcdklmnefopqr

789 # types are callables, and we assume the return type 

790 # is the type itself (e.g. `int()` results in an instance of `int`). 

791 return callable_obj 1abghijcdklmnefopqr

792 

793 if not isinstance(callable_obj, _function_like): 1abghijcdklmnefopqr

794 call_func = getattr(type(callable_obj), '__call__', None) # noqa: B004 1abghijcdklmnefopqr

795 if call_func is not None: 795 ↛ 798line 795 didn't jump to line 798 because the condition on line 795 was always true1abghijcdklmnefopqr

796 callable_obj = call_func 1abghijcdklmnefopqr

797 

798 hints = get_function_type_hints( 1abghijcdklmnefopqr

799 unwrap_wrapped_function(callable_obj), 

800 include_keys={'return'}, 

801 globalns=globalns, 

802 localns=localns, 

803 ) 

804 return hints.get('return', PydanticUndefined) 1abghijcdklmnefopqr

805 

806 

807def count_positional_required_params(sig: Signature) -> int: 1abghijcdklmnsefopqr

808 """Get the number of positional (required) arguments of a signature. 

809 

810 This function should only be used to inspect signatures of validation and serialization functions. 

811 The first argument (the value being serialized or validated) is counted as a required argument 

812 even if a default value exists. 

813 

814 Returns: 

815 The number of positional arguments of a signature. 

816 """ 

817 parameters = list(sig.parameters.values()) 1abghijcdklmnsefopqr

818 return sum( 1abghijcdklmnsefopqr

819 1 

820 for param in parameters 

821 if can_be_positional(param) 

822 # First argument is the value being validated/serialized, and can have a default value 

823 # (e.g. `float`, which has signature `(x=0, /)`). We assume other parameters (the info arg 

824 # for instance) should be required, and thus without any default value. 

825 and (param.default is Parameter.empty or param is parameters[0]) 

826 ) 

827 

828 

829def ensure_property(f: Any) -> Any: 1abghijcdklmnsefopqr

830 """Ensure that a function is a `property` or `cached_property`, or is a valid descriptor. 

831 

832 Args: 

833 f: The function to check. 

834 

835 Returns: 

836 The function, or a `property` or `cached_property` instance wrapping the function. 

837 """ 

838 if ismethoddescriptor(f) or isdatadescriptor(f): 1abghijcdklmnefopqr

839 return f 1abghijcdklmnefopqr

840 else: 

841 return property(f) 1abghijcdklmnefopqr