Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pydantic/dataclasses.py: 9%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

126 statements  

1"""Provide an enhanced dataclass that performs validation.""" 

2 

3from __future__ import annotations as _annotations 

4 

5import dataclasses 

6import functools 

7import sys 

8import types 

9from collections.abc import Callable 

10from typing import TYPE_CHECKING, Any, Generic, Literal, NoReturn, TypeGuard, TypeVar, overload 

11from warnings import warn 

12 

13from typing_extensions import dataclass_transform 

14 

15from ._internal import _config, _decorators, _mock_val_ser, _namespace_utils, _typing_extra 

16from ._internal import _dataclasses as _pydantic_dataclasses 

17from ._migration import getattr_migration 

18from .config import ConfigDict 

19from .errors import PydanticUserError 

20from .fields import Field, FieldInfo, PrivateAttr 

21 

22if TYPE_CHECKING: 

23 from ._internal._dataclasses import PydanticDataclass 

24 from ._internal._namespace_utils import MappingNamespace 

25 

26__all__ = 'dataclass', 'rebuild_dataclass' 

27 

28_T = TypeVar('_T') 

29 

30 

31@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 

32@overload 

33def dataclass( 

34 *, 

35 init: Literal[False] = False, 

36 repr: bool = True, 

37 eq: bool = True, 

38 order: bool = False, 

39 unsafe_hash: bool = False, 

40 frozen: bool = False, 

41 config: ConfigDict | type[object] | None = None, 

42 validate_on_init: bool | None = None, 

43 kw_only: bool = ..., 

44 slots: bool = ..., 

45) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore 

46 ... 

47 

48 

49@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 

50@overload 

51def dataclass( 

52 _cls: type[_T], # type: ignore 

53 *, 

54 init: Literal[False] = False, 

55 repr: bool = True, 

56 eq: bool = True, 

57 order: bool = False, 

58 unsafe_hash: bool = False, 

59 frozen: bool | None = None, 

60 config: ConfigDict | type[object] | None = None, 

61 validate_on_init: bool | None = None, 

62 kw_only: bool = ..., 

63 slots: bool = ..., 

64) -> type[PydanticDataclass]: ... 

65@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 

66def dataclass( 

67 _cls: type[_T] | None = None, 

68 *, 

69 init: Literal[False] = False, 

70 repr: bool = True, 

71 eq: bool = True, 

72 order: bool = False, 

73 unsafe_hash: bool = False, 

74 frozen: bool | None = None, 

75 config: ConfigDict | type[object] | None = None, 

76 validate_on_init: bool | None = None, 

77 kw_only: bool = False, 

78 slots: bool = False, 

79) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]: 

80 """!!! abstract "Usage Documentation" 

81 [`dataclasses`](../concepts/dataclasses.md) 

82 

83 A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`, 

84 but with added validation. 

85 

86 This decorator should be used similarly to the [`@dataclasses.dataclass`][dataclasses.dataclass] decorator. 

87 

88 A Pydantic dataclass validates its inputs like a `BaseModel` does. Its 

89 [`ValidationError`][pydantic_core.ValidationError] includes each rejected value, while 

90 [Logfire](../integrations/logfire.md) can retain the complete validation input and surrounding trace 

91 context — see [Troubleshooting validation errors](../errors/troubleshooting.md). 

92 

93 Args: 

94 _cls: The target `dataclass`. 

95 init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to 

96 `dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its 

97 own `__init__()` function. 

98 repr: A boolean indicating whether to include the field in the `__repr__()` output. 

99 eq: Determines if a `__eq__()` method should be generated for the class. 

100 order: Determines if comparison magic methods should be generated, such as `__lt__()`, but not `__eq__()`. 

101 unsafe_hash: Determines if a `__hash__()` method should be included in the class, as in `dataclasses.dataclass`. 

102 frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its 

103 attributes to be modified after it has been initialized. If not set, the value from the provided `config` argument will be used (and will default to `False` otherwise). 

104 config: The Pydantic config to use for the `dataclass`. 

105 validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses 

106 are validated on init. 

107 kw_only: Determines if `__init__()` method parameters must be specified by keyword only. Defaults to `False`. 

108 slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of 

109 new attributes after instantiation. 

110 

111 Returns: 

112 A decorator that accepts a class as its argument and returns a Pydantic `dataclass`. 

113 

114 Raises: 

115 AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`. 

116 """ 

