Coverage for pydantic / _internal / _config.py: 100.00%

137 statements  

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

1from __future__ import annotations as _annotations 1abcdefghijklsmnopqr

2 

3from collections.abc import Callable 1abcdefghijklsmnopqr

4from re import Pattern 1abcdefghijklsmnopqr

5from typing import ( 1abcdefghijklsmnopqr

6 TYPE_CHECKING, 

7 Any, 

8 Literal, 

9 Self, 

10 cast, 

11) 

12 

13from pydantic_core import core_schema 1abcdefghijklsmnopqr

14 

15from ..aliases import AliasGenerator 1abcdefghijklsmnopqr

16from ..config import ConfigDict, ExtraValues, JsonDict, JsonEncoder, JsonSchemaExtraCallable 1abcdefghijklsmnopqr

17from ..errors import PydanticUserError 1abcdefghijklsmnopqr

18from ._contextlib import contextmanager 1abcdefghijklsmnopqr

19 

20if TYPE_CHECKING: 1abcdefghijklsmnopqr

21 from ..fields import ComputedFieldInfo, FieldInfo 

22 

23# Maps the `ConfigDict` keys that have a `CoreConfig` counterpart to the corresponding 

24# `CoreConfig` key (`'title'` is omitted as it requires special handling, see `ConfigWrapper.core_config()`): 

25_config_dict_to_core_config_key: dict[str, str] = { 1abcdefghijklsmnopqr

26 'extra': 'extra_fields_behavior', 

27 'allow_inf_nan': 'allow_inf_nan', 

28 'str_strip_whitespace': 'str_strip_whitespace', 

29 'str_to_lower': 'str_to_lower', 

30 'str_to_upper': 'str_to_upper', 

31 'strict': 'strict', 

32 'ser_json_timedelta': 'ser_json_timedelta', 

33 'ser_json_temporal': 'ser_json_temporal', 

34 'val_temporal_unit': 'val_temporal_unit', 

35 'ser_json_bytes': 'ser_json_bytes', 

36 'val_json_bytes': 'val_json_bytes', 

37 'ser_json_inf_nan': 'ser_json_inf_nan', 

38 'from_attributes': 'from_attributes', 

39 'loc_by_alias': 'loc_by_alias', 

40 'revalidate_instances': 'revalidate_instances', 

41 'validate_default': 'validate_default', 

42 'str_max_length': 'str_max_length', 

43 'str_min_length': 'str_min_length', 

44 'hide_input_in_errors': 'hide_input_in_errors', 

45 'coerce_numbers_to_str': 'coerce_numbers_to_str', 

46 'regex_engine': 'regex_engine', 

47 'validation_error_cause': 'validation_error_cause', 

48 'cache_strings': 'cache_strings', 

49 'validate_by_alias': 'validate_by_alias', 

50 'validate_by_name': 'validate_by_name', 

51 'serialize_by_alias': 'serialize_by_alias', 

52 'url_preserve_empty_path': 'url_preserve_empty_path', 

53 'polymorphic_serialization': 'polymorphic_serialization', 

54} 

55 

56 

57class ConfigWrapper: 1abcdefghijklsmnopqr

58 """Internal wrapper for Config which exposes ConfigDict items as attributes.""" 

59 

60 __slots__ = ('config_dict', 'effective_config') 1abcdefghijklsmnopqr

61 

62 config_dict: ConfigDict 1abcdefghijklsmnopqr

63 """The configuration as declared by the user. 1abcdefghijklsmnopqr

64 

65 This is the mapping exposed as the `model_config` attribute of models (and the 

66 `__pydantic_config__` attribute of dataclasses), and the one merged with the 

67 configuration of the bases when subclassing. As such, it must never be mutated. 

68 """ 

69 

70 effective_config: ConfigDict 1abcdefghijklsmnopqr

71 """The configuration actually in effect, with the deprecated settings applied. 1abcdefghijklsmnopqr

72 

73 This is what every consumer of the configuration should read (both the attribute 

74 access on this wrapper and `core_config()` do), as `config_dict` alone does not 

75 account for the deprecated settings (see `_build_effective_config()`). 

76 """ 

77 

78 # all annotations are copied directly from ConfigDict, and should be kept up to date, a test will fail if they 

79 # stop matching 

80 title: str | None 1abcdefghijklsmnopqr

81 str_to_lower: bool 1abcdefghijklsmnopqr

82 str_to_upper: bool 1abcdefghijklsmnopqr

83 str_strip_whitespace: bool 1abcdefghijklsmnopqr

84 str_min_length: int 1abcdefghijklsmnopqr

