Coverage for pydantic / _internal / _model_construction.py: 99.34%

330 statements  

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

1"""Private logic for creating models.""" 

2 

3from __future__ import annotations as _annotations 1jklabcmnodefspqrghi

4 

5import operator 1jklabcmnodefspqrghi

6import sys 1jklabcmnodefspqrghi

7import typing 1jklabcmnodefspqrghi

8import warnings 1jklabcmnodefspqrghi

9import weakref 1jklabcmnodefspqrghi

10from abc import ABCMeta 1jklabcmnodefspqrghi

11from collections.abc import Callable, MutableMapping 1jklabcmnodefspqrghi

12from functools import cache, partial, wraps 1jklabcmnodefspqrghi

13from types import FunctionType 1jklabcmnodefspqrghi

14from typing import TYPE_CHECKING, Any, Generic, Literal, NoReturn, TypeVar, cast 1jklabcmnodefspqrghi

15 

16from pydantic_core import PydanticUndefined, SchemaSerializer 1jklabcmnodefspqrghi

17from typing_extensions import ( 1jklabcmnodefspqrghi

18 TypeAliasType, 

19 dataclass_transform, 

20) 

21 

22from ..errors import PydanticUndefinedAnnotation, PydanticUserError 1jklabcmnodefspqrghi

23from ..plugin._schema_validator import create_schema_validator 1jklabcmnodefspqrghi

24from ..warnings import GenericBeforeBaseModelWarning 1jklabcmnodefspqrghi

25from ._config import ConfigWrapper 1jklabcmnodefspqrghi

26from ._decorators import DecoratorInfos, PydanticDescriptorProxy, get_attribute_from_bases, unwrap_wrapped_function 1jklabcmnodefspqrghi

27from ._fields import ( 1jklabcmnodefspqrghi

28 ModelNamespaceInfo, 

29 collect_model_fields, 

30 is_valid_field_name, 

31 is_valid_privateattr_name, 

32 rebuild_model_fields, 

33) 

34from ._generate_schema import GenerateSchema, InvalidSchemaError 1jklabcmnodefspqrghi

35from ._generics import PydanticGenericMetadata, get_model_typevars_map 1jklabcmnodefspqrghi

36from ._import_utils import import_cached_base_model, import_cached_field_info 1jklabcmnodefspqrghi

37from ._mock_val_ser import set_model_mocks 1jklabcmnodefspqrghi

38from ._namespace_utils import NsResolver 1jklabcmnodefspqrghi

39from ._signature import generate_pydantic_signature 1jklabcmnodefspqrghi

40from ._typing_extra import parent_frame_namespace 1jklabcmnodefspqrghi

41from ._utils import LazyClassAttribute, SafeGetItemProxy 1jklabcmnodefspqrghi

42 

43if TYPE_CHECKING: 1jklabcmnodefspqrghi

44 from ..fields import ComputedFieldInfo, FieldInfo, ModelPrivateAttr 

45 from ..fields import Field as PydanticModelField 

46 from ..fields import PrivateAttr as PydanticModelPrivateAttr 

47 from ..main import BaseModel 

48 from ._fields import PydanticExtraInfo 

49else: 

50 PydanticModelField = object() 1jklabcmnodefspqrghi

51 PydanticModelPrivateAttr = object() 1jklabcmnodefspqrghi

52 

53object_setattr = object.__setattr__ 1jklabcmnodefspqrghi

54 

55 

56class _ModelNamespaceDict(dict): 1jklabcmnodefspqrghi

57 """A dictionary subclass that intercepts attribute setting on model classes and 

58 warns about overriding of decorators. 

59 """ 

60 

61 def __setitem__(self, k: str, v: object) -> None: 1jklabcmnodefspqrghi

62 existing: Any = self.get(k, None) 1jklabcmnodefspqrghi

63 if existing and v is not existing and isinstance(existing, PydanticDescriptorProxy): 1jklabcmnodefspqrghi

64 warnings.warn( 1jklabcmnodefpqrghi

65 f'`{k}` overrides an existing Pydantic `{existing.decorator_info.decorator_repr}` decorator', 

66 stacklevel=2, 

67 ) 

68 

69 return super().__setitem__(k, v) 1jklabcmnodefspqrghi

70 

71 

72def NoInitField( 1jklabcmnodefspqrghi

73 *, 

74 init: Literal[False] = False, 

75) -> Any: 

76 """Only for typing purposes. Used as default value of `__pydantic_fields_set__`, 

77 `__pydantic_extra__`, `__pydantic_private__`, so they could be ignored when 

78 synthesizing the `__init__` signature. 

79 """ 

80 

81 

82# For ModelMetaclass.register(): 

83_T = TypeVar('_T') 1jklabcmnodefspqrghi

84 

85 

86@dataclass_transform(kw_only_default=True, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr, NoInitField)) 1jklabcmnodefspqrghi

87class ModelMetaclass(ABCMeta): 1jklabcmnodefspqrghi

88 def __new__( 1jklabcmnodefspqrghi

89 mcs, 

90 cls_name: str, 

91 bases: tuple[type[Any], ...], 

92 namespace: dict[str, Any], 

93 __pydantic_generic_metadata__: PydanticGenericMetadata | None = None, 

94 __pydantic_reset_parent_namespace__: bool = True, 

95 _create_model_module: str | None = None, 

96 **kwargs: Any, 

97 ) -> type: 

98 """Metaclass for creating Pydantic models. 

99 

100 Args: 

101 cls_name: The name of the class to be created. 

102 bases: The base classes of the class to be created. 

103 namespace: The attribute dictionary of the class to be created. 

104 __pydantic_generic_metadata__: Metadata for generic models. 

105 __pydantic_reset_parent_namespace__: Reset parent namespace. 

106 _create_model_module: The module of the class to be created, if created by `create_model`. 

107 **kwargs: Catch-all for any other keyword arguments. 

108 

109 Returns: 

110 The new class created by the metaclass. 

111 """ 

