Coverage for pydantic/_internal/_dataclasses.py: 95.59%

62 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-05-02 08:21 +0000

1"""Private logic for creating pydantic dataclasses.""" 

2 

3from __future__ import annotations as _annotations 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

4 

5import typing 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

6import warnings 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

7from functools import partial 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

8from typing import Any, ClassVar 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

9 

10from pydantic_core import ( 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

11 ArgsKwargs, 

12 SchemaSerializer, 

13 SchemaValidator, 

14 core_schema, 

15) 

16from typing_extensions import TypeIs 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

17 

18from ..errors import PydanticUndefinedAnnotation 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

19from ..plugin._schema_validator import PluggableSchemaValidator, create_schema_validator 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

20from ..warnings import PydanticDeprecatedSince20 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

21from . import _config, _decorators 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

22from ._fields import collect_dataclass_fields 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

23from ._generate_schema import GenerateSchema, InvalidSchemaError 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

24from ._generics import get_standard_typevars_map 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

25from ._mock_val_ser import set_dataclass_mocks 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

26from ._namespace_utils import NsResolver 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

27from ._signature import generate_pydantic_signature 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

28from ._utils import LazyClassAttribute 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

29 

30if typing.TYPE_CHECKING: 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

31 from _typeshed import DataclassInstance as StandardDataclass 

32 

33 from ..config import ConfigDict 

34 from ..fields import FieldInfo 

35 

36 class PydanticDataclass(StandardDataclass, typing.Protocol): 

37 """A protocol containing attributes only available once a class has been decorated as a Pydantic dataclass. 

38 

39 Attributes: 

40 __pydantic_config__: Pydantic-specific configuration settings for the dataclass. 

41 __pydantic_complete__: Whether dataclass building is completed, or if there are still undefined fields. 

42 __pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer. 

43 __pydantic_decorators__: Metadata containing the decorators defined on the dataclass. 

44 __pydantic_fields__: Metadata about the fields defined on the dataclass. 

45 __pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the dataclass. 

46 __pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the dataclass. 

47 """ 

48 

49 __pydantic_config__: ClassVar[ConfigDict] 

50 __pydantic_complete__: ClassVar[bool] 

51 __pydantic_core_schema__: ClassVar[core_schema.CoreSchema] 

52 __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] 

53 __pydantic_fields__: ClassVar[dict[str, FieldInfo]] 

54 __pydantic_serializer__: ClassVar[SchemaSerializer] 

55 __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator] 

56 

57else: 

58 # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 

59 # and https://youtrack.jetbrains.com/issue/PY-51428 

60 DeprecationWarning = PydanticDeprecatedSince20 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

61 

62 

63def set_dataclass_fields( 1abcdefghijklmnopqrstuvJKLMNOPwxyzABCDEFG

64 cls: type[StandardDataclass], 

65 config_wrapper: _config.ConfigWrapper, 

66 ns_resolver: NsResolver | None = None, 

67) -> None: 

68 """Collect and set `cls.__pydantic_fields__`. 

69 

70 Args: 

71 cls: The class. 

72 config_wrapper: The config wrapper instance. 

73 ns_resolver: Namespace resolver to use when getting dataclass annotations. 

74 """ 

75 typevars_map = get_standard_typevars_map(cls) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

76 fields = collect_dataclass_fields( 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

77 cls, ns_resolver=ns_resolver, typevars_map=typevars_map, config_wrapper=config_wrapper 

78 ) 

79 

80 cls.__pydantic_fields__ = fields # type: ignore 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

81 

82 

83def complete_dataclass( 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

84 cls: type[Any], 

85 config_wrapper: _config.ConfigWrapper, 

86 *, 

87 raise_errors: bool = True, 

88 ns_resolver: NsResolver | None = None, 

89 _force_build: bool = False, 

90) -> bool: 

91 """Finish building a pydantic dataclass. 

92 

93 This logic is called on a class which has already been wrapped in `dataclasses.dataclass()`. 

94 

95 This is somewhat analogous to `pydantic._internal._model_construction.complete_model_class`. 

96 

97 Args: 

98 cls: The class. 

99 config_wrapper: The config wrapper instance. 

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

101 ns_resolver: The namespace resolver instance to use when collecting dataclass fields 

102 and during schema building. 

103 _force_build: Whether to force building the dataclass, no matter if 

104 [`defer_build`][pydantic.config.ConfigDict.defer_build] is set. 

105 

106 Returns: 

107 `True` if building a pydantic dataclass is successfully completed, `False` otherwise. 

108 

109 Raises: 

110 PydanticUndefinedAnnotation: If `raise_error` is `True` and there is an undefined annotations. 

111 """ 