85 str_max_length: int | None 1abcdefghijklsmnopqr

86 extra: ExtraValues | None 1abcdefghijklsmnopqr

87 frozen: bool 1abcdefghijklsmnopqr

88 populate_by_name: bool 1abcdefghijklsmnopqr

89 use_enum_values: bool 1abcdefghijklsmnopqr

90 validate_assignment: bool 1abcdefghijklsmnopqr

91 arbitrary_types_allowed: bool 1abcdefghijklsmnopqr

92 from_attributes: bool 1abcdefghijklsmnopqr

93 # whether to use the actual key provided in the data (e.g. alias or first alias for "field required" errors) instead of field_names 

94 # to construct error `loc`s, default `True` 

95 loc_by_alias: bool 1abcdefghijklsmnopqr

96 alias_generator: Callable[[str], str] | AliasGenerator | None 1abcdefghijklsmnopqr

97 model_title_generator: Callable[[type], str] | None 1abcdefghijklsmnopqr

98 field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None 1abcdefghijklsmnopqr

99 ignored_types: tuple[type, ...] 1abcdefghijklsmnopqr

100 allow_inf_nan: bool 1abcdefghijklsmnopqr

101 json_schema_extra: JsonDict | JsonSchemaExtraCallable | None 1abcdefghijklsmnopqr

102 json_encoders: dict[type[object], JsonEncoder] | None 1abcdefghijklsmnopqr

103 

104 # new in V2 

105 strict: bool 1abcdefghijklsmnopqr

106 # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never' 

107 revalidate_instances: Literal['always', 'never', 'subclass-instances'] 1abcdefghijklsmnopqr

108 ser_json_timedelta: Literal['iso8601', 'float'] 1abcdefghijklsmnopqr

109 ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds'] 1abcdefghijklsmnopqr

110 val_temporal_unit: Literal['seconds', 'milliseconds', 'infer'] 1abcdefghijklsmnopqr

111 ser_json_bytes: Literal['utf8', 'base64', 'hex'] 1abcdefghijklsmnopqr

112 val_json_bytes: Literal['utf8', 'base64', 'hex'] 1abcdefghijklsmnopqr

113 ser_json_inf_nan: Literal['null', 'constants', 'strings'] 1abcdefghijklsmnopqr

114 # whether to validate default values during validation, default False 

115 validate_default: bool 1abcdefghijklsmnopqr

116 validate_return: bool 1abcdefghijklsmnopqr

117 protected_namespaces: tuple[str | Pattern[str], ...] 1abcdefghijklsmnopqr

118 hide_input_in_errors: bool 1abcdefghijklsmnopqr

119 defer_build: bool 1abcdefghijklsmnopqr

120 plugin_settings: dict[str, object] | None 1abcdefghijklsmnopqr

121 json_schema_serialization_defaults_required: bool 1abcdefghijklsmnopqr

122 json_schema_mode_override: Literal['validation', 'serialization', None] 1abcdefghijklsmnopqr

123 coerce_numbers_to_str: bool 1abcdefghijklsmnopqr

124 regex_engine: Literal['rust-regex', 'python-re'] 1abcdefghijklsmnopqr

125 validation_error_cause: bool 1abcdefghijklsmnopqr

126 use_attribute_docstrings: bool 1abcdefghijklsmnopqr

127 cache_strings: bool | Literal['all', 'keys', 'none'] 1abcdefghijklsmnopqr

128 validate_by_alias: bool 1abcdefghijklsmnopqr

129 validate_by_name: bool 1abcdefghijklsmnopqr

130 serialize_by_alias: bool 1abcdefghijklsmnopqr

131 url_preserve_empty_path: bool 1abcdefghijklsmnopqr

132 polymorphic_serialization: bool 1abcdefghijklsmnopqr

133 

134 def __init__(self, config: ConfigDict | dict[str, Any] | None, *, check: bool = True): 1abcdefghijklsmnopqr

135 if check: 1abcdefghijklsmnopqr

136 self.config_dict = prepare_config(config) 1abcdefghijklsmnopqr

137 else: 

138 self.config_dict = cast(ConfigDict, config) 1abcdefghijklsmnopqr

139 self.effective_config = _build_effective_config(self.config_dict) 1abcdefghijklsmnopqr

140 

141 @classmethod 1abcdefghijklsmnopqr

142 def for_model( 1abcdefghijklsmnopqr

143 cls, 

144 bases: tuple[type[Any], ...], 

145 namespace: dict[str, Any], 

146 kwargs: dict[str, Any], 

147 ) -> Self: 