112 # Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we rely on the fact 

113 # that `BaseModel` itself won't have any bases, but any subclass of it will, to determine whether the `__new__` 

114 # call we're in the middle of is for the `BaseModel` class. 

115 if bases: 1jklabcmnodefspqrghi

116 base_field_names, class_vars, base_private_attributes = mcs._collect_bases_data(bases) 1jklabcmnodefspqrghi

117 

118 config_wrapper = ConfigWrapper.for_model(bases, namespace, kwargs) 1jklabcmnodefspqrghi

119 namespace_info = inspect_namespace( 1jklabcmnodefspqrghi

120 namespace, 

121 config_wrapper.ignored_types, 

122 base_class_fields=base_field_names, 

123 base_class_vars=class_vars, 

124 ) 

125 private_attributes = namespace_info.private_attributes 1jklabcmnodefspqrghi

126 # Must be done after `inspect_namespace()` is called, as it checks for the 

127 # user-assigned `model_config`: 

128 namespace['model_config'] = config_wrapper.config_dict 1jklabcmnodefspqrghi

129 namespace['__class_vars__'] = class_vars 1jklabcmnodefspqrghi

130 namespace['__private_attributes__'] = {**base_private_attributes, **private_attributes} 1jklabcmnodefspqrghi

131 

132 cls = cast('type[BaseModel]', super().__new__(mcs, cls_name, bases, namespace, **kwargs)) 1jklabcmnodefspqrghi

133 BaseModel_ = import_cached_base_model() 1jklabcmnodefspqrghi

134 

135 mro = cls.__mro__ 1jklabcmnodefspqrghi

136 if Generic in mro and mro.index(Generic) < mro.index(BaseModel_): 1jklabcmnodefspqrghi

137 warnings.warn( 1jklabcmnodefpqrghi

138 GenericBeforeBaseModelWarning( 

139 'Classes should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) ' 

140 'for pydantic generics to work properly.' 

141 ), 

142 stacklevel=2, 

143 ) 

144 

145 cls.__pydantic_custom_init__ = not getattr(cls.__init__, '__pydantic_base_init__', False) 1jklabcmnodefspqrghi

146 

147 cls.__pydantic_setattr_handlers__ = {} 1jklabcmnodefspqrghi

148 

149 cls.__pydantic_decorators__ = DecoratorInfos.build(cls, replace_wrapped_methods=True) 1jklabcmnodefspqrghi

150 cls.__pydantic_decorators__.update_from_config(config_wrapper) 1jklabcmnodefspqrghi

151 

152 # Use the getattr below to grab the __parameters__ from the `typing.Generic` parent class 

153 if __pydantic_generic_metadata__: 1jklabcmnodefspqrghi

154 cls.__pydantic_generic_metadata__ = __pydantic_generic_metadata__ 1jklabcmnodefspqrghi

155 else: 

156 parent_parameters = getattr(cls, '__pydantic_generic_metadata__', {}).get('parameters', ()) 1jklabcmnodefspqrghi

157 parameters = getattr(cls, '__parameters__', None) or parent_parameters 1jklabcmnodefspqrghi

158 if parameters and parent_parameters and not all(x in parameters for x in parent_parameters): 1jklabcmnodefspqrghi

159 from ..root_model import RootModelRootType 1jklabcmnodefpqrghi

160 

161 missing_parameters = tuple(x for x in parameters if x not in parent_parameters) 1jklabcmnodefpqrghi

162 if RootModelRootType in parent_parameters and RootModelRootType not in parameters: 1jklabcmnodefpqrghi

163 # This is a special case where the user has subclassed RootModel, but has not parameterized 

164 # RootModel with the generic type identifiers being used. Ex: 

165 # class MyModel(RootModel, Generic[T]): 

166 # root: T 

167 # Should instead just be: 

168 # class MyModel(RootModel[T]): 

169 # root: T 

170 parameters_str = ', '.join([x.__name__ for x in missing_parameters]) 1jklabcmnodefpqrghi

171 error_message = ( 1jklabcmnodefpqrghi

172 f'{cls.__name__} is a subclass of `RootModel`, but does not include the generic type identifier(s) ' 

173 f'{parameters_str} in its parameters. ' 

174 f'You should parametrize RootModel directly, e.g., `class {cls.__name__}(RootModel[{parameters_str}]): ...`.' 

175 ) 

176 else: 

177 combined_parameters = parent_parameters + missing_parameters 1jklabcmnodefpqrghi

178 parameters_str = ', '.join([str(x) for x in combined_parameters]) 1jklabcmnodefpqrghi

179 generic_type_label = f'typing.Generic[{parameters_str}]' 1jklabcmnodefpqrghi

180 error_message = ( 1jklabcmnodefpqrghi

181 f'All parameters must be present on typing.Generic;' 

182 f' you should inherit from {generic_type_label}.' 

183 ) 

184 if Generic not in bases: # pragma: no cover 1jklabcmnodefpqrghi

185 # We raise an error here not because it is desirable, but because some cases are mishandled. 

186 # It would be nice to remove this error and still have things behave as expected, it's just 

187 # challenging because we are using a custom `__class_getitem__` to parametrize generic models, 

188 # and not returning a typing._GenericAlias from it. 

189 bases_str = ', '.join([x.__name__ for x in bases] + [generic_type_label]) 1jklabcmnodefpqrghi

190 error_message += ( 1jklabcmnodefpqrghi

191 f' Note: `typing.Generic` must go last: `class {cls.__name__}({bases_str}): ...`)' 

192 ) 

193 raise TypeError(error_message) 1jklabcmnodefpqrghi

194 

195 cls.__pydantic_generic_metadata__ = { 1jklabcmnodefspqrghi

196 'origin': None, 

197 'args': (), 

198 'parameters': parameters, 

199 } 

200 

