Coverage for pydantic / root_model.py: 100.00%

64 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""RootModel class and type definitions.""" 

2 

3from __future__ import annotations as _annotations 1gabhijkcdlmnsoefpqr

4 

5from collections.abc import Callable 1gabhijkcdlmnsoefpqr

6from copy import copy, deepcopy 1gabhijkcdlmnsoefpqr

7from typing import TYPE_CHECKING, Any, Generic, Literal, Self, TypeVar, dataclass_transform 1gabhijkcdlmnsoefpqr

8 

9from pydantic_core import PydanticUndefined 1gabhijkcdlmnsoefpqr

10 

11from . import PydanticUserError 1gabhijkcdlmnsoefpqr

12from ._internal import _model_construction, _repr 1gabhijkcdlmnsoefpqr

13from .main import BaseModel, _object_setattr 1gabhijkcdlmnsoefpqr

14 

15if TYPE_CHECKING: 1gabhijkcdlmnsoefpqr

16 from .fields import Field as PydanticModelField 1gabhijkcdlmnoefpqr

17 from .fields import PrivateAttr as PydanticModelPrivateAttr 1gabhijkcdlmnoefpqr

18 from .main import IncEx 1gabhijkcdlmnoefpqr

19 

20 # dataclass_transform could be applied to RootModel directly, but `ModelMetaclass`'s dataclass_transform 

21 # takes priority (at least with pyright). We trick type checkers into thinking we apply dataclass_transform 

22 # on a new metaclass. 

23 @dataclass_transform(kw_only_default=False, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr)) 1gabhijkcdlmnoefpqr

24 class _RootModelMetaclass(_model_construction.ModelMetaclass): ... 1gabhijkcdlmnoefpqr

25else: 

26 _RootModelMetaclass = _model_construction.ModelMetaclass 1gabhijkcdlmnsoefpqr

27 

28__all__ = ('RootModel',) 1gabhijkcdlmnsoefpqr

29 

30RootModelRootType = TypeVar('RootModelRootType') 1gabhijkcdlmnsoefpqr

31 

32 

33class RootModel(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetaclass): 1gabhijkcdlmnsoefpqr

34 """!!! abstract "Usage Documentation" 