117 assert init is False, 'pydantic.dataclasses.dataclass only supports init=False' 

118 assert validate_on_init is not False, 'validate_on_init=False is no longer supported' 

119 

120 def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]: 

121 """Create a Pydantic dataclass from a regular dataclass. 

122 

123 Args: 

124 cls: The class to create the Pydantic dataclass from. 

125 

126 Returns: 

127 A Pydantic dataclass. 

128 """ 

129 from ._internal._utils import is_model_class 

130 

131 if is_model_class(cls): 

132 raise PydanticUserError( 

133 f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model', 

134 code='dataclass-on-model', 

135 ) 

136 

137 original_cls = cls 

138 

139 # we warn on conflicting config specifications, but only if the class doesn't have a dataclass base 

140 # because a dataclass base might provide a __pydantic_config__ attribute that we don't want to warn about 

141 has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__) 

142 if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'): 

143 warn( 

144 f'`config` is set via both the `dataclass` decorator and `__pydantic_config__` for dataclass {cls.__name__}. ' 

145 f'The `config` specification from `dataclass` decorator will take priority.', 

146 category=UserWarning, 

147 stacklevel=2, 

148 ) 

149 

150 # if config is not explicitly provided, try to read it from the type 

151 config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None) 

152 config_wrapper = _config.ConfigWrapper(config_dict) 

153 decorators = _decorators.DecoratorInfos.build(cls, replace_wrapped_methods=True) 

154 decorators.update_from_config(config_wrapper) 

155 

156 # Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator 

157 # Otherwise, classes with no __doc__ will have their signature added into the JSON schema description, 

158 # since dataclasses.dataclass will set this as the __doc__ 

159 original_doc = cls.__doc__ 

160 

161 if _pydantic_dataclasses.is_stdlib_dataclass(cls): 

162 # Vanilla dataclasses include a default docstring (representing the class signature), 

163 # which we don't want to preserve. 

164 original_doc = None 

165 

166 # We don't want to add validation to the existing std lib dataclass, so we will subclass it 

167 # If the class is generic, we need to make sure the subclass also inherits from Generic 

168 # with all the same parameters. 

169 bases = (cls,) 

170 if issubclass(cls, Generic): 

171 generic_base = Generic[cls.__parameters__] # type: ignore 

172 bases = bases + (generic_base,) 

173 cls = types.new_class(cls.__name__, bases) 

174 

175 # Respect frozen setting from dataclass constructor and fallback to config setting if not provided 

176 if frozen is not None: 

177 frozen_ = frozen 

178 if config_wrapper.frozen: 

179 # It's not recommended to define both, as the setting from the dataclass decorator will take priority. 

180 warn( 

181 f'`frozen` is set via both the `dataclass` decorator and `config` for dataclass {cls.__name__!r}.' 

182 'This is not recommended. The `frozen` specification on `dataclass` will take priority.', 

183 category=UserWarning, 

184 stacklevel=2, 

185 ) 

186 else: 

187 frozen_ = config_wrapper.frozen or False 

188 

189 # Make Pydantic's `Field()` function compatible with stdlib dataclasses. As we'll decorate 

190 # `cls` with the stdlib `@dataclass` decorator first, some attributes (`kw_only`, `repr`, `init`) 

191 # need to be understood *during* the stdlib creation. We do so in two steps: 

192 

193 # 1. On the decorated class, wrap `Field()` assignment with `dataclass.field()`, with these 

194 # attributes set (done in `as_dataclass_field()`) 

195 cls_anns = _typing_extra.safe_get_annotations(cls) 

196 for field_name in cls_anns: 

197 # We should look for assignments in `__dict__` instead, but for now we follow 

198 # the same behavior as stdlib dataclasses (see https://github.com/python/cpython/issues/88609) 

199 field_value = getattr(cls, field_name, None) 

200 if isinstance(field_value, FieldInfo): 

201 setattr(cls, field_name, _pydantic_dataclasses.as_dataclass_field(field_value)) 

202 

203 # 2. For bases of `cls` that are stdlib dataclasses, we temporarily patch their fields 