201 cls.__pydantic_complete__ = False # Ensure this specific class gets completed 1jklabcmnodefspqrghi

202 

203 # preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487 

204 # for attributes not in `new_namespace` (e.g. private attributes) 

205 for name, obj in private_attributes.items(): 1jklabcmnodefspqrghi

206 obj.__set_name__(cls, name) 1jklabcmnodefpqrghi

207 

208 if __pydantic_reset_parent_namespace__: 1jklabcmnodefspqrghi

209 cls.__pydantic_parent_namespace__ = build_lenient_weakvaluedict(parent_frame_namespace()) 1jklabcmnodefspqrghi

210 parent_namespace: dict[str, Any] | None = getattr(cls, '__pydantic_parent_namespace__', None) 1jklabcmnodefspqrghi

211 if isinstance(parent_namespace, dict): 1jklabcmnodefspqrghi

212 parent_namespace = unpack_lenient_weakvaluedict(parent_namespace) 1jklabcmnodefspqrghi

213 

214 ns_resolver = NsResolver(parent_namespace=parent_namespace) 1jklabcmnodefspqrghi

215 

216 set_model_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver, namespace_info=namespace_info) 1jklabcmnodefspqrghi

217 

218 # This can only be done after fields collection, as private attributes may be 

219 # discovered from the (evaluated) class annotations: 

220 if cls.__private_attributes__: 1jklabcmnodefspqrghi

221 original_model_post_init = get_model_post_init(namespace, bases) 1jklabcmnodefpqrghi

222 if original_model_post_init is not None: 1jklabcmnodefpqrghi

223 # if there are private attributes and a model_post_init function, we handle both 

224 

225 @wraps(original_model_post_init) 1jklabcmnodefpqrghi

226 def wrapped_model_post_init(self: BaseModel, context: Any, /) -> None: 1jklabcmnodefpqrghi

227 """We need to both initialize private attributes and call the user-defined model_post_init 

228 method. 

229 """ 

230 init_private_attributes(self, context) 1jklabcmnodefpqrghi

231 original_model_post_init(self, context) 1jklabcmnodefpqrghi

232 

233 cls.model_post_init = wrapped_model_post_init # pyright: ignore[reportAttributeAccessIssue] 1jklabcmnodefpqrghi

234 else: 

235 cls.model_post_init = init_private_attributes # pyright: ignore[reportAttributeAccessIssue] 1jklabcmnodefpqrghi

236 

237 cls.__pydantic_post_init__ = ( 1jklabcmnodefspqrghi

238 None if cls.model_post_init is BaseModel_.model_post_init else 'model_post_init' 

239 ) 

240 

241 # This is also set in `complete_model_class()`, after schema gen because they are recreated. 

242 # We set them here as well for backwards compatibility: 

243 cls.__pydantic_computed_fields__ = { 1jklabcmnodefspqrghi

244 k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items() 

245 } 

246 

247 if config_wrapper.defer_build: 1jklabcmnodefspqrghi

248 set_model_mocks(cls) 1jklabcmnodefpqrghi

249 else: 

250 # Any operation that requires accessing the field infos instances should be put inside 

251 # `complete_model_class()`: 

252 complete_model_class( 1jklabcmnodefspqrghi

253 cls, 

254 config_wrapper, 

255 ns_resolver, 

256 raise_errors=False, 

257 create_model_module=_create_model_module, 

258 ) 

259 

260 if config_wrapper.frozen and '__hash__' not in namespace: 1jklabcmnodefspqrghi

261 set_default_hash_func(cls, bases) 1jklabcmnodefspqrghi

262 

263 # using super(cls, cls) on the next line ensures we only call the parent class's __pydantic_init_subclass__ 

264 # I believe the `type: ignore` is only necessary because mypy doesn't realize that this code branch is 

265 # only hit for _proper_ subclasses of BaseModel 

266 super(cls, cls).__pydantic_init_subclass__(**kwargs) # type: ignore[misc] 1jklabcmnodefspqrghi

267 return cls 1jklabcmnodefspqrghi

268 else: 

269 # These are instance variables, but have been assigned to `NoInitField` to trick the type checker. 

270 for instance_slot in '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__': 1jklabcmnodefspqrghi

271 namespace.pop( 1jklabcmnodefspqrghi

272 instance_slot, 

273 None, # In case the metaclass is used with a class other than `BaseModel`. 

274 ) 

275 namespace.get('__annotations__', {}).clear() 1jklabcmnodefspqrghi

276 return super().__new__(mcs, cls_name, bases, namespace, **kwargs) 1jklabcmnodefspqrghi

277 

278 if not TYPE_CHECKING: # pragma: no branch 1jklabcmnodefspqrghi

279 # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access 

280 

281 def __getattr__(self, item: str) -> Any: 1jklabcmnodefspqrghi

282 """This is necessary to keep attribute access working for class attribute access.""" 

283 private_attributes = self.__dict__.get('__private_attributes__') 1jklabcmnodefspqrghi

284 if private_attributes and item in private_attributes: 1jklabcmnodefspqrghi

285 return private_attributes[item] 1jklabcmnodefpqrghi

286 raise AttributeError(item) 1jklabcmnodefspqrghi

287 

288 @classmethod 1jklabcmnodefspqrghi

289 def __prepare__(cls, *args: Any, **kwargs: Any) -> dict[str, object]: 1jklabcmnodefspqrghi

290 return _ModelNamespaceDict() 1jklabcmnodefspqrghi

291 

292 # Due to performance and memory issues, in the ABCMeta.__subclasscheck__ implementation, we don't support 

293 # registered virtual subclasses. See https://github.com/python/cpython/issues/92810#issuecomment-2762454345. 

294 # This may change once CPython is fixed (possibly in 3.15), in which case we should conditionally 

295 # define `register()`. 

296 def register(self, subclass: type[_T]) -> type[_T]: 1jklabcmnodefspqrghi