35 [`RootModel` and Custom Root Types](../concepts/models.md#rootmodel-and-custom-root-types) 

36 

37 A Pydantic `BaseModel` for the root object of the model. 

38 

39 Attributes: 

40 root: The root object of the model. 

41 __pydantic_root_model__: Whether the model is a RootModel. 

42 __pydantic_private__: Private fields in the model. 

43 __pydantic_extra__: Extra fields in the model. 

44 

45 """ 

46 

47 __pydantic_root_model__ = True 1gabhijkcdlmnsoefpqr

48 __pydantic_private__ = None 1gabhijkcdlmnsoefpqr

49 __pydantic_extra__ = None 1gabhijkcdlmnsoefpqr

50 

51 root: RootModelRootType 1gabhijkcdlmnsoefpqr

52 

53 def __init_subclass__(cls, **kwargs): 1gabhijkcdlmnsoefpqr

54 extra = cls.model_config.get('extra') 1gabhijkcdlmnsoefpqr

55 if extra is not None: 1gabhijkcdlmnsoefpqr

56 raise PydanticUserError( 1gabhijkcdlmnoefpqr

57 "`RootModel` does not support setting `model_config['extra']`", code='root-model-extra' 

58 ) 

59 super().__init_subclass__(**kwargs) 1gabhijkcdlmnsoefpqr

60 

61 def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None: # type: ignore 1gabhijkcdlmnsoefpqr

62 __tracebackhide__ = True 1gabhijkcdlmnoefpqr

63 if data: 1gabhijkcdlmnoefpqr

64 if root is not PydanticUndefined: 1gabhijkcdlmnoefpqr

65 raise ValueError( 1gabhijkcdlmnoefpqr

66 '"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments' 

67 ) 

68 root = data # type: ignore 1gabhijkcdlmnoefpqr

69 self.__pydantic_validator__.validate_python(root, self_instance=self) 1gabhijkcdlmnoefpqr

70 

71 __init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess] 1gabhijkcdlmnsoefpqr

72 

73 @classmethod 1gabhijkcdlmnsoefpqr

74 def model_construct(cls, root: RootModelRootType, _fields_set: set[str] | None = None) -> Self: # type: ignore 1gabhijkcdlmnsoefpqr

75 """Create a new model using the provided root object and update fields set. 

76 

77 Args: 

78 root: The root object of the model. 

79 _fields_set: The set of fields to be updated. 

80 

81 Returns: 

82 The new model. 

83 

84 Raises: 

85 NotImplemented: If the model is not a subclass of `RootModel`. 

86 """ 

87 return super().model_construct(root=root, _fields_set=_fields_set) 1gabhijkcdlmnoefpqr

88 

89 def __getstate__(self) -> dict[Any, Any]: 1gabhijkcdlmnsoefpqr

90 return { 1gabhijkcdlmnoefpqr

91 '__dict__': self.__dict__, 

92 '__pydantic_fields_set__': self.__pydantic_fields_set__, 

93 } 

94 

95 def __setstate__(self, state: dict[Any, Any]) -> None: 1gabhijkcdlmnsoefpqr

96 _object_setattr(self, '__pydantic_fields_set__', state['__pydantic_fields_set__']) 1gabhijkcdlmnoefpqr

97 _object_setattr(self, '__dict__', state['__dict__']) 1gabhijkcdlmnoefpqr

98 

99 def __copy__(self) -> Self: 1gabhijkcdlmnsoefpqr

100 """Returns a shallow copy of the model.""" 

101 cls = type(self) 1gabhijkcdlmnoefpqr

102 m = cls.__new__(cls) 1gabhijkcdlmnoefpqr

103 new_dict = copy(self.__dict__) 1gabhijkcdlmnoefpqr

104 new_dict['root'] = copy(self.__dict__['root']) # pyright: ignore[reportIndexIssue] (https://github.com/microsoft/pyright/issues/11548) 1gabhijkcdlmnoefpqr

105 # Private attributes live in `__dict__` on root models, so give the copy its own: 

106 private = new_dict.get('__pydantic_private__') 1gabhijkcdlmnoefpqr

107 if private is not None: 1gabhijkcdlmnoefpqr

108 new_dict['__pydantic_private__'] = { # pyright: ignore[reportIndexIssue] (https://github.com/microsoft/pyright/issues/11548) 1gabhijkcdlmnoefpqr

109 k: v for k, v in private.items() if v is not PydanticUndefined 

110 } 

111 _object_setattr(m, '__dict__', new_dict) 1gabhijkcdlmnoefpqr

112 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 1gabhijkcdlmnoefpqr

113 return m 1gabhijkcdlmnoefpqr

114 

115 def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self: 1gabhijkcdlmnsoefpqr

116 """Returns a deep copy of the model.""" 

117 if memo is None: 1gabhijkcdlmnoefpqr

118 memo = {} 1gabhijkcdlmnoefpqr

119 cls = type(self) 1gabhijkcdlmnoefpqr

120 m = cls.__new__(cls) 1gabhijkcdlmnoefpqr

121 memo[id(self)] = m 1gabhijkcdlmnoefpqr

122 _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo)) 1gabhijkcdlmnoefpqr

123 # This next line doesn't need a deepcopy because __pydantic_fields_set__ only contains strings, 

124 # and attempting a deepcopy would be marginally slower. 

125 _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) 1gabhijkcdlmnoefpqr

126 return m 1gabhijkcdlmnoefpqr

127 

128 if TYPE_CHECKING: 1gabhijkcdlmnsoefpqr

129 # This `model_dump()` definition is only provided to get a more accurate return type for type checkers 

130 # (no override is actually necessary at runtime). Generally, the return type will be `RootModelRootType`, 

131 # assuming that `RootModelRootType` is not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` 

132 # subclass, then the return type will likely be `dict[str, Any]`, as `model_dump()` calls are recursive. 

133 # The return type could even be something different, in the case of a custom serializer. Thus, `Any` is 

134 # used here to catch all of these cases. 

135 

136 def model_dump( # type: ignore 1gabhijkcdlmnoefpqr

137 self, 

138 *, 

139 mode: Literal['json', 'python'] | str = 'python', 1gabhijkcdlmnoefpqr

140 include: IncEx | None = None, 1gabhijkcdlmnoefpqr

141 exclude: IncEx | None = None, 1gabhijkcdlmnoefpqr

142 context: Any | None = None, 1gabhijkcdlmnoefpqr

143 by_alias: bool | None = None, 1gabhijkcdlmnoefpqr

144 exclude_unset: bool = False, 1gabhijkcdlmnoefpqr

145 exclude_defaults: bool = False, 1gabhijkcdlmnoefpqr

146 exclude_none: bool = False, 1gabhijkcdlmnoefpqr

147 exclude_computed_fields: bool = False, 1gabhijkcdlmnoefpqr

148 round_trip: bool = False, 1gabhijkcdlmnoefpqr

149 warnings: bool | Literal['none', 'warn', 'error'] = True, 1gabhijkcdlmnoefpqr

150 fallback: Callable[[Any], Any] | None = None, 1gabhijkcdlmnoefpqr

151 serialize_as_any: bool = False, 1gabhijkcdlmnoefpqr

152 polymorphic_serialization: bool | None = None, 1gabhijkcdlmnoefpqr

153 ) -> Any: 1abcdef

154 """!!! abstract "Usage Documentation" 

155 [`model_dump`](../concepts/serialization.md#python-mode) 

156 

157 Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. 

158 

159 Args: 

160 mode: The mode in which `to_python` should run. 

161 If mode is 'json', the output will only contain JSON serializable types. 

162 If mode is 'python', the output may contain non-JSON-serializable Python objects. 

163 include: A set of fields to include in the output. 

164 exclude: A set of fields to exclude from the output. 

165 context: Additional context to pass to the serializer. 

166 by_alias: Whether to use the field's alias in the dictionary key if defined. 

167 exclude_unset: Whether to exclude fields that have not been explicitly set. 

168 exclude_defaults: Whether to exclude fields that are set to their default value. 

169 exclude_none: Whether to exclude fields that have a value of `None`. 

170 exclude_computed_fields: Whether to exclude computed fields. 

171 While this can be useful for round-tripping, it is usually recommended to use the dedicated 

172 `round_trip` parameter instead. 

173 round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. 

174 warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, 

175 "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. 

176 fallback: A function to call when an unknown value is encountered. If not provided, 

177 a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. 

178 serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. 

179 polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call. 

180 

181 Returns: 

182 A dictionary representation of the model. 

183 """ 

184 ... 

185 

186 def __eq__(self, other: Any) -> bool: 1gabhijkcdlmnsoefpqr

187 if not isinstance(other, RootModel): 1gabhijkcdlmnoefpqr

188 return NotImplemented 1gabhijkcdlmnoefpqr

189 return self.__pydantic_fields__['root'].annotation == other.__pydantic_fields__[ 1gabhijkcdlmnoefpqr

190 'root' 

191 ].annotation and super().__eq__(other) 

192 

193 def __repr_args__(self) -> _repr.ReprArgs: 1gabhijkcdlmnsoefpqr

194 if self.__pydantic_fields__['root'].repr: 1gabhijkcdlmnoefpqr

195 yield 'root', self.root 1gabhijkcdlmnoefpqr