204 # (see the docstring of the context manager): 

205 with _pydantic_dataclasses.patch_base_fields(cls): 

206 cls = dataclasses.dataclass( # pyright: ignore[reportCallIssue] 

207 cls, 

208 # the value of init here doesn't affect anything except that it makes it easier to generate a signature 

209 init=True, 

210 repr=repr, 

211 eq=eq, 

212 order=order, 

213 unsafe_hash=unsafe_hash, 

214 frozen=frozen_, 

215 kw_only=kw_only, 

216 slots=slots, 

217 ) 

218 

219 if config_wrapper.validate_assignment: 

220 original_setattr = cls.__setattr__ 

221 

222 @functools.wraps(cls.__setattr__) 

223 def validated_setattr(instance: PydanticDataclass, name: str, value: Any, /) -> None: 

224 if frozen_: 

225 return original_setattr(instance, name, value) # pyright: ignore[reportCallIssue] 

226 inst_cls = type(instance) 

227 attr = getattr(inst_cls, name, None) 

228 

229 if isinstance(attr, property): 

230 attr.__set__(instance, value) 

231 elif isinstance(attr, functools.cached_property): 

232 instance.__dict__.__setitem__(name, value) 

233 else: 

234 inst_cls.__pydantic_validator__.validate_assignment(instance, name, value) 

235 

236 cls.__setattr__ = validated_setattr.__get__(None, cls) # type: ignore 

237 

238 if slots and not hasattr(cls, '__setstate__'): 

239 # If slots is set, `pickle` (relied on by `copy.copy()`) will use 

240 # `__setattr__()` to reconstruct the dataclass. However, the custom 

241 # `__setattr__()` set above relies on `validate_assignment()`, which 

242 # in turn expects all the field values to be already present on the 

243 # instance, resulting in attribute errors. 

244 # As such, we make use of `object.__setattr__()` instead. 

245 # Note that we do so only if `__setstate__()` isn't already set (this is the 

246 # case if on top of `slots`, `frozen` is used). 

247 

248 # Taken from `dataclasses._dataclass_get/setstate()`: 

249 def _dataclass_getstate(self: Any) -> list[Any]: 

250 return [getattr(self, f.name) for f in dataclasses.fields(self)] 

251 

252 def _dataclass_setstate(self: Any, state: list[Any]) -> None: 

253 for field, value in zip(dataclasses.fields(self), state, strict=True): 

254 object.__setattr__(self, field.name, value) 

255 

256 cls.__getstate__ = _dataclass_getstate # pyright: ignore[reportAttributeAccessIssue] 

257 cls.__setstate__ = _dataclass_setstate # pyright: ignore[reportAttributeAccessIssue] 

258 

259 # This is an undocumented attribute to distinguish stdlib/Pydantic dataclasses. 

260 # It should be set as early as possible: 

261 cls.__is_pydantic_dataclass__ = True 

262 cls.__pydantic_decorators__ = decorators # type: ignore 

263 cls.__doc__ = original_doc 

264 # Can be non-existent for dynamically created classes: 

265 firstlineno = getattr(original_cls, '__firstlineno__', None) 

266 cls.__module__ = original_cls.__module__ 

267 if sys.version_info >= (3, 13) and firstlineno is not None: 

268 # As per https://docs.python.org/3/reference/datamodel.html#type.__firstlineno__: 

269 # Setting the `__module__` attribute removes the `__firstlineno__` item from the type’s dictionary. 

270 original_cls.__firstlineno__ = firstlineno 

271 cls.__firstlineno__ = firstlineno 

272 cls.__qualname__ = original_cls.__qualname__ 

273 cls.__pydantic_fields_complete__ = classmethod(_pydantic_fields_complete) 

274 cls.__pydantic_complete__ = False # `complete_dataclass` will set it to `True` if successful. 

275 # TODO `parent_namespace` is currently None, but we could do the same thing as Pydantic models: 

276 # fetch the parent ns using `parent_frame_namespace` (if the dataclass was defined in a function), 

277 # and possibly cache it (see the `__pydantic_parent_namespace__` logic for models). 

278 _pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False) 

279 return cls 

280 

281 return create_dataclass if _cls is None else create_dataclass(_cls) 

282 

283 