297 warnings.warn( 1jklabcmnodefpqrghi

298 f"For performance reasons, virtual subclasses registered using '{self.__qualname__}.register()' " 

299 "are not supported in 'isinstance()' and 'issubclass()' checks.", 

300 stacklevel=2, 

301 ) 

302 return super().register(subclass) 1jklabcmnodefpqrghi

303 

304 __instancecheck__ = type.__instancecheck__ # pyright: ignore[reportAssignmentType] 1jklabcmnodefspqrghi

305 __subclasscheck__ = type.__subclasscheck__ # pyright: ignore[reportAssignmentType] 1jklabcmnodefspqrghi

306 

307 @staticmethod 1jklabcmnodefspqrghi

308 def _collect_bases_data(bases: tuple[type[Any], ...]) -> tuple[set[str], set[str], dict[str, ModelPrivateAttr]]: 1jklabcmnodefspqrghi

309 BaseModel = import_cached_base_model() 1jklabcmnodefspqrghi

310 

311 field_names: set[str] = set() 1jklabcmnodefspqrghi

312 class_vars: set[str] = set() 1jklabcmnodefspqrghi

313 private_attributes: dict[str, ModelPrivateAttr] = {} 1jklabcmnodefspqrghi

314 for base in bases: 1jklabcmnodefspqrghi

315 if issubclass(base, BaseModel) and base is not BaseModel: 1jklabcmnodefspqrghi

316 # model_fields might not be defined yet in the case of generics, so we use getattr here: 

317 field_names.update(getattr(base, '__pydantic_fields__', {}).keys()) 1jklabcmnodefspqrghi

318 class_vars.update(base.__class_vars__) 1jklabcmnodefspqrghi

319 private_attributes.update(base.__private_attributes__) 1jklabcmnodefspqrghi

320 return field_names, class_vars, private_attributes 1jklabcmnodefspqrghi

321 

322 @property 1jklabcmnodefspqrghi

323 def model_fields(self) -> dict[str, FieldInfo]: 1jklabcmnodefspqrghi

324 """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.""" 

325 return getattr(self, '__pydantic_fields__', {}) 1jklabcmnodefpqrghi

326 

327 @property 1jklabcmnodefspqrghi

328 def model_computed_fields(self) -> dict[str, ComputedFieldInfo]: 1jklabcmnodefspqrghi

329 """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.""" 

330 return getattr(self, '__pydantic_computed_fields__', {}) 1jklabcmnodefpqrghi

331 

332 @property 1jklabcmnodefspqrghi

333 def __pydantic_fields_complete__(self) -> bool: 1jklabcmnodefspqrghi

334 """Whether the fields were successfully collected (i.e. type hints were successfully resolved). 

335 

336 This is a private attribute, not meant to be used outside Pydantic. 

337 """ 

338 if '__pydantic_fields__' not in self.__dict__: 1jklabcmnodefspqrghi

339 return False 1jklabcmnodefpqrghi

340 

341 field_infos = cast('dict[str, FieldInfo]', self.__pydantic_fields__) # pyright: ignore[reportAttributeAccessIssue] 1jklabcmnodefspqrghi

342 

343 pydantic_extra_info = cast('PydanticExtraInfo | None', self.__pydantic_extra_info__) # pyright: ignore[reportAttributeAccessIssue] 1jklabcmnodefspqrghi

344 if pydantic_extra_info is not None: 1jklabcmnodefspqrghi

345 extra_complete = pydantic_extra_info.complete 1jklabcmnodefpqrghi

346 else: 

347 extra_complete = True 1jklabcmnodefspqrghi

348 

349 return all(field_info._complete for field_info in field_infos.values()) and extra_complete 1jklabcmnodefspqrghi

350 

351 

352def init_private_attributes(self: BaseModel, context: Any, /) -> None: 1jklabcmnodefspqrghi

353 """This function is meant to behave like a BaseModel method to initialize private attributes. 

354 

355 It takes context as an argument since that's what pydantic-core passes when calling it. 

356 

357 Args: 

358 self: The BaseModel instance. 

359 context: The context. 

360 """ 

361 if getattr(self, '__pydantic_private__', None) is None: 1jklabcmnodefpqrghi

362 pydantic_private = {} 1jklabcmnodefpqrghi

363 for name, private_attr in self.__private_attributes__.items(): 1jklabcmnodefpqrghi

364 # Avoid needlessly creating a new dict for the validated data: 

365 if private_attr.default_factory_takes_validated_data: 1jklabcmnodefpqrghi

366 default = private_attr.get_default( 1jklabcmnodefpqrghi

367 call_default_factory=True, validated_data={**self.__dict__, **pydantic_private} 

368 ) 

369 else: 

370 default = private_attr.get_default(call_default_factory=True) 1jklabcmnodefpqrghi

371 if default is not PydanticUndefined: 1jklabcmnodefpqrghi

372 pydantic_private[name] = default 1jklabcmnodefpqrghi

373 object_setattr(self, '__pydantic_private__', pydantic_private) 1jklabcmnodefpqrghi

374 

375 

376def get_model_post_init(namespace: dict[str, Any], bases: tuple[type[Any], ...]) -> Callable[..., Any] | None: 1jklabcmnodefspqrghi

377 """Get the `model_post_init` method from the namespace or the class bases, or `None` if not defined.""" 

378 if 'model_post_init' in namespace: 1jklabcmnodefpqrghi

379 return namespace['model_post_init'] 1jklabcmnodefpqrghi

380 

381 BaseModel = import_cached_base_model() 1jklabcmnodefpqrghi

382 

383 model_post_init = get_attribute_from_bases(bases, 'model_post_init') 1jklabcmnodefpqrghi

384 if model_post_init is not BaseModel.model_post_init: 1jklabcmnodefpqrghi

385 return model_post_init 1jklabcmnodefpqrghi

386 

387 