148 """Build a new `ConfigWrapper` instance for a `BaseModel`. 

149 

150 The config wrapper built based on (in descending order of priority): 

151 - options from `kwargs` 

152 - options from the `namespace` 

153 - options from the base classes (`bases`) 

154 

155 Args: 

156 bases: A tuple of base classes. 

157 namespace: The namespace of the class being created. 

158 kwargs: The kwargs passed to the class being created. 

159 

160 Returns: 

161 A `ConfigWrapper` instance for `BaseModel`. 

162 """ 

163 config_new = ConfigDict() 1abcdefghijklsmnopqr

164 for base in bases: 1abcdefghijklsmnopqr

165 config = getattr(base, 'model_config', None) 1abcdefghijklsmnopqr

166 if config: 1abcdefghijklsmnopqr

167 config_new.update(config.copy()) 1abcdefghijklsmnopqr

168 

169 config_new.update(namespace.get('model_config') or {}) 1abcdefghijklsmnopqr

170 

171 for k in list(kwargs.keys()): 1abcdefghijklsmnopqr

172 if k in config_keys: 1abcdefghijklsmnopqr

173 config_new[k] = kwargs.pop(k) 1abcdefghijklsmnopqr

174 

175 return cls(config_new) 1abcdefghijklsmnopqr

176 

177 # we don't show `__getattr__` to type checkers so missing attributes cause errors 

178 if not TYPE_CHECKING: # pragma: no branch 1abcdefghijklsmnopqr

179 

180 def __getattr__(self, name: str) -> Any: 1abcdefghijklsmnopqr

181 try: 1abcdefghijklsmnopqr

182 return self.effective_config[name] 1abcdefghijklsmnopqr

183 except KeyError: 1abcdefghijklsmnopqr

184 try: 1abcdefghijklsmnopqr

185 return config_defaults[name] 1abcdefghijklsmnopqr

186 except KeyError: 1abcdefghijklmnopqr

187 raise AttributeError(f'Config has no attribute {name!r}') from None 1abcdefghijklmnopqr

188 

189 def core_config(self, title: str | None) -> core_schema.CoreConfig: 1abcdefghijklsmnopqr

190 """Create a pydantic-core config. 

191 

192 We don't use getattr here since we don't want to populate with defaults. 

193 

194 Args: 

195 title: The title to use if not set in config. 

196 

197 Returns: 

198 A `CoreConfig` object created from config. 

199 """ 

200 config = self.effective_config 1abcdefghijklsmnopqr

201 

202 if not config: 1abcdefghijklsmnopqr

203 # Fast path for the common case of an empty (default) config: 

204 return core_schema.CoreConfig(title=title) if title else core_schema.CoreConfig() 1abcdefghijklsmnopqr

205 

206 core_config_values: dict[str, Any] = {} 1abcdefghijklsmnopqr

207 for k, v in config.items(): 1abcdefghijklsmnopqr

208 if v is not None and (core_config_key := _config_dict_to_core_config_key.get(k)) is not None: 1abcdefghijklsmnopqr

209 core_config_values[core_config_key] = v 1abcdefghijklsmnopqr

210 title = config.get('title') or title 1abcdefghijklsmnopqr

211 if title: 1abcdefghijklsmnopqr

212 core_config_values['title'] = title 1abcdefghijklsmnopqr

213 

214 return cast(core_schema.CoreConfig, core_config_values) 1abcdefghijklsmnopqr

215 

216 def __repr__(self): 1abcdefghijklsmnopqr

217 c = ', '.join(f'{k}={v!r}' for k, v in self.config_dict.items()) 1abcdefghijklmnopqr

218 return f'ConfigWrapper({c})' 1abcdefghijklmnopqr

219 

220 

221class ConfigWrapperStack: 1abcdefghijklsmnopqr

222 """A stack of `ConfigWrapper` instances.""" 

223 

224 def __init__(self, config_wrapper: ConfigWrapper): 1abcdefghijklsmnopqr

225 self._config_wrapper_stack: list[ConfigWrapper] = [config_wrapper] 1abcdefghijklsmnopqr

226 

227 @property 1abcdefghijklsmnopqr

228 def tail(self) -> ConfigWrapper: 1abcdefghijklsmnopqr

229 return self._config_wrapper_stack[-1] 1abcdefghijklsmnopqr

230 

231 @contextmanager 1abcdefghijklsmnopqr

232 def push(self, config_wrapper: ConfigWrapper | ConfigDict | None): 1abcdefghijklsmnopqr

233 if config_wrapper is None: 1abcdefghijklsmnopqr