284def _pydantic_fields_complete(cls: type[PydanticDataclass]) -> bool: 

285 """Return whether the fields were successfully collected (i.e. type hints were successfully resolved). 

286 

287 This is a private helper, not meant to be used outside Pydantic. 

288 """ 

289 return all(field_info._complete for field_info in cls.__pydantic_fields__.values()) 

290 

291 

292__getattr__ = getattr_migration(__name__) 

293 

294if sys.version_info < (3, 11): 

295 # Monkeypatch dataclasses.InitVar so that typing doesn't error if it occurs as a type when evaluating type hints 

296 # Starting in 3.11, typing.get_type_hints will not raise an error if the retrieved type hints are not callable. 

297 

298 def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn: 

299 """This function does nothing but raise an error that is as similar as possible to what you'd get 

300 if you were to try calling `InitVar[int]()` without this monkeypatch. The whole purpose is just 

301 to ensure typing._type_check does not error if the type hint evaluates to `InitVar[<parameter>]`. 

302 """ 

303 raise TypeError("'InitVar' object is not callable") 

304 

305 dataclasses.InitVar.__call__ = _call_initvar 

306 

307 

308def rebuild_dataclass( 

309 cls: type[PydanticDataclass], 

310 *, 

311 force: bool = False, 

312 raise_errors: bool = True, 

313 _parent_namespace_depth: int = 2, 

314 _types_namespace: MappingNamespace | None = None, 

315) -> bool | None: 

316 """Try to rebuild the pydantic-core schema for the dataclass. 

317 

318 This may be necessary when one of the annotations is a ForwardRef which could not be resolved during 

319 the initial attempt to build the schema, and automatic rebuilding fails. 

320 

321 This is analogous to `BaseModel.model_rebuild`. 

322 

323 Args: 

324 cls: The class to rebuild the pydantic-core schema for. 

325 force: Whether to force the rebuilding of the schema, defaults to `False`. 

326 raise_errors: Whether to raise errors, defaults to `True`. 

327 _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. 

328 _types_namespace: The types namespace, defaults to `None`. 

329 

330 Returns: 

331 Returns `None` if the schema is already "complete" and rebuilding was not required. 

332 If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. 

333 """ 

334 if not force and cls.__pydantic_complete__: 

335 return None 

336 

337 for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): 

338 if attr in cls.__dict__ and not isinstance( 

339 getattr(cls, attr), (_mock_val_ser.MockCoreSchema, _mock_val_ser.MockValSer) 

340 ): 

341 # Deleting the validator/serializer is necessary as otherwise they can get reused in 

342 # pydantic-core. Same applies for the core schema that can be reused in schema generation. 

343 # We do so only if they aren't mock instances, otherwise concurrent reads of these attributes 

344 # (e.g. when instantiating the dataclass in another thread) can resolve them from the parent class. 

345 delattr(cls, attr) 

346 

347 cls.__pydantic_complete__ = False 

348 

349 if _types_namespace is not None: 

350 rebuild_ns = _types_namespace 

351 elif _parent_namespace_depth > 0: 

352 rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} 

353 else: 

354 rebuild_ns = {} 

355 

356 ns_resolver = _namespace_utils.NsResolver( 

357 parent_namespace=rebuild_ns, 

358 ) 

359 

360 return _pydantic_dataclasses.complete_dataclass( 

361 cls, 

362 _config.ConfigWrapper(cls.__pydantic_config__, check=False), 

363 raise_errors=raise_errors, 

364 ns_resolver=ns_resolver, 

365 # We could provide a different config instead (with `'defer_build'` set to `True`) 

366 # of this explicit `_force_build` argument, but because config can come from the 

367 # decorator parameter or the `__pydantic_config__` attribute, `complete_dataclass` 

368 # will overwrite `__pydantic_config__` with the provided config above: 

369 _force_build=True, 

370 ) 

371 

372 

373def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]: 

374 """Whether a class is a pydantic dataclass. 

375 

376 Args: 

377 class_: The class. 

378 

379 Returns: 

380 `True` if the class is a pydantic dataclass, `False` otherwise. 

381 """ 

382 try: 

383 return '__is_pydantic_dataclass__' in class_.__dict__ and dataclasses.is_dataclass(class_) 

384 except AttributeError: 

385 return False