388def inspect_namespace( 1jklabcmnodefspqrghi

389 namespace: dict[str, Any], 

390 ignored_types: tuple[type[Any], ...], 

391 *, 

392 base_class_vars: set[str], 

393 base_class_fields: set[str], 

394) -> ModelNamespaceInfo: 

395 """Inspect the namespace prior to class creation. 

396 

397 Most of the collected information is then used by `collect_model_fields()` to perform checks. 

398 

399 Args: 

400 namespace: The attribute dictionary of the class to be created. 

401 ignored_types: Tuple of ignore types. 

402 base_class_vars: The set of base class variables. 

403 base_class_fields: The set of base class fields. 

404 

405 Returns: 

406 A `ModelNamespaceInfo` instance. 

407 

408 Raises: 

409 PydanticUserError: If a private attribute name is invalid. 

410 """ 

411 from ..fields import ModelPrivateAttr 1jklabcmnodefspqrghi

412 

413 FieldInfo = import_cached_field_info() 1jklabcmnodefspqrghi

414 

415 all_ignored_types = ignored_types + default_ignored_types() 1jklabcmnodefspqrghi

416 

417 private_attributes: dict[str, ModelPrivateAttr] = {} 1jklabcmnodefspqrghi

418 ignored_names: set[str] = set() 1jklabcmnodefspqrghi

419 private_candidates: list[str] = [] 1jklabcmnodefspqrghi

420 field_candidates: list[str] = [] 1jklabcmnodefspqrghi

421 

422 for var_name, value in namespace.items(): 1jklabcmnodefspqrghi

423 if var_name == 'model_config' or var_name == '__pydantic_extra__': 1jklabcmnodefspqrghi

424 continue 1jklabcmnodefspqrghi

425 elif ( 1jabcmdefpghi

426 isinstance(value, type) 

427 and value.__module__ == namespace['__module__'] 

428 and '__qualname__' in namespace 

429 and value.__qualname__.startswith(f'{namespace["__qualname__"]}.') 

430 ): 

431 # `value` is a nested type defined in this namespace; don't error 

432 continue 1jklabcmnodefspqrghi

433 elif isinstance(value, all_ignored_types) or value.__class__.__module__ == 'functools': 1jklabcmnodefspqrghi

434 ignored_names.add(var_name) 1jklabcmnodefspqrghi

435 continue 1jklabcmnodefspqrghi

436 elif isinstance(value, ModelPrivateAttr): 1jklabcmnodefspqrghi

437 if var_name.startswith('__'): 1jklabcmnodefpqrghi

438 raise PydanticUserError( 1jklabcmnodefpqrghi

439 'Private attributes must not use dunder names;' 

440 f' use a single underscore prefix instead of {var_name!r}.', 

441 code=None, 

442 ) 

443 elif is_valid_field_name(var_name): 1jklabcmnodefpqrghi

444 raise PydanticUserError( 1jklabcmnodefpqrghi

445 'Private attributes must not use valid field names;' 

446 f' use sunder names, e.g. {"_" + var_name!r} instead of {var_name!r}.', 

447 code=None, 

448 ) 

449 private_attributes[var_name] = value 1jklabcmnodefpqrghi

450 elif isinstance(value, FieldInfo) and not is_valid_field_name(var_name): 1jklabcmnodefspqrghi

451 suggested_name = var_name.lstrip('_') or 'my_field' # don't suggest '' for all-underscore name 1jklabcmnodefpqrghi

452 raise PydanticUserError( 1jklabcmnodefpqrghi

453 f'Fields must not use names with leading underscores;' 

454 f' e.g., use {suggested_name!r} instead of {var_name!r}.', 

455 code=None, 

456 ) 

457 elif var_name.startswith('__'): 1jklabcmnodefspqrghi

458 continue 1jklabcmnodefspqrghi

459 elif is_valid_privateattr_name(var_name): 1jklabcmnodefspqrghi

460 # A private attribute, unless annotated as a class variable (only known 

461 # once annotations are evaluated during fields collection): 

462 private_candidates.append(var_name) 1jklabcmnodefpqrghi

463 elif var_name in base_class_vars: 1jklabcmnodefspqrghi

464 continue 1jklabcmnodefpqrghi

465 else: 

466 # A field default or an invalid non-annotated attribute (only known 

467 # once annotations are evaluated during fields collection): 

468 field_candidates.append(var_name) 1jklabcmnodefspqrghi

469 

470 for var_name in private_attributes: 1jklabcmnodefspqrghi

471 del namespace[var_name] 1jklabcmnodefpqrghi

472 

473 return ModelNamespaceInfo( 1jklabcmnodefspqrghi

474 private_attributes=private_attributes, 

475 ignored_names=ignored_names, 

476 ignored_types=all_ignored_types, 

477 private_candidates=private_candidates, 

478 field_candidates=field_candidates, 

479 base_field_names=base_class_fields, 

480 model_config_assigned=namespace.get('model_config') is not None, 

481 ) 

482 

483 

484def set_default_hash_func(cls: type[BaseModel], bases: tuple[type[Any], ...]) -> None: 1jklabcmnodefspqrghi

485 base_hash_func = get_attribute_from_bases(bases, '__hash__') 1jklabcmnodefspqrghi

486 new_hash_func = make_hash_func(cls) 1jklabcmnodefspqrghi

487 if base_hash_func in {None, object.__hash__} or getattr(base_hash_func, '__code__', None) == new_hash_func.__code__: 1jklabcmnodefspqrghi

488 # If `__hash__` is some default, we generate a hash function. 

489 # It will be `None` if not overridden from BaseModel. 

490 # It may be `object.__hash__` if there is another 

491 # parent class earlier in the bases which doesn't override `__hash__` (e.g. `typing.Generic`). 

492 # It may be a value set by `set_default_hash_func` if `cls` is a subclass of another frozen model. 

493 # In the last case we still need a new hash function to account for new `model_fields`. 

