您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

384 行
16 KiB

  1. """Provide an enhanced dataclass that performs validation."""
  2. from __future__ import annotations as _annotations
  3. import dataclasses
  4. import sys
  5. import types
  6. from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, NoReturn, TypeVar, overload
  7. from warnings import warn
  8. from typing_extensions import TypeGuard, dataclass_transform
  9. from ._internal import _config, _decorators, _namespace_utils, _typing_extra
  10. from ._internal import _dataclasses as _pydantic_dataclasses
  11. from ._migration import getattr_migration
  12. from .config import ConfigDict
  13. from .errors import PydanticUserError
  14. from .fields import Field, FieldInfo, PrivateAttr
  15. if TYPE_CHECKING:
  16. from ._internal._dataclasses import PydanticDataclass
  17. from ._internal._namespace_utils import MappingNamespace
  18. __all__ = 'dataclass', 'rebuild_dataclass'
  19. _T = TypeVar('_T')
  20. if sys.version_info >= (3, 10):
  21. @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
  22. @overload
  23. def dataclass(
  24. *,
  25. init: Literal[False] = False,
  26. repr: bool = True,
  27. eq: bool = True,
  28. order: bool = False,
  29. unsafe_hash: bool = False,
  30. frozen: bool = False,
  31. config: ConfigDict | type[object] | None = None,
  32. validate_on_init: bool | None = None,
  33. kw_only: bool = ...,
  34. slots: bool = ...,
  35. ) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore
  36. ...
  37. @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
  38. @overload
  39. def dataclass(
  40. _cls: type[_T], # type: ignore
  41. *,
  42. init: Literal[False] = False,
  43. repr: bool = True,
  44. eq: bool = True,
  45. order: bool = False,
  46. unsafe_hash: bool = False,
  47. frozen: bool | None = None,
  48. config: ConfigDict | type[object] | None = None,
  49. validate_on_init: bool | None = None,
  50. kw_only: bool = ...,
  51. slots: bool = ...,
  52. ) -> type[PydanticDataclass]: ...
  53. else:
  54. @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
  55. @overload
  56. def dataclass(
  57. *,
  58. init: Literal[False] = False,
  59. repr: bool = True,
  60. eq: bool = True,
  61. order: bool = False,
  62. unsafe_hash: bool = False,
  63. frozen: bool | None = None,
  64. config: ConfigDict | type[object] | None = None,
  65. validate_on_init: bool | None = None,
  66. ) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore
  67. ...
  68. @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
  69. @overload
  70. def dataclass(
  71. _cls: type[_T], # type: ignore
  72. *,
  73. init: Literal[False] = False,
  74. repr: bool = True,
  75. eq: bool = True,
  76. order: bool = False,
  77. unsafe_hash: bool = False,
  78. frozen: bool | None = None,
  79. config: ConfigDict | type[object] | None = None,
  80. validate_on_init: bool | None = None,
  81. ) -> type[PydanticDataclass]: ...
  82. @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
  83. def dataclass(
  84. _cls: type[_T] | None = None,
  85. *,
  86. init: Literal[False] = False,
  87. repr: bool = True,
  88. eq: bool = True,
  89. order: bool = False,
  90. unsafe_hash: bool = False,
  91. frozen: bool | None = None,
  92. config: ConfigDict | type[object] | None = None,
  93. validate_on_init: bool | None = None,
  94. kw_only: bool = False,
  95. slots: bool = False,
  96. ) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]:
  97. """!!! abstract "Usage Documentation"
  98. [`dataclasses`](../concepts/dataclasses.md)
  99. A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`,
  100. but with added validation.
  101. This function should be used similarly to `dataclasses.dataclass`.
  102. Args:
  103. _cls: The target `dataclass`.
  104. init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to
  105. `dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its
  106. own `__init__` function.
  107. repr: A boolean indicating whether to include the field in the `__repr__` output.
  108. eq: Determines if a `__eq__` method should be generated for the class.
  109. order: Determines if comparison magic methods should be generated, such as `__lt__`, but not `__eq__`.
  110. unsafe_hash: Determines if a `__hash__` method should be included in the class, as in `dataclasses.dataclass`.
  111. frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its
  112. 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).
  113. config: The Pydantic config to use for the `dataclass`.
  114. validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses
  115. are validated on init.
  116. kw_only: Determines if `__init__` method parameters must be specified by keyword only. Defaults to `False`.
  117. slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of
  118. new attributes after instantiation.
  119. Returns:
  120. A decorator that accepts a class as its argument and returns a Pydantic `dataclass`.
  121. Raises:
  122. AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`.
  123. """
  124. assert init is False, 'pydantic.dataclasses.dataclass only supports init=False'
  125. assert validate_on_init is not False, 'validate_on_init=False is no longer supported'
  126. if sys.version_info >= (3, 10):
  127. kwargs = {'kw_only': kw_only, 'slots': slots}
  128. else:
  129. kwargs = {}
  130. def make_pydantic_fields_compatible(cls: type[Any]) -> None:
  131. """Make sure that stdlib `dataclasses` understands `Field` kwargs like `kw_only`
  132. To do that, we simply change
  133. `x: int = pydantic.Field(..., kw_only=True)`
  134. into
  135. `x: int = dataclasses.field(default=pydantic.Field(..., kw_only=True), kw_only=True)`
  136. """
  137. for annotation_cls in cls.__mro__:
  138. annotations: dict[str, Any] = getattr(annotation_cls, '__annotations__', {})
  139. for field_name in annotations:
  140. field_value = getattr(cls, field_name, None)
  141. # Process only if this is an instance of `FieldInfo`.
  142. if not isinstance(field_value, FieldInfo):
  143. continue
  144. # Initialize arguments for the standard `dataclasses.field`.
  145. field_args: dict = {'default': field_value}
  146. # Handle `kw_only` for Python 3.10+
  147. if sys.version_info >= (3, 10) and field_value.kw_only:
  148. field_args['kw_only'] = True
  149. # Set `repr` attribute if it's explicitly specified to be not `True`.
  150. if field_value.repr is not True:
  151. field_args['repr'] = field_value.repr
  152. setattr(cls, field_name, dataclasses.field(**field_args))
  153. # In Python 3.9, when subclassing, information is pulled from cls.__dict__['__annotations__']
  154. # for annotations, so we must make sure it's initialized before we add to it.
  155. if cls.__dict__.get('__annotations__') is None:
  156. cls.__annotations__ = {}
  157. cls.__annotations__[field_name] = annotations[field_name]
  158. def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]:
  159. """Create a Pydantic dataclass from a regular dataclass.
  160. Args:
  161. cls: The class to create the Pydantic dataclass from.
  162. Returns:
  163. A Pydantic dataclass.
  164. """
  165. from ._internal._utils import is_model_class
  166. if is_model_class(cls):
  167. raise PydanticUserError(
  168. f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model',
  169. code='dataclass-on-model',
  170. )
  171. original_cls = cls
  172. # we warn on conflicting config specifications, but only if the class doesn't have a dataclass base
  173. # because a dataclass base might provide a __pydantic_config__ attribute that we don't want to warn about
  174. has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__)
  175. if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'):
  176. warn(
  177. f'`config` is set via both the `dataclass` decorator and `__pydantic_config__` for dataclass {cls.__name__}. '
  178. f'The `config` specification from `dataclass` decorator will take priority.',
  179. category=UserWarning,
  180. stacklevel=2,
  181. )
  182. # if config is not explicitly provided, try to read it from the type
  183. config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None)
  184. config_wrapper = _config.ConfigWrapper(config_dict)
  185. decorators = _decorators.DecoratorInfos.build(cls)
  186. # Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator
  187. # Otherwise, classes with no __doc__ will have their signature added into the JSON schema description,
  188. # since dataclasses.dataclass will set this as the __doc__
  189. original_doc = cls.__doc__
  190. if _pydantic_dataclasses.is_builtin_dataclass(cls):
  191. # Don't preserve the docstring for vanilla dataclasses, as it may include the signature
  192. # This matches v1 behavior, and there was an explicit test for it
  193. original_doc = None
  194. # We don't want to add validation to the existing std lib dataclass, so we will subclass it
  195. # If the class is generic, we need to make sure the subclass also inherits from Generic
  196. # with all the same parameters.
  197. bases = (cls,)
  198. if issubclass(cls, Generic):
  199. generic_base = Generic[cls.__parameters__] # type: ignore
  200. bases = bases + (generic_base,)
  201. cls = types.new_class(cls.__name__, bases)
  202. make_pydantic_fields_compatible(cls)
  203. # Respect frozen setting from dataclass constructor and fallback to config setting if not provided
  204. if frozen is not None:
  205. frozen_ = frozen
  206. if config_wrapper.frozen:
  207. # It's not recommended to define both, as the setting from the dataclass decorator will take priority.
  208. warn(
  209. f'`frozen` is set via both the `dataclass` decorator and `config` for dataclass {cls.__name__!r}.'
  210. 'This is not recommended. The `frozen` specification on `dataclass` will take priority.',
  211. category=UserWarning,
  212. stacklevel=2,
  213. )
  214. else:
  215. frozen_ = config_wrapper.frozen or False
  216. cls = dataclasses.dataclass( # type: ignore[call-overload]
  217. cls,
  218. # the value of init here doesn't affect anything except that it makes it easier to generate a signature
  219. init=True,
  220. repr=repr,
  221. eq=eq,
  222. order=order,
  223. unsafe_hash=unsafe_hash,
  224. frozen=frozen_,
  225. **kwargs,
  226. )
  227. # This is an undocumented attribute to distinguish stdlib/Pydantic dataclasses.
  228. # It should be set as early as possible:
  229. cls.__is_pydantic_dataclass__ = True
  230. cls.__pydantic_decorators__ = decorators # type: ignore
  231. cls.__doc__ = original_doc
  232. cls.__module__ = original_cls.__module__
  233. cls.__qualname__ = original_cls.__qualname__
  234. cls.__pydantic_fields_complete__ = classmethod(_pydantic_fields_complete)
  235. cls.__pydantic_complete__ = False # `complete_dataclass` will set it to `True` if successful.
  236. # TODO `parent_namespace` is currently None, but we could do the same thing as Pydantic models:
  237. # fetch the parent ns using `parent_frame_namespace` (if the dataclass was defined in a function),
  238. # and possibly cache it (see the `__pydantic_parent_namespace__` logic for models).
  239. _pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False)
  240. return cls
  241. return create_dataclass if _cls is None else create_dataclass(_cls)
  242. def _pydantic_fields_complete(cls: type[PydanticDataclass]) -> bool:
  243. """Return whether the fields where successfully collected (i.e. type hints were successfully resolves).
  244. This is a private property, not meant to be used outside Pydantic.
  245. """
  246. return all(field_info._complete for field_info in cls.__pydantic_fields__.values())
  247. __getattr__ = getattr_migration(__name__)
  248. if sys.version_info < (3, 11):
  249. # Monkeypatch dataclasses.InitVar so that typing doesn't error if it occurs as a type when evaluating type hints
  250. # Starting in 3.11, typing.get_type_hints will not raise an error if the retrieved type hints are not callable.
  251. def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn:
  252. """This function does nothing but raise an error that is as similar as possible to what you'd get
  253. if you were to try calling `InitVar[int]()` without this monkeypatch. The whole purpose is just
  254. to ensure typing._type_check does not error if the type hint evaluates to `InitVar[<parameter>]`.
  255. """
  256. raise TypeError("'InitVar' object is not callable")
  257. dataclasses.InitVar.__call__ = _call_initvar
  258. def rebuild_dataclass(
  259. cls: type[PydanticDataclass],
  260. *,
  261. force: bool = False,
  262. raise_errors: bool = True,
  263. _parent_namespace_depth: int = 2,
  264. _types_namespace: MappingNamespace | None = None,
  265. ) -> bool | None:
  266. """Try to rebuild the pydantic-core schema for the dataclass.
  267. This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
  268. the initial attempt to build the schema, and automatic rebuilding fails.
  269. This is analogous to `BaseModel.model_rebuild`.
  270. Args:
  271. cls: The class to rebuild the pydantic-core schema for.
  272. force: Whether to force the rebuilding of the schema, defaults to `False`.
  273. raise_errors: Whether to raise errors, defaults to `True`.
  274. _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
  275. _types_namespace: The types namespace, defaults to `None`.
  276. Returns:
  277. Returns `None` if the schema is already "complete" and rebuilding was not required.
  278. If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
  279. """
  280. if not force and cls.__pydantic_complete__:
  281. return None
  282. for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
  283. if attr in cls.__dict__:
  284. # Deleting the validator/serializer is necessary as otherwise they can get reused in
  285. # pydantic-core. Same applies for the core schema that can be reused in schema generation.
  286. delattr(cls, attr)
  287. cls.__pydantic_complete__ = False
  288. if _types_namespace is not None:
  289. rebuild_ns = _types_namespace
  290. elif _parent_namespace_depth > 0:
  291. rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
  292. else:
  293. rebuild_ns = {}
  294. ns_resolver = _namespace_utils.NsResolver(
  295. parent_namespace=rebuild_ns,
  296. )
  297. return _pydantic_dataclasses.complete_dataclass(
  298. cls,
  299. _config.ConfigWrapper(cls.__pydantic_config__, check=False),
  300. raise_errors=raise_errors,
  301. ns_resolver=ns_resolver,
  302. # We could provide a different config instead (with `'defer_build'` set to `True`)
  303. # of this explicit `_force_build` argument, but because config can come from the
  304. # decorator parameter or the `__pydantic_config__` attribute, `complete_dataclass`
  305. # will overwrite `__pydantic_config__` with the provided config above:
  306. _force_build=True,
  307. )
  308. def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]:
  309. """Whether a class is a pydantic dataclass.
  310. Args:
  311. class_: The class.
  312. Returns:
  313. `True` if the class is a pydantic dataclass, `False` otherwise.
  314. """
  315. try:
  316. return '__is_pydantic_dataclass__' in class_.__dict__ and dataclasses.is_dataclass(class_)
  317. except AttributeError:
  318. return False