Coverage for pydantic/dataclasses.py: 98.09%

113 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-05-01 08:13 +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 decorators.update_from_config(config_wrapper) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

221 

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

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

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

225 original_doc = cls.__doc__ 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

226 

227 if _pydantic_dataclasses.is_stdlib_dataclass(cls): 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

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

229 # which we don't want to preserve. 

230 original_doc = None 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

231 

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

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

234 # with all the same parameters. 

235 bases = (cls,) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

236 if issubclass(cls, Generic): 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

238 bases = bases + (generic_base,) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

240 

241 make_pydantic_fields_compatible(cls) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

242 

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

244 if frozen is not None: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

245 frozen_ = frozen 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

246 if config_wrapper.frozen: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

248 warn( 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

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

251 category=UserWarning, 

252 stacklevel=2, 

253 ) 

254 else: 

255 frozen_ = config_wrapper.frozen or False 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

256 

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

258 cls, 

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

260 init=True, 

261 repr=repr, 

262 eq=eq, 

263 order=order, 

264 unsafe_hash=unsafe_hash, 

265 frozen=frozen_, 

266 **kwargs, 

267 ) 

268 

269 if config_wrapper.validate_assignment: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

270 

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

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

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

274 

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

276 

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

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

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

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

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

282 # instance, resulting in attribute errors. 

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

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

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

286 

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

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

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

290 

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

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

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

294 

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

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

297 

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

299 # It should be set as early as possible: 

300 cls.__is_pydantic_dataclass__ = True 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

301 

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

303 cls.__doc__ = original_doc 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

304 cls.__module__ = original_cls.__module__ 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

305 cls.__qualname__ = original_cls.__qualname__ 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

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

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

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

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

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

311 return cls 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

312 

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

314 

315 

316__getattr__ = getattr_migration(__name__) 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

317 

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

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

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

321 

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

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

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

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

326 """ 

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

328 

329 dataclasses.InitVar.__call__ = _call_initvar 1DEbcCaFGijPNHIpq

330 

331 

332def rebuild_dataclass( 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

333 cls: type[PydanticDataclass], 

334 *, 

335 force: bool = False, 

336 raise_errors: bool = True, 

337 _parent_namespace_depth: int = 2, 

338 _types_namespace: MappingNamespace | None = None, 

339) -> bool | None: 

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

341 

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

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

344 

345 This is analogous to `BaseModel.model_rebuild`. 

346 

347 Args: 

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

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

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

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

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

353 

354 Returns: 

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

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

357 """ 

358 if not force and cls.__pydantic_complete__: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

359 return None 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

360 

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

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

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

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

365 delattr(cls, attr) 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

366 

367 cls.__pydantic_complete__ = False 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

368 

369 if _types_namespace is not None: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

370 rebuild_ns = _types_namespace 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

371 elif _parent_namespace_depth > 0: 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

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

373 else: 

374 rebuild_ns = {} 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

375 

376 ns_resolver = _namespace_utils.NsResolver( 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

377 parent_namespace=rebuild_ns, 

378 ) 

379 

380 return _pydantic_dataclasses.complete_dataclass( 1DEbcwxdefghCaFGijyzklmnoHIpqABrstuv

381 cls, 

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

383 raise_errors=raise_errors, 

384 ns_resolver=ns_resolver, 

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

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

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

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

389 _force_build=True, 

390 ) 

391 

392 

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

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

395 

396 Args: 

397 class_: The class. 

398 

399 Returns: 

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

401 """ 

402 try: 1DEbcwxdefghCaFGijyzklmnoPNOJKLMHIpqABrstuv

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

404 except AttributeError: 

405 return False