494 cls.__hash__ = new_hash_func 1jklabcmnodefspqrghi

495 

496 

497def make_hash_func(cls: type[BaseModel]) -> Any: 1jklabcmnodefspqrghi

498 getter = operator.itemgetter(*cls.__pydantic_fields__.keys()) if cls.__pydantic_fields__ else lambda _: 0 1jklabcmnodefspqrghi

499 

500 def hash_func(self: Any) -> int: 1jklabcmnodefspqrghi

501 try: 1jklabcmnodefpqrghi

502 return hash(getter(self.__dict__)) 1jklabcmnodefpqrghi

503 except KeyError: 1jklabcmnodefpqrghi

504 # In rare cases (such as when using the deprecated copy method), the __dict__ may not contain 

505 # all model fields, which is how we can get here. 

506 # getter(self.__dict__) is much faster than any 'safe' method that accounts for missing keys, 

507 # and wrapping it in a `try` doesn't slow things down much in the common case. 

508 return hash(getter(SafeGetItemProxy(self.__dict__))) 1jklabcmnodefpqrghi

509 

510 return hash_func 1jklabcmnodefspqrghi

511 

512 

513def set_model_fields( 1jklabcmnodefspqrghi

514 cls: type[BaseModel], 

515 config_wrapper: ConfigWrapper, 

516 ns_resolver: NsResolver, 

517 namespace_info: ModelNamespaceInfo | None = None, 

518) -> None: 

519 """Collect and set `cls.__pydantic_fields__`, `cls.__class_vars__` and `cls.__private_attributes__`. 

520 

521 Args: 

522 cls: BaseModel or dataclass. 

523 config_wrapper: The config wrapper instance. 

524 ns_resolver: Namespace resolver to use when getting model annotations. 

525 namespace_info: The result of inspecting the class namespace before the class was created. 

526 """ 

527 typevars_map = get_model_typevars_map(cls) 1jklabcmnodefspqrghi

528 fields, pydantic_extra_info, class_vars, private_attributes = collect_model_fields( 1jklabcmnodefspqrghi

529 cls, config_wrapper, ns_resolver, typevars_map=typevars_map, namespace_info=namespace_info 

530 ) 

531 

532 cls.__pydantic_fields__ = fields 1jklabcmnodefspqrghi

533 cls.__pydantic_extra_info__ = pydantic_extra_info 1jklabcmnodefspqrghi

534 cls.__class_vars__.update(class_vars) 1jklabcmnodefspqrghi

535 cls.__private_attributes__.update(private_attributes) 1jklabcmnodefspqrghi

536 

537 for k in class_vars: 1jklabcmnodefspqrghi

538 # Class vars should not be private attributes (this can happen when a class variable 

539 # of a base class shadows a private attribute, e.g. when annotated as a `ClassVar` 

540 # in a subclass): 

541 value = cls.__private_attributes__.pop(k, None) 1jklabcmnodefspqrghi

542 if value is not None and value.default is not PydanticUndefined: 542 ↛ 543line 542 didn't jump to line 543 because the condition on line 542 was never true1jklabcmnodefspqrghi

543 setattr(cls, k, value.default) 

544 

545 

546def complete_model_class( 1jklabcmnodefspqrghi

547 cls: type[BaseModel], 

548 config_wrapper: ConfigWrapper, 

549 ns_resolver: NsResolver, 

550 *, 

551 raise_errors: bool = True, 

552 call_on_complete_hook: bool = True, 

553 create_model_module: str | None = None, 

554 is_force_rebuild: bool = False, 

555) -> bool: 

556 """Finish building a model class. 

557 

558 This logic must be called after class has been created since validation functions must be bound 

559 and `get_type_hints` requires a class object. 

560 

561 Args: 

562 cls: BaseModel or dataclass. 

563 config_wrapper: The config wrapper instance. 

564 ns_resolver: The namespace resolver instance to use during schema building. 

565 raise_errors: Whether to raise errors. 

566 call_on_complete_hook: Whether to call the `__pydantic_on_complete__` hook. 

567 create_model_module: The module of the class to be created, if created by `create_model`. 

568 is_force_rebuild: Whether the model is being force-rebuilt (if True, pre-built serializers and 

569 validators are not used, to avoid stale references). 

570 

571 Returns: 

572 `True` if the model is successfully completed, else `False`. 

573 

574 Raises: 

575 PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation` occurs during core schema generation 

576 and `raise_errors` is True. 

577 """ 

578 typevars_map = get_model_typevars_map(cls) 1jklabcmnodefspqrghi

579 

580 if not cls.__pydantic_fields_complete__: 1jklabcmnodefspqrghi

581 # Note: when coming from `ModelMetaclass.__new__()`, this results in fields being built twice. 

582 # We do so a second time here so that we can get the ``NameError`` for the specific undefined annotation. 

583 # Alternatively, we could let `GenerateSchema()` raise the error, but there are cases where incomplete 

584 # fields are inherited in `collect_model_fields()` and can actually have their annotation resolved in the 

585 # generate schema process. As we want to avoid having `__pydantic_fields_complete__` set to `False` 

586 # when `__pydantic_complete__` is `True`, we rebuild here: 

587 try: 1jklabcmnodefspqrghi

588 cls.__pydantic_fields__, cls.__pydantic_extra_info__ = rebuild_model_fields( 1jklabcmnodefspqrghi

589 cls, 

590 config_wrapper=config_wrapper, 

591 ns_resolver=ns_resolver, 

592 typevars_map=typevars_map, 

593 ) 

594 except NameError as e: 1jklabcmnodefspqrghi

595 exc = PydanticUndefinedAnnotation.from_name_error(e) 1jklabcmnodefspqrghi

596 set_model_mocks(cls, f'`{exc.name}`' if exc.name is not None else None) 1jklabcmnodefspqrghi

597 if raise_errors: 1jklabcmnodefspqrghi