112 original_init = cls.__init__ 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

113 

114 # dataclass.__init__ must be defined here so its `__qualname__` can be changed since functions can't be copied, 

115 # and so that the mock validator is used if building was deferred: 

116 def __init__(__dataclass_self__: PydanticDataclass, *args: Any, **kwargs: Any) -> None: 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

117 __tracebackhide__ = True 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

118 s = __dataclass_self__ 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

119 s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

120 

121 __init__.__qualname__ = f'{cls.__qualname__}.__init__' 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

122 

123 cls.__init__ = __init__ # type: ignore 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

124 cls.__pydantic_config__ = config_wrapper.config_dict # type: ignore 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

125 

126 set_dataclass_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

127 

128 if not _force_build and config_wrapper.defer_build: 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

129 set_dataclass_mocks(cls) 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG

130 return False 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG

131 

132 if hasattr(cls, '__post_init_post_parse__'): 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

133 warnings.warn( 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG

134 'Support for `__post_init_post_parse__` has been dropped, the method will not be called', DeprecationWarning 

135 ) 

136 

137 typevars_map = get_standard_typevars_map(cls) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

138 gen_schema = GenerateSchema( 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

139 config_wrapper, 

140 ns_resolver=ns_resolver, 

141 typevars_map=typevars_map, 

142 ) 

143 

144 # set __signature__ attr only for the class, but not for its instances 

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

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

147 cls.__signature__ = LazyClassAttribute( 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

148 '__signature__', 

149 partial( 

150 generate_pydantic_signature, 

151 # It's important that we reference the `original_init` here, 

152 # as it is the one synthesized by the stdlib `dataclass` module: 

153 init=original_init, 

154 fields=cls.__pydantic_fields__, # type: ignore 

155 validate_by_name=config_wrapper.validate_by_name, 

156 extra=config_wrapper.extra, 

157 is_dataclass=True, 

158 ), 

159 ) 

160 

161 try: 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

162 schema = gen_schema.generate_schema(cls) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

163 except PydanticUndefinedAnnotation as e: 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG

164 if raise_errors: 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG

165 raise 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG

166 set_dataclass_mocks(cls, f'`{e.name}`') 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG

167 return False 1abcdefghijkHIlmnopqrstuvwxyzABCDEFG

168 

169 core_config = config_wrapper.core_config(title=cls.__name__) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

170 

171 try: 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

172 schema = gen_schema.clean_schema(schema) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

173 except InvalidSchemaError: 

174 set_dataclass_mocks(cls) 

175 return False 

176 

177 # We are about to set all the remaining required properties expected for this cast; 

178 # __pydantic_decorators__ and __pydantic_fields__ should already be set 

179 cls = typing.cast('type[PydanticDataclass]', cls) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

180 

181 cls.__pydantic_core_schema__ = schema 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

182 cls.__pydantic_validator__ = create_schema_validator( 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

183 schema, cls, cls.__module__, cls.__qualname__, 'dataclass', core_config, config_wrapper.plugin_settings 

184 ) 

185 cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config) 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

186 cls.__pydantic_complete__ = True 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

187 return True 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

188 

189 

190def is_stdlib_dataclass(cls: type[Any], /) -> TypeIs[type[StandardDataclass]]: 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG

191 """Returns `True` if the class is a stdlib dataclass and *not* a Pydantic dataclass. 

192 

193 Unlike the stdlib `dataclasses.is_dataclass()` function, this does *not* include subclasses 

194 of a dataclass that are themselves not dataclasses. 

195 

196 Args: 

197 cls: The class. 

198 

199 Returns: 

200 `True` if the class is a stdlib dataclass, `False` otherwise. 

201 """ 

202 return '__dataclass_fields__' in cls.__dict__ and not hasattr(cls, '__pydantic_validator__') 1abcdefghijkHIlmnopqrstuvJKLMNOPwxyzABCDEFG