pboot-validator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,350 @@
1
+ import os
2
+ import warnings
3
+ from pathlib import Path
4
+ from typing import AbstractSet, Any, Callable, ClassVar, Dict, List, Mapping, Optional, Tuple, Type, Union
5
+
6
+ from pboot_validator.v1.config import BaseConfig, Extra
7
+ from pboot_validator.v1.fields import ModelField
8
+ from pboot_validator.v1.main import BaseModel
9
+ from pboot_validator.v1.types import JsonWrapper
10
+ from pboot_validator.v1.typing import StrPath, display_as_type, get_origin, is_union
11
+ from pboot_validator.v1.utils import deep_update, lenient_issubclass, path_type, sequence_like
12
+
13
+ env_file_sentinel = str(object())
14
+
15
+ SettingsSourceCallable = Callable[['BaseSettings'], Dict[str, Any]]
16
+ DotenvType = Union[StrPath, List[StrPath], Tuple[StrPath, ...]]
17
+
18
+
19
+ class SettingsError(ValueError):
20
+ pass
21
+
22
+
23
+ class BaseSettings(BaseModel):
24
+ """
25
+ Base class for settings, allowing values to be overridden by environment variables.
26
+
27
+ This is useful in production for secrets you do not wish to save in code, it plays nicely with docker(-compose),
28
+ Heroku and any 12 factor app design.
29
+ """
30
+
31
+ def __init__(
32
+ __pydantic_self__,
33
+ _env_file: Optional[DotenvType] = env_file_sentinel,
34
+ _env_file_encoding: Optional[str] = None,
35
+ _env_nested_delimiter: Optional[str] = None,
36
+ _secrets_dir: Optional[StrPath] = None,
37
+ **values: Any,
38
+ ) -> None:
39
+ # Uses something other than `self` the first arg to allow "self" as a settable attribute
40
+ super().__init__(
41
+ **__pydantic_self__._build_values(
42
+ values,
43
+ _env_file=_env_file,
44
+ _env_file_encoding=_env_file_encoding,
45
+ _env_nested_delimiter=_env_nested_delimiter,
46
+ _secrets_dir=_secrets_dir,
47
+ )
48
+ )
49
+
50
+ def _build_values(
51
+ self,
52
+ init_kwargs: Dict[str, Any],
53
+ _env_file: Optional[DotenvType] = None,
54
+ _env_file_encoding: Optional[str] = None,
55
+ _env_nested_delimiter: Optional[str] = None,
56
+ _secrets_dir: Optional[StrPath] = None,
57
+ ) -> Dict[str, Any]:
58
+ # Configure built-in sources
59
+ init_settings = InitSettingsSource(init_kwargs=init_kwargs)
60
+ env_settings = EnvSettingsSource(
61
+ env_file=(_env_file if _env_file != env_file_sentinel else self.__config__.env_file),
62
+ env_file_encoding=(
63
+ _env_file_encoding if _env_file_encoding is not None else self.__config__.env_file_encoding
64
+ ),
65
+ env_nested_delimiter=(
66
+ _env_nested_delimiter if _env_nested_delimiter is not None else self.__config__.env_nested_delimiter
67
+ ),
68
+ env_prefix_len=len(self.__config__.env_prefix),
69
+ )
70
+ file_secret_settings = SecretsSettingsSource(secrets_dir=_secrets_dir or self.__config__.secrets_dir)
71
+ # Provide a hook to set built-in sources priority and add / remove sources
72
+ sources = self.__config__.customise_sources(
73
+ init_settings=init_settings, env_settings=env_settings, file_secret_settings=file_secret_settings
74
+ )
75
+ if sources:
76
+ return deep_update(*reversed([source(self) for source in sources]))
77
+ else:
78
+ # no one should mean to do this, but I think returning an empty dict is marginally preferable
79
+ # to an informative error and much better than a confusing error
80
+ return {}
81
+
82
+ class Config(BaseConfig):
83
+ env_prefix: str = ''
84
+ env_file: Optional[DotenvType] = None
85
+ env_file_encoding: Optional[str] = None
86
+ env_nested_delimiter: Optional[str] = None
87
+ secrets_dir: Optional[StrPath] = None
88
+ validate_all: bool = True
89
+ extra: Extra = Extra.forbid
90
+ arbitrary_types_allowed: bool = True
91
+ case_sensitive: bool = False
92
+
93
+ @classmethod
94
+ def prepare_field(cls, field: ModelField) -> None:
95
+ env_names: Union[List[str], AbstractSet[str]]
96
+ field_info_from_config = cls.get_field_info(field.name)
97
+
98
+ env = field_info_from_config.get('env') or field.field_info.extra.get('env')
99
+ if env is None:
100
+ if field.has_alias:
101
+ warnings.warn(
102
+ 'aliases are no longer used by BaseSettings to define which environment variables to read. '
103
+ 'Instead use the "env" field setting. '
104
+ 'See https://pydantic-docs.helpmanual.io/usage/settings/#environment-variable-names',
105
+ FutureWarning,
106
+ )
107
+ env_names = {cls.env_prefix + field.name}
108
+ elif isinstance(env, str):
109
+ env_names = {env}
110
+ elif isinstance(env, (set, frozenset)):
111
+ env_names = env
112
+ elif sequence_like(env):
113
+ env_names = list(env)
114
+ else:
115
+ raise TypeError(f'invalid field env: {env!r} ({display_as_type(env)}); should be string, list or set')
116
+
117
+ if not cls.case_sensitive:
118
+ env_names = env_names.__class__(n.lower() for n in env_names)
119
+ field.field_info.extra['env_names'] = env_names
120
+
121
+ @classmethod
122
+ def customise_sources(
123
+ cls,
124
+ init_settings: SettingsSourceCallable,
125
+ env_settings: SettingsSourceCallable,
126
+ file_secret_settings: SettingsSourceCallable,
127
+ ) -> Tuple[SettingsSourceCallable, ...]:
128
+ return init_settings, env_settings, file_secret_settings
129
+
130
+ @classmethod
131
+ def parse_env_var(cls, field_name: str, raw_val: str) -> Any:
132
+ return cls.json_loads(raw_val)
133
+
134
+ # populated by the metaclass using the Config class defined above, annotated here to help IDEs only
135
+ __config__: ClassVar[Type[Config]]
136
+
137
+
138
+ class InitSettingsSource:
139
+ __slots__ = ('init_kwargs',)
140
+
141
+ def __init__(self, init_kwargs: Dict[str, Any]):
142
+ self.init_kwargs = init_kwargs
143
+
144
+ def __call__(self, settings: BaseSettings) -> Dict[str, Any]:
145
+ return self.init_kwargs
146
+
147
+ def __repr__(self) -> str:
148
+ return f'InitSettingsSource(init_kwargs={self.init_kwargs!r})'
149
+
150
+
151
+ class EnvSettingsSource:
152
+ __slots__ = ('env_file', 'env_file_encoding', 'env_nested_delimiter', 'env_prefix_len')
153
+
154
+ def __init__(
155
+ self,
156
+ env_file: Optional[DotenvType],
157
+ env_file_encoding: Optional[str],
158
+ env_nested_delimiter: Optional[str] = None,
159
+ env_prefix_len: int = 0,
160
+ ):
161
+ self.env_file: Optional[DotenvType] = env_file
162
+ self.env_file_encoding: Optional[str] = env_file_encoding
163
+ self.env_nested_delimiter: Optional[str] = env_nested_delimiter
164
+ self.env_prefix_len: int = env_prefix_len
165
+
166
+ def __call__(self, settings: BaseSettings) -> Dict[str, Any]: # noqa C901
167
+ """
168
+ Build environment variables suitable for passing to the Model.
169
+ """
170
+ d: Dict[str, Any] = {}
171
+
172
+ if settings.__config__.case_sensitive:
173
+ env_vars: Mapping[str, Optional[str]] = os.environ
174
+ else:
175
+ env_vars = {k.lower(): v for k, v in os.environ.items()}
176
+
177
+ dotenv_vars = self._read_env_files(settings.__config__.case_sensitive)
178
+ if dotenv_vars:
179
+ env_vars = {**dotenv_vars, **env_vars}
180
+
181
+ for field in settings.__fields__.values():
182
+ env_val: Optional[str] = None
183
+ for env_name in field.field_info.extra['env_names']:
184
+ env_val = env_vars.get(env_name)
185
+ if env_val is not None:
186
+ break
187
+
188
+ is_complex, allow_parse_failure = self.field_is_complex(field)
189
+ if is_complex:
190
+ if env_val is None:
191
+ # field is complex but no value found so far, try explode_env_vars
192
+ env_val_built = self.explode_env_vars(field, env_vars)
193
+ if env_val_built:
194
+ d[field.alias] = env_val_built
195
+ else:
196
+ # field is complex and there's a value, decode that as JSON, then add explode_env_vars
197
+ try:
198
+ env_val = settings.__config__.parse_env_var(field.name, env_val)
199
+ except ValueError as e:
200
+ if not allow_parse_failure:
201
+ raise SettingsError(f'error parsing env var "{env_name}"') from e
202
+
203
+ if isinstance(env_val, dict):
204
+ d[field.alias] = deep_update(env_val, self.explode_env_vars(field, env_vars))
205
+ else:
206
+ d[field.alias] = env_val
207
+ elif env_val is not None:
208
+ # simplest case, field is not complex, we only need to add the value if it was found
209
+ d[field.alias] = env_val
210
+
211
+ return d
212
+
213
+ def _read_env_files(self, case_sensitive: bool) -> Dict[str, Optional[str]]:
214
+ env_files = self.env_file
215
+ if env_files is None:
216
+ return {}
217
+
218
+ if isinstance(env_files, (str, os.PathLike)):
219
+ env_files = [env_files]
220
+
221
+ dotenv_vars = {}
222
+ for env_file in env_files:
223
+ env_path = Path(env_file).expanduser()
224
+ if env_path.is_file():
225
+ dotenv_vars.update(
226
+ read_env_file(env_path, encoding=self.env_file_encoding, case_sensitive=case_sensitive)
227
+ )
228
+
229
+ return dotenv_vars
230
+
231
+ def field_is_complex(self, field: ModelField) -> Tuple[bool, bool]:
232
+ """
233
+ Find out if a field is complex, and if so whether JSON errors should be ignored
234
+ """
235
+ if lenient_issubclass(field.annotation, JsonWrapper):
236
+ return False, False
237
+
238
+ if field.is_complex():
239
+ allow_parse_failure = False
240
+ elif is_union(get_origin(field.type_)) and field.sub_fields and any(f.is_complex() for f in field.sub_fields):
241
+ allow_parse_failure = True
242
+ else:
243
+ return False, False
244
+
245
+ return True, allow_parse_failure
246
+
247
+ def explode_env_vars(self, field: ModelField, env_vars: Mapping[str, Optional[str]]) -> Dict[str, Any]:
248
+ """
249
+ Process env_vars and extract the values of keys containing env_nested_delimiter into nested dictionaries.
250
+
251
+ This is applied to a single field, hence filtering by env_var prefix.
252
+ """
253
+ prefixes = [f'{env_name}{self.env_nested_delimiter}' for env_name in field.field_info.extra['env_names']]
254
+ result: Dict[str, Any] = {}
255
+ for env_name, env_val in env_vars.items():
256
+ if not any(env_name.startswith(prefix) for prefix in prefixes):
257
+ continue
258
+ # we remove the prefix before splitting in case the prefix has characters in common with the delimiter
259
+ env_name_without_prefix = env_name[self.env_prefix_len :]
260
+ _, *keys, last_key = env_name_without_prefix.split(self.env_nested_delimiter)
261
+ env_var = result
262
+ for key in keys:
263
+ env_var = env_var.setdefault(key, {})
264
+ env_var[last_key] = env_val
265
+
266
+ return result
267
+
268
+ def __repr__(self) -> str:
269
+ return (
270
+ f'EnvSettingsSource(env_file={self.env_file!r}, env_file_encoding={self.env_file_encoding!r}, '
271
+ f'env_nested_delimiter={self.env_nested_delimiter!r})'
272
+ )
273
+
274
+
275
+ class SecretsSettingsSource:
276
+ __slots__ = ('secrets_dir',)
277
+
278
+ def __init__(self, secrets_dir: Optional[StrPath]):
279
+ self.secrets_dir: Optional[StrPath] = secrets_dir
280
+
281
+ def __call__(self, settings: BaseSettings) -> Dict[str, Any]:
282
+ """
283
+ Build fields from "secrets" files.
284
+ """
285
+ secrets: Dict[str, Optional[str]] = {}
286
+
287
+ if self.secrets_dir is None:
288
+ return secrets
289
+
290
+ secrets_path = Path(self.secrets_dir).expanduser()
291
+
292
+ if not secrets_path.exists():
293
+ warnings.warn(f'directory "{secrets_path}" does not exist')
294
+ return secrets
295
+
296
+ if not secrets_path.is_dir():
297
+ raise SettingsError(f'secrets_dir must reference a directory, not a {path_type(secrets_path)}')
298
+
299
+ for field in settings.__fields__.values():
300
+ for env_name in field.field_info.extra['env_names']:
301
+ path = find_case_path(secrets_path, env_name, settings.__config__.case_sensitive)
302
+ if not path:
303
+ # path does not exist, we currently don't return a warning for this
304
+ continue
305
+
306
+ if path.is_file():
307
+ secret_value = path.read_text().strip()
308
+ if field.is_complex():
309
+ try:
310
+ secret_value = settings.__config__.parse_env_var(field.name, secret_value)
311
+ except ValueError as e:
312
+ raise SettingsError(f'error parsing env var "{env_name}"') from e
313
+
314
+ secrets[field.alias] = secret_value
315
+ else:
316
+ warnings.warn(
317
+ f'attempted to load secret file "{path}" but found a {path_type(path)} instead.',
318
+ stacklevel=4,
319
+ )
320
+ return secrets
321
+
322
+ def __repr__(self) -> str:
323
+ return f'SecretsSettingsSource(secrets_dir={self.secrets_dir!r})'
324
+
325
+
326
+ def read_env_file(
327
+ file_path: StrPath, *, encoding: str = None, case_sensitive: bool = False
328
+ ) -> Dict[str, Optional[str]]:
329
+ try:
330
+ from dotenv import dotenv_values
331
+ except ImportError as e:
332
+ raise ImportError('python-dotenv is not installed, run `pip install pydantic[dotenv]`') from e
333
+
334
+ file_vars: Dict[str, Optional[str]] = dotenv_values(file_path, encoding=encoding or 'utf8')
335
+ if not case_sensitive:
336
+ return {k.lower(): v for k, v in file_vars.items()}
337
+ else:
338
+ return file_vars
339
+
340
+
341
+ def find_case_path(dir_path: Path, file_name: str, case_sensitive: bool) -> Optional[Path]:
342
+ """
343
+ Find a file within path's directory matching filename, optionally ignoring case.
344
+ """
345
+ for f in dir_path.iterdir():
346
+ if f.name == file_name:
347
+ return f
348
+ elif not case_sensitive and f.name.lower() == file_name.lower():
349
+ return f
350
+ return None
@@ -0,0 +1,161 @@
1
+ import json
2
+ from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union
3
+
4
+ from pboot_validator.v1.json import pydantic_encoder
5
+ from pboot_validator.v1.utils import Representation
6
+
7
+ if TYPE_CHECKING:
8
+ from typing_extensions import TypedDict
9
+
10
+ from pboot_validator.v1.config import BaseConfig
11
+ from pboot_validator.v1.types import ModelOrDc
12
+ from pboot_validator.v1.typing import ReprArgs
13
+
14
+ Loc = Tuple[Union[int, str], ...]
15
+
16
+ class _ErrorDictRequired(TypedDict):
17
+ loc: Loc
18
+ msg: str
19
+ type: str
20
+
21
+ class ErrorDict(_ErrorDictRequired, total=False):
22
+ ctx: Dict[str, Any]
23
+
24
+
25
+ __all__ = 'ErrorWrapper', 'ValidationError'
26
+
27
+
28
+ class ErrorWrapper(Representation):
29
+ __slots__ = 'exc', '_loc'
30
+
31
+ def __init__(self, exc: Exception, loc: Union[str, 'Loc']) -> None:
32
+ self.exc = exc
33
+ self._loc = loc
34
+
35
+ def loc_tuple(self) -> 'Loc':
36
+ if isinstance(self._loc, tuple):
37
+ return self._loc
38
+ else:
39
+ return (self._loc,)
40
+
41
+ def __repr_args__(self) -> 'ReprArgs':
42
+ return [('exc', self.exc), ('loc', self.loc_tuple())]
43
+
44
+
45
+ # ErrorList is something like Union[List[Union[List[ErrorWrapper], ErrorWrapper]], ErrorWrapper]
46
+ # but recursive, therefore just use:
47
+ ErrorList = Union[Sequence[Any], ErrorWrapper]
48
+
49
+
50
+ class ValidationError(Representation, ValueError):
51
+ __slots__ = 'raw_errors', 'model', '_error_cache'
52
+
53
+ def __init__(self, errors: Sequence[ErrorList], model: 'ModelOrDc') -> None:
54
+ self.raw_errors = errors
55
+ self.model = model
56
+ self._error_cache: Optional[List['ErrorDict']] = None
57
+
58
+ def errors(self) -> List['ErrorDict']:
59
+ if self._error_cache is None:
60
+ try:
61
+ config = self.model.__config__ # type: ignore
62
+ except AttributeError:
63
+ config = self.model.__pydantic_model__.__config__ # type: ignore
64
+ self._error_cache = list(flatten_errors(self.raw_errors, config))
65
+ return self._error_cache
66
+
67
+ def json(self, *, indent: Union[None, int, str] = 2) -> str:
68
+ return json.dumps(self.errors(), indent=indent, default=pydantic_encoder)
69
+
70
+ def __str__(self) -> str:
71
+ errors = self.errors()
72
+ no_errors = len(errors)
73
+ return (
74
+ f'{no_errors} validation error{"" if no_errors == 1 else "s"} for {self.model.__name__}\n'
75
+ f'{display_errors(errors)}'
76
+ )
77
+
78
+ def __repr_args__(self) -> 'ReprArgs':
79
+ return [('model', self.model.__name__), ('errors', self.errors())]
80
+
81
+
82
+ def display_errors(errors: List['ErrorDict']) -> str:
83
+ return '\n'.join(f'{_display_error_loc(e)}\n {e["msg"]} ({_display_error_type_and_ctx(e)})' for e in errors)
84
+
85
+
86
+ def _display_error_loc(error: 'ErrorDict') -> str:
87
+ return ' -> '.join(str(e) for e in error['loc'])
88
+
89
+
90
+ def _display_error_type_and_ctx(error: 'ErrorDict') -> str:
91
+ t = 'type=' + error['type']
92
+ ctx = error.get('ctx')
93
+ if ctx:
94
+ return t + ''.join(f'; {k}={v}' for k, v in ctx.items())
95
+ else:
96
+ return t
97
+
98
+
99
+ def flatten_errors(
100
+ errors: Sequence[Any], config: Type['BaseConfig'], loc: Optional['Loc'] = None
101
+ ) -> Generator['ErrorDict', None, None]:
102
+ for error in errors:
103
+ if isinstance(error, ErrorWrapper):
104
+ if loc:
105
+ error_loc = loc + error.loc_tuple()
106
+ else:
107
+ error_loc = error.loc_tuple()
108
+
109
+ if isinstance(error.exc, ValidationError):
110
+ yield from flatten_errors(error.exc.raw_errors, config, error_loc)
111
+ else:
112
+ yield error_dict(error.exc, config, error_loc)
113
+ elif isinstance(error, list):
114
+ yield from flatten_errors(error, config, loc=loc)
115
+ else:
116
+ raise RuntimeError(f'Unknown error object: {error}')
117
+
118
+
119
+ def error_dict(exc: Exception, config: Type['BaseConfig'], loc: 'Loc') -> 'ErrorDict':
120
+ type_ = get_exc_type(exc.__class__)
121
+ msg_template = config.error_msg_templates.get(type_) or getattr(exc, 'msg_template', None)
122
+ ctx = exc.__dict__
123
+ if msg_template:
124
+ msg = msg_template.format(**ctx)
125
+ else:
126
+ msg = str(exc)
127
+
128
+ d: 'ErrorDict' = {'loc': loc, 'msg': msg, 'type': type_}
129
+
130
+ if ctx:
131
+ d['ctx'] = ctx
132
+
133
+ return d
134
+
135
+
136
+ _EXC_TYPE_CACHE: Dict[Type[Exception], str] = {}
137
+
138
+
139
+ def get_exc_type(cls: Type[Exception]) -> str:
140
+ # slightly more efficient than using lru_cache since we don't need to worry about the cache filling up
141
+ try:
142
+ return _EXC_TYPE_CACHE[cls]
143
+ except KeyError:
144
+ r = _get_exc_type(cls)
145
+ _EXC_TYPE_CACHE[cls] = r
146
+ return r
147
+
148
+
149
+ def _get_exc_type(cls: Type[Exception]) -> str:
150
+ if issubclass(cls, AssertionError):
151
+ return 'assertion_error'
152
+
153
+ base_name = 'type_error' if issubclass(cls, TypeError) else 'value_error'
154
+ if cls in (TypeError, ValueError):
155
+ # just TypeError or ValueError, no extra code
156
+ return base_name
157
+
158
+ # if it's not a TypeError or ValueError, we just take the lowercase of the exception name
159
+ # no chaining or snake case logic, use "code" for more complex error types.
160
+ code = getattr(cls, 'code', None) or cls.__name__.replace('Error', '').lower()
161
+ return base_name + '.' + code