598 raise exc from e 1jklabcmnodefpqrghi

599 

600 if not raise_errors and not cls.__pydantic_fields_complete__: 1jklabcmnodefspqrghi

601 # No need to continue with schema gen, it is guaranteed to fail 

602 return False 1jklabcmnodefspqrghi

603 

604 assert cls.__pydantic_fields_complete__ 1jklabcmnodefspqrghi

605 

606 gen_schema = GenerateSchema( 1jklabcmnodefspqrghi

607 config_wrapper, 

608 ns_resolver, 

609 typevars_map, 

610 ) 

611 

612 try: 1jklabcmnodefspqrghi

613 schema = gen_schema.generate_schema(cls) 1jklabcmnodefspqrghi

614 except PydanticUndefinedAnnotation as e: 1jklabcmnodefpqrghi

615 if raise_errors: 1jklabcmnodefpqrghi

616 raise 1jklabcmnodefpqrghi

617 set_model_mocks(cls, f'`{e.name}`' if e.name is not None else None) 1jklabcmnodefpqrghi

618 return False 1jklabcmnodefpqrghi

619 

620 core_config = config_wrapper.core_config(title=cls.__name__) 1jklabcmnodefspqrghi

621 

622 try: 1jklabcmnodefspqrghi

623 schema = gen_schema.clean_schema(schema) 1jklabcmnodefspqrghi

624 except InvalidSchemaError: 1jklabcmnodefpqrghi

625 set_model_mocks(cls) 1jklabcmnodefpqrghi

626 return False 1jklabcmnodefpqrghi

627 

628 # This needs to happen *after* model schema generation, as the return types 

629 # of the properties are evaluated and the `ComputedFieldInfo` are recreated: 

630 cls.__pydantic_computed_fields__ = {k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()} 1jklabcmnodefspqrghi

631 

632 set_deprecated_descriptors(cls) 1jklabcmnodefspqrghi

633 

634 cls.__pydantic_core_schema__ = schema 1jklabcmnodefspqrghi

635 

636 cls.__pydantic_validator__ = create_schema_validator( 1jklabcmnodefspqrghi

637 schema, 

638 cls, 

639 create_model_module or cls.__module__, 

640 cls.__qualname__, 

641 'create_model' if create_model_module else 'BaseModel', 

642 core_config, 

643 config_wrapper.plugin_settings, 

644 _use_prebuilt=not is_force_rebuild, 

645 ) 

646 cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config, _use_prebuilt=not is_force_rebuild) 1jklabcmnodefspqrghi

647 

648 # set __signature__ attr only for model class, but not for its instances 

649 # (because instances can define `__call__`, and `inspect.signature` shouldn't 

650 # use the `__signature__` attribute and instead generate from `__call__`). 

651 cls.__signature__ = LazyClassAttribute( 1jklabcmnodefspqrghi

652 '__signature__', 

653 partial( 

654 generate_pydantic_signature, 

655 init=cls.__init__, 

656 fields=cls.__pydantic_fields__, 

657 validate_by_alias=config_wrapper.validate_by_alias, 

658 extra=config_wrapper.extra, 

659 ), 

660 ) 

661 

662 cls.__pydantic_complete__ = True 1jklabcmnodefspqrghi

663 

664 if call_on_complete_hook: 1jklabcmnodefspqrghi

665 cls.__pydantic_on_complete__() 1jklabcmnodefspqrghi

666 

667 return True 1jklabcmnodefspqrghi

668 

669 

670def set_deprecated_descriptors(cls: type[BaseModel]) -> None: 1jklabcmnodefspqrghi

671 """Set data descriptors on the class for deprecated fields.""" 

672 for field, field_info in cls.__pydantic_fields__.items(): 1jklabcmnodefspqrghi

673 if (msg := field_info.deprecation_message) is not None: 1jklabcmnodefspqrghi

674 desc = _DeprecatedFieldDescriptor(msg) 1jklabcmnodefpqrghi

675 desc.__set_name__(cls, field) 1jklabcmnodefpqrghi

676 setattr(cls, field, desc) 1jklabcmnodefpqrghi

677 

678 for field, computed_field_info in cls.__pydantic_computed_fields__.items(): 1jklabcmnodefspqrghi

679 if ( 1abcdefghi

680 (msg := computed_field_info.deprecation_message) is not None 

681 # If the property was already decorated with `@deprecated`, we avoid emitting the warning message 

682 # from `@computed_field` and give priority to the other. Ideally, the deprecation message from 

683 # `@computed_field` should take priority, but we can't safely unwrap (using `inspect.unwrap()`) 

684 # to get the inner property decorated by `@deprecated`, as we might skip other user-defined decorators 

685 # while doing so: 

686 and not hasattr(unwrap_wrapped_function(computed_field_info.wrapped_property), '__deprecated__') 

687 ): 

688 desc = _DeprecatedFieldDescriptor(msg, computed_field_info.wrapped_property) 1jklabcmnodefpqrghi

689 desc.__set_name__(cls, field) 1jklabcmnodefpqrghi

690 setattr(cls, field, desc) 1jklabcmnodefpqrghi

691 

692 

693class _DeprecatedFieldDescriptor: 1jklabcmnodefspqrghi

694 """Read-only data descriptor used to emit a runtime deprecation warning before accessing a deprecated field. 

695 

696 Attributes: 

697 msg: The deprecation message to be emitted. 

698 wrapped_property: The property instance if the deprecated field is a computed field, or `None`. 

699 field_name: The name of the field being deprecated. 

700 """ 

701 

702 field_name: str 1jklabcmnodefspqrghi

703 

704 def __init__(self, msg: str, wrapped_property: property | None = None) -> None: 1jklabcmnodefspqrghi

705 self.msg = msg 1jklabcmnodefpqrghi

706 self.wrapped_property = wrapped_property 1jklabcmnodefpqrghi

707 

