Coverage for pydantic/dataclasses.py: 98.08%

112 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-26 07:45 +0000

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

2 

3from __future__ import annotations as _annotations 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

4 

5import dataclasses 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

6import functools 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

7import sys 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

8import types 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

9from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, NoReturn, TypeVar, overload 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

10from warnings import warn 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

11 

12from typing_extensions import TypeGuard, dataclass_transform 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

13 

14from ._internal import _config, _decorators, _namespace_utils, _typing_extra 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

15from ._internal import _dataclasses as _pydantic_dataclasses 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

16from ._migration import getattr_migration 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

17from .config import ConfigDict 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

18from .errors import PydanticUserError 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

19from .fields import Field, FieldInfo, PrivateAttr 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

20 

21if TYPE_CHECKING: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

22 from ._internal._dataclasses import PydanticDataclass 

23 from ._internal._namespace_utils import MappingNamespace 

24 

25__all__ = 'dataclass', 'rebuild_dataclass' 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

26 

27_T = TypeVar('_T') 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

28 

29if sys.version_info >= (3, 10): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

30 

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

32 @overload 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

33 def dataclass( 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

34 *, 

35 init: Literal[False] = False, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

36 repr: bool = True, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

37 eq: bool = True, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

38 order: bool = False, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

39 unsafe_hash: bool = False, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

40 frozen: bool = False, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

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

42 validate_on_init: bool | None = None, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

43 kw_only: bool = ..., 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

44 slots: bool = ..., 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

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

46 ... 

47 

48 @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

49 @overload 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

50 def dataclass( 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

51 _cls: type[_T], # type: ignore 1defghaklmnoJKLMrstuv

52 *, 

53 init: Literal[False] = False, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

54 repr: bool = True, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

55 eq: bool = True, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

56 order: bool = False, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

57 unsafe_hash: bool = False, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

58 frozen: bool | None = None, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

59 config: ConfigDict | type[object] | None = None, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

60 validate_on_init: bool | None = None, 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

61 kw_only: bool = ..., 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

62 slots: bool = ..., 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

63 ) -> type[PydanticDataclass]: ... 1defghaklmnoJKLMrstuv

64 

65else: 

66 

67 @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1DECFGPHI

68 @overload 1DECFGPHI

69 def dataclass( 1DECFGPHI

70 *, 

71 init: Literal[False] = False, 1DECFGPHI

72 repr: bool = True, 1DECFGPHI

73 eq: bool = True, 1DECFGPHI

74 order: bool = False, 1DECFGPHI

75 unsafe_hash: bool = False, 1DECFGPHI

76 frozen: bool | None = None, 1DECFGPHI

77 config: ConfigDict | type[object] | None = None, 1DECFGPHI

78 validate_on_init: bool | None = None, 1DECFGPHI

79 ) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore 1C

80 ... 

81 

82 @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1DECFGPHI

83 @overload 1DECFGPHI

84 def dataclass( 1DECFGPHI

85 _cls: type[_T], # type: ignore 1C

86 *, 

87 init: Literal[False] = False, 1DECFGPHI

88 repr: bool = True, 1DECFGPHI

89 eq: bool = True, 1DECFGPHI

90 order: bool = False, 1DECFGPHI

91 unsafe_hash: bool = False, 1DECFGPHI

92 frozen: bool | None = None, 1DECFGPHI

93 config: ConfigDict | type[object] | None = None, 1DECFGPHI

94 validate_on_init: bool | None = None, 1DECFGPHI

95 ) -> type[PydanticDataclass]: ... 1C

96 

97 

98@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

99def dataclass( 1DEbcwxdefghFGijyzklmnoPNOJKLMHIpqABrstuv

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

101 *, 

102 init: Literal[False] = False, 

103 repr: bool = True, 

104 eq: bool = True, 

105 order: bool = False, 

106 unsafe_hash: bool = False, 

107 frozen: bool | None = None, 

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

109 validate_on_init: bool | None = None, 

110 kw_only: bool = False, 

111 slots: bool = False, 

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

113 """!!! abstract "Usage Documentation" 

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

115 

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

117 but with added validation. 

118 

119 This function should be used similarly to `dataclasses.dataclass`. 

120 

121 Args: 

122 _cls: The target `dataclass`. 

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

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

125 own `__init__` function. 

126 repr: A boolean indicating whether to include the field in the `__repr__` output. 

127 eq: Determines if a `__eq__` method should be generated for the class. 

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

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

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

131 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). 

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

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

134 are validated on init. 

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

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

137 new attributes after instantiation. 

138 

139 Returns: 

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

141 

142 Raises: 

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

144 """ 

145 assert init is False, 'pydantic.dataclasses.dataclass only supports init=False' 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

146 assert validate_on_init is not False, 'validate_on_init=False is no longer supported' 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

147 

148 if sys.version_info >= (3, 10): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

149 kwargs = {'kw_only': kw_only, 'slots': slots} 1bcwxdefghaijyzklmnoNOJKLMpqABrstuv

150 else: 

151 kwargs = {} 1DECFGPHI

152 

153 def make_pydantic_fields_compatible(cls: type[Any]) -> None: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

154 """Make sure that stdlib `dataclasses` understands `Field` kwargs like `kw_only` 

155 To do that, we simply change 

156 `x: int = pydantic.Field(..., kw_only=True)` 

157 into 

158 `x: int = dataclasses.field(default=pydantic.Field(..., kw_only=True), kw_only=True)` 

159 """ 

160 for annotation_cls in cls.__mro__: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

161 annotations: dict[str, Any] = getattr(annotation_cls, '__annotations__', {}) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

162 for field_name in annotations: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

163 field_value = getattr(cls, field_name, None) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

164 # Process only if this is an instance of `FieldInfo`. 

165 if not isinstance(field_value, FieldInfo): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

166 continue 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

167 

168 # Initialize arguments for the standard `dataclasses.field`. 

169 field_args: dict = {'default': field_value} 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

170 

171 # Handle `kw_only` for Python 3.10+ 

172 if sys.version_info >= (3, 10) and field_value.kw_only: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

173 field_args['kw_only'] = True 1bcwxdefghaijyzklmnopqABrstuv

174 

175 # Set `repr` attribute if it's explicitly specified to be not `True`. 

176 if field_value.repr is not True: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

177 field_args['repr'] = field_value.repr 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

178 

179 setattr(cls, field_name, dataclasses.field(**field_args)) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

180 # In Python 3.9, when subclassing, information is pulled from cls.__dict__['__annotations__'] 

181 # for annotations, so we must make sure it's initialized before we add to it. 

182 if cls.__dict__.get('__annotations__') is None: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

183 cls.__annotations__ = {} 1DECFGHI

184 cls.__annotations__[field_name] = annotations[field_name] 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

185 

186 def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

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

188 

189 Args: 

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

191 

192 Returns: 

193 A Pydantic dataclass. 

194 """ 

195 from ._internal._utils import is_model_class 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

196 

197 if is_model_class(cls): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

198 raise PydanticUserError( 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

200 code='dataclass-on-model', 

201 ) 

202 

203 original_cls = cls 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

204 

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

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

207 has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

208 if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

209 warn( 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

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

212 category=UserWarning, 

213 stacklevel=2, 

214 ) 

215 

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

217 config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

218 config_wrapper = _config.ConfigWrapper(config_dict) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

219 decorators = _decorators.DecoratorInfos.build(cls) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

220 

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

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

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

224 original_doc = cls.__doc__ 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

225 

226 if _pydantic_dataclasses.is_builtin_dataclass(cls): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

227 # Don't preserve the docstring for vanilla dataclasses, as it may include the signature 

228 # This matches v1 behavior, and there was an explicit test for it 

229 original_doc = None 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

230 

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

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

233 # with all the same parameters. 

234 bases = (cls,) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

235 if issubclass(cls, Generic): 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

236 generic_base = Generic[cls.__parameters__] # type: ignore 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

237 bases = bases + (generic_base,) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

238 cls = types.new_class(cls.__name__, bases) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

239 

240 make_pydantic_fields_compatible(cls) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

241 

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

243 if frozen is not None: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

244 frozen_ = frozen 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

245 if config_wrapper.frozen: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

247 warn( 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

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

250 category=UserWarning, 

251 stacklevel=2, 

252 ) 

253 else: 

254 frozen_ = config_wrapper.frozen or False 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

255 

256 cls = dataclasses.dataclass( # type: ignore[call-overload] 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

257 cls, 

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

259 init=True, 

260 repr=repr, 

261 eq=eq, 

262 order=order, 

263 unsafe_hash=unsafe_hash, 

264 frozen=frozen_, 

265 **kwargs, 

266 ) 

267 

268 if config_wrapper.validate_assignment: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

269 

270 @functools.wraps(cls.__setattr__) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

271 def validated_setattr(instance: Any, field: str, value: str, /) -> None: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

272 type(instance).__pydantic_validator__.validate_assignment(instance, field, value) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

273 

274 cls.__setattr__ = validated_setattr.__get__(None, cls) # type: ignore 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

275 

276 if slots and not hasattr(cls, '__setstate__'): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

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

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

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

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

281 # instance, resulting in attribute errors. 

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

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

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

285 

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

287 def _dataclass_getstate(self: Any) -> list[Any]: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

288 return [getattr(self, f.name) for f in dataclasses.fields(self)] 1bcwxdefghaijyzklmnopqABrstuv

289 

290 def _dataclass_setstate(self: Any, state: list[Any]) -> None: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

291 for field, value in zip(dataclasses.fields(self), state): 1bcwxdefghaijyzklmnopqABrstuv

292 object.__setattr__(self, field.name, value) 1bcwxdefghaijyzklmnopqABrstuv

293 

294 cls.__getstate__ = _dataclass_getstate # pyright: ignore[reportAttributeAccessIssue] 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

295 cls.__setstate__ = _dataclass_setstate # pyright: ignore[reportAttributeAccessIssue] 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

296 

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

298 # It should be set as early as possible: 

299 cls.__is_pydantic_dataclass__ = True 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

300 

301 cls.__pydantic_decorators__ = decorators # type: ignore 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

302 cls.__doc__ = original_doc 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

303 cls.__module__ = original_cls.__module__ 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

304 cls.__qualname__ = original_cls.__qualname__ 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

305 cls.__pydantic_complete__ = False # `complete_dataclass` will set it to `True` if successful. 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

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

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

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

309 _pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

310 return cls 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

311 

312 return create_dataclass if _cls is None else create_dataclass(_cls) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

313 

314 

315__getattr__ = getattr_migration(__name__) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

316 

317if sys.version_info < (3, 11): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

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

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

320 

321 def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn: 1DEbcCaFGijPNHIpq

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

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

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

325 """ 

326 raise TypeError("'InitVar' object is not callable") 1DEbcCaFGijHIpq

327 

328 dataclasses.InitVar.__call__ = _call_initvar 1DEbcCaFGijPNHIpq

329 

330 

331def rebuild_dataclass( 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

332 cls: type[PydanticDataclass], 

333 *, 

334 force: bool = False, 

335 raise_errors: bool = True, 

336 _parent_namespace_depth: int = 2, 

337 _types_namespace: MappingNamespace | None = None, 

338) -> bool | None: 

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

340 

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

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

343 

344 This is analogous to `BaseModel.model_rebuild`. 

345 

346 Args: 

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

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

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

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

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

352 

353 Returns: 

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

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

356 """ 

357 if not force and cls.__pydantic_complete__: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

358 return None 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

359 

360 for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'): 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

361 if attr in cls.__dict__: 361 ↛ 360line 361 didn't jump to line 360 because the condition on line 361 was always true1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

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

364 delattr(cls, attr) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

365 

366 cls.__pydantic_complete__ = False 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

367 

368 if _types_namespace is not None: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

369 rebuild_ns = _types_namespace 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

370 elif _parent_namespace_depth > 0: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

371 rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {} 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

372 else: 

373 rebuild_ns = {} 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

374 

375 ns_resolver = _namespace_utils.NsResolver( 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

376 parent_namespace=rebuild_ns, 

377 ) 

378 

379 return _pydantic_dataclasses.complete_dataclass( 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

380 cls, 

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

382 raise_errors=raise_errors, 

383 ns_resolver=ns_resolver, 

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

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

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

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

388 _force_build=True, 

389 ) 

390 

391 

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

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

394 

395 Args: 

396 class_: The class. 

397 

398 Returns: 

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

400 """ 

401 try: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

402 return '__is_pydantic_dataclass__' in class_.__dict__ and dataclasses.is_dataclass(class_) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

403 except AttributeError: 

404 return False