234 yield 1abcdefghijklmnopqr

235 return 1abcdefghijklmnopqr

236 

237 if not isinstance(config_wrapper, ConfigWrapper): 1abcdefghijklsmnopqr

238 config_wrapper = ConfigWrapper(config_wrapper, check=False) 1abcdefghijklsmnopqr

239 

240 self._config_wrapper_stack.append(config_wrapper) 1abcdefghijklsmnopqr

241 try: 1abcdefghijklsmnopqr

242 yield 1abcdefghijklsmnopqr

243 finally: 

244 self._config_wrapper_stack.pop() 1abcdefghijklsmnopqr

245 

246 

247config_defaults = ConfigDict( 1abcdefghijklsmnopqr

248 title=None, 

249 str_to_lower=False, 

250 str_to_upper=False, 

251 str_strip_whitespace=False, 

252 str_min_length=0, 

253 str_max_length=None, 

254 # let the model / dataclass decide how to handle it 

255 extra=None, 

256 frozen=False, 

257 populate_by_name=False, 

258 use_enum_values=False, 

259 validate_assignment=False, 

260 arbitrary_types_allowed=False, 

261 from_attributes=False, 

262 loc_by_alias=True, 

263 alias_generator=None, 

264 model_title_generator=None, 

265 field_title_generator=None, 

266 ignored_types=(), 

267 allow_inf_nan=True, 

268 json_schema_extra=None, 

269 strict=False, 

270 revalidate_instances='never', 

271 ser_json_timedelta='iso8601', 

272 ser_json_temporal='iso8601', 

273 val_temporal_unit='infer', 

274 ser_json_bytes='utf8', 

275 val_json_bytes='utf8', 

276 ser_json_inf_nan='null', 

277 validate_default=False, 

278 validate_return=False, 

279 protected_namespaces=('model_validate', 'model_dump'), 

280 hide_input_in_errors=False, 

281 json_encoders=None, 

282 defer_build=False, 

283 plugin_settings=None, 

284 json_schema_serialization_defaults_required=False, 

285 json_schema_mode_override=None, 

286 coerce_numbers_to_str=False, 

287 regex_engine='rust-regex', 

288 validation_error_cause=False, 

289 use_attribute_docstrings=False, 

290 cache_strings=True, 

291 validate_by_alias=True, 

292 validate_by_name=False, 

293 serialize_by_alias=False, 

294 url_preserve_empty_path=False, 

295 polymorphic_serialization=False, 

296) 

297 

298 

299def _build_effective_config(config: ConfigDict) -> ConfigDict: 1abcdefghijklsmnopqr

300 """Build the configuration in effect from the configuration as declared. 

301 

302 Raises: 

303 PydanticUserError: If validation can happen by neither alias nor name. 

304 """ 

305 if config.get('validate_by_name') is None: 1abcdefghijklsmnopqr

306 if (populate_by_name := config.get('populate_by_name')) is not None: 1abcdefghijklsmnopqr

307 config = cast(ConfigDict, {**config, 'validate_by_alias': True, 'validate_by_name': populate_by_name}) 1abcdefghijklsmnopqr

308 elif config.get('validate_by_alias') is False: 1abcdefghijklsmnopqr

309 config = cast(ConfigDict, {**config, 'validate_by_name': True}) 1abcdefghijklmnopqr

310 

311 if (not config.get('validate_by_alias', True)) and (not config.get('validate_by_name', False)): 1abcdefghijklsmnopqr

312 raise PydanticUserError( 1abcdefghijklmnopqr

313 'At least one of `validate_by_alias` or `validate_by_name` must be set to True.', 

314 code='validate-by-alias-and-name-false', 

315 ) 

316 

317 return config 1abcdefghijklsmnopqr

318 

319 

320def prepare_config(config: ConfigDict | dict[str, Any] | None) -> ConfigDict: 1abcdefghijklsmnopqr

321 """Create a `ConfigDict` instance from an existing dict or None. 

322 

323 Args: 

324 config: The input config. 

325 

326 Returns: 

327 A ConfigDict object created from config. 

328 """ 

329 if config is None: 1abcdefghijklsmnopqr

330 return ConfigDict() 1abcdefghijklsmnopqr

331 

332 # Copy, so that the `ConfigWrapper` owns its configuration and can never 

333 # mutate the mapping provided by the user: 

334 config = config.copy() 1abcdefghijklsmnopqr

335 

336 return cast(ConfigDict, config) 1abcdefghijklsmnopqr

337 

338 

339config_keys = set(ConfigDict.__annotations__.keys()) 1abcdefghijklsmnopqr