708 def __set_name__(self, cls: type[BaseModel], name: str) -> None: 1jklabcmnodefspqrghi

709 self.field_name = name 1jklabcmnodefpqrghi

710 

711 def __get__(self, obj: BaseModel | None, obj_type: type[BaseModel] | None = None) -> Any: 1jklabcmnodefspqrghi

712 if obj is None: 1jklabcmnodefpqrghi

713 if self.wrapped_property is not None: 1jklabcmnodefpqrghi

714 return self.wrapped_property.__get__(None, obj_type) 1jklabcmnodefpqrghi

715 raise AttributeError(self.field_name) 1jklabcmnodefpqrghi

716 

717 warnings.warn(self.msg, DeprecationWarning, stacklevel=2) 1jklabcmnodefpqrghi

718 

719 if self.wrapped_property is not None: 1jklabcmnodefpqrghi

720 return self.wrapped_property.__get__(obj, obj_type) 1jklabcmnodefpqrghi

721 return obj.__dict__[self.field_name] 1jklabcmnodefpqrghi

722 

723 # Defined to make it a data descriptor and take precedence over the instance's dictionary. 

724 # Note that it will not be called when setting a value on a model instance 

725 # as `BaseModel.__setattr__` is defined and takes priority. 

726 def __set__(self, obj: Any, value: Any) -> NoReturn: 1jklabcmnodefspqrghi

727 raise AttributeError(self.field_name) 

728 

729 

730class _PydanticWeakRef: 1jklabcmnodefspqrghi

731 """Wrapper for `weakref.ref` that enables `pickle` serialization. 

732 

733 Cloudpickle fails to serialize weakref.ref objects due to an arcane error related to 

734 to abstract base classes (`abc.ABC`). This class works around the issue by wrapping 

735 `weakref.ref` instead of subclassing it. 

736 

737 See https://github.com/pydantic/pydantic/issues/6763 for context. 

738 

739 Semantics: 

740 - If not pickled, behaves the same as a `weakref.ref`. 

741 - If pickled along with the referenced object, the same `weakref.ref` behavior 

742 will be maintained between them after unpickling. 

743 - If pickled without the referenced object, after unpickling the underlying 

744 reference will be cleared (`__call__` will always return `None`). 

745 """ 

746 

747 def __init__(self, obj: Any): 1jklabcmnodefspqrghi

748 if obj is None: 1jklabcmnodefspqrghi

749 # The object will be `None` upon deserialization if the serialized weakref 

750 # had lost its underlying object. 

751 self._wr = None 1jklabcmnodefpqrghi

752 else: 

753 self._wr = weakref.ref(obj) 1jklabcmnodefspqrghi

754 

755 def __call__(self) -> Any: 1jklabcmnodefspqrghi

756 if self._wr is None: 1jklabcmnodefpqrghi

757 return None 1jklabcmnodefpqrghi

758 else: 

759 return self._wr() 1jklabcmnodefpqrghi

760 

761 def __reduce__(self) -> tuple[Callable, tuple[weakref.ReferenceType | None]]: 1jklabcmnodefspqrghi

762 return _PydanticWeakRef, (self(),) 1jklabcmnodefpqrghi

763 

764 

765def build_lenient_weakvaluedict(d: MutableMapping[str, Any] | None) -> dict[str, Any] | None: 1jklabcmnodefspqrghi

766 """Takes an input dictionary, and produces a new value that (invertibly) replaces the values with weakrefs. 

767 

768 We can't just use a WeakValueDictionary because many types (including int, str, etc.) can't be stored as values 

769 in a WeakValueDictionary. 

770 

771 The `unpack_lenient_weakvaluedict` function can be used to reverse this operation. 

772 """ 

773 if d is None: 1jklabcmnodefspqrghi

774 return None 1jklabcmnodefspqrghi

775 result = {} 1jklabcmnodefspqrghi

776 for k, v in d.items(): 1jklabcmnodefspqrghi

777 try: 1jklabcmnodefspqrghi

778 proxy = _PydanticWeakRef(v) 1jklabcmnodefspqrghi

779 except TypeError: 1jklabcmnodefspqrghi

780 proxy = v 1jklabcmnodefspqrghi

781 result[k] = proxy 1jklabcmnodefspqrghi

782 return result 1jklabcmnodefspqrghi

783 

784 

785def unpack_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None: 1jklabcmnodefspqrghi

786 """Inverts the transform performed by `build_lenient_weakvaluedict`.""" 

787 if d is None: 1jklabcmnodefspqrghi

788 return None 1jklabcmnodefspqrghi

789 

790 result = {} 1jklabcmnodefspqrghi

791 for k, v in d.items(): 1jklabcmnodefspqrghi

792 if isinstance(v, _PydanticWeakRef): 1jklabcmnodefspqrghi

793 v = v() 1jklabcmnodefpqrghi

794 if v is not None: 1jklabcmnodefpqrghi

795 result[k] = v 1jklabcmnodefpqrghi

796 else: 

797 result[k] = v 1jklabcmnodefspqrghi

798 return result 1jklabcmnodefspqrghi

799 

800 

801@cache 1jklabcmnodefspqrghi

802def default_ignored_types() -> tuple[type[Any], ...]: 1jklabcmnodefspqrghi

803 from ..fields import ComputedFieldInfo 1jklabcmnodefspqrghi

804 

805 ignored_types = [ 1jklabcmnodefspqrghi

806 FunctionType, 

807 property, 

808 classmethod, 

809 staticmethod, 

810 PydanticDescriptorProxy, 

811 ComputedFieldInfo, 

812 TypeAliasType, # from `typing_extensions` 

813 ] 

814 

815 if sys.version_info >= (3, 12): 1jklabcmnodefspqrghi

816 ignored_types.append(typing.TypeAliasType) 1klabcnodefsqrghi

817 

818 return tuple(ignored_types) 1jklabcmnodefspqrghi