codekingpro commited on
Commit
f339cf1
·
verified ·
1 Parent(s): a040e70

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic-2.13.4.dist-info/licenses/LICENSE +21 -0
  2. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/alias_generators.cpython-311.pyc +0 -0
  3. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/aliases.cpython-311.pyc +0 -0
  4. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-311.pyc +0 -0
  5. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/class_validators.cpython-311.pyc +0 -0
  6. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/color.cpython-311.pyc +0 -0
  7. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/config.cpython-311.pyc +0 -0
  8. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/dataclasses.cpython-311.pyc +0 -0
  9. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/__init__.py +0 -0
  10. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_config.py +386 -0
  11. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_core_metadata.py +97 -0
  12. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_core_utils.py +174 -0
  13. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_dataclasses.py +315 -0
  14. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_decorators.py +873 -0
  15. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_decorators_v1.py +174 -0
  16. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_discriminated_union.py +494 -0
  17. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_docs_extraction.py +113 -0
  18. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_fields.py +729 -0
  19. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_forward_ref.py +23 -0
  20. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_generate_schema.py +0 -0
  21. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_generics.py +530 -0
  22. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_git.py +27 -0
  23. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_import_utils.py +20 -0
  24. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_internal_dataclass.py +7 -0
  25. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_known_annotated_metadata.py +403 -0
  26. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_mock_val_ser.py +228 -0
  27. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_model_construction.py +868 -0
  28. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_namespace_utils.py +293 -0
  29. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_repr.py +124 -0
  30. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_schema_gather.py +212 -0
  31. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_schema_generation_shared.py +125 -0
  32. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_serializers.py +53 -0
  33. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_signature.py +189 -0
  34. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_typing_extra.py +785 -0
  35. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_utils.py +446 -0
  36. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_validate_call.py +141 -0
  37. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_validators.py +534 -0
  38. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/__init__.py +0 -0
  39. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/class_validators.py +256 -0
  40. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/config.py +72 -0
  41. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/copy_internals.py +224 -0
  42. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/decorator.py +284 -0
  43. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/json.py +141 -0
  44. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/parse.py +80 -0
  45. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/tools.py +103 -0
  46. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/experimental/__init__.py +1 -0
  47. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/experimental/arguments_schema.py +44 -0
  48. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/experimental/missing_sentinel.py +5 -0
  49. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/experimental/pipeline.py +663 -0
  50. micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/plugin/__init__.py +193 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic-2.13.4.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 to present Pydantic Services Inc. and individual contributors.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/alias_generators.cpython-311.pyc ADDED
Binary file (3.54 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/aliases.cpython-311.pyc ADDED
Binary file (7.23 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-311.pyc ADDED
Binary file (5.86 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/class_validators.cpython-311.pyc ADDED
Binary file (411 Bytes). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/color.cpython-311.pyc ADDED
Binary file (32.5 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/config.cpython-311.pyc ADDED
Binary file (8.54 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/__pycache__/dataclasses.cpython-311.pyc ADDED
Binary file (18.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/__init__.py ADDED
File without changes
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_config.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations as _annotations
2
+
3
+ import warnings
4
+ from contextlib import contextmanager
5
+ from re import Pattern
6
+ from typing import (
7
+ TYPE_CHECKING,
8
+ Any,
9
+ Callable,
10
+ Literal,
11
+ cast,
12
+ )
13
+
14
+ from pydantic_core import core_schema
15
+ from typing_extensions import Self
16
+
17
+ from ..aliases import AliasGenerator
18
+ from ..config import ConfigDict, ExtraValues, JsonDict, JsonEncoder, JsonSchemaExtraCallable
19
+ from ..errors import PydanticUserError
20
+ from ..warnings import PydanticDeprecatedSince20, PydanticDeprecatedSince210
21
+
22
+ if TYPE_CHECKING:
23
+ from .._internal._schema_generation_shared import GenerateSchema
24
+ from ..fields import ComputedFieldInfo, FieldInfo
25
+
26
+ DEPRECATION_MESSAGE = 'Support for class-based `config` is deprecated, use ConfigDict instead.'
27
+
28
+
29
+ class ConfigWrapper:
30
+ """Internal wrapper for Config which exposes ConfigDict items as attributes."""
31
+
32
+ __slots__ = ('config_dict',)
33
+
34
+ config_dict: ConfigDict
35
+
36
+ # all annotations are copied directly from ConfigDict, and should be kept up to date, a test will fail if they
37
+ # stop matching
38
+ title: str | None
39
+ str_to_lower: bool
40
+ str_to_upper: bool
41
+ str_strip_whitespace: bool
42
+ str_min_length: int
43
+ str_max_length: int | None
44
+ extra: ExtraValues | None
45
+ frozen: bool
46
+ populate_by_name: bool
47
+ use_enum_values: bool
48
+ validate_assignment: bool
49
+ arbitrary_types_allowed: bool
50
+ from_attributes: bool
51
+ # whether to use the actual key provided in the data (e.g. alias or first alias for "field required" errors) instead of field_names
52
+ # to construct error `loc`s, default `True`
53
+ loc_by_alias: bool
54
+ alias_generator: Callable[[str], str] | AliasGenerator | None
55
+ model_title_generator: Callable[[type], str] | None
56
+ field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None
57
+ ignored_types: tuple[type, ...]
58
+ allow_inf_nan: bool
59
+ json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
60
+ json_encoders: dict[type[object], JsonEncoder] | None
61
+
62
+ # new in V2
63
+ strict: bool
64
+ # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
65
+ revalidate_instances: Literal['always', 'never', 'subclass-instances']
66
+ ser_json_timedelta: Literal['iso8601', 'float']
67
+ ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']
68
+ val_temporal_unit: Literal['seconds', 'milliseconds', 'infer']
69
+ ser_json_bytes: Literal['utf8', 'base64', 'hex']
70
+ val_json_bytes: Literal['utf8', 'base64', 'hex']
71
+ ser_json_inf_nan: Literal['null', 'constants', 'strings']
72
+ # whether to validate default values during validation, default False
73
+ validate_default: bool
74
+ validate_return: bool
75
+ protected_namespaces: tuple[str | Pattern[str], ...]
76
+ hide_input_in_errors: bool
77
+ defer_build: bool
78
+ plugin_settings: dict[str, object] | None
79
+ schema_generator: type[GenerateSchema] | None
80
+ json_schema_serialization_defaults_required: bool
81
+ json_schema_mode_override: Literal['validation', 'serialization', None]
82
+ coerce_numbers_to_str: bool
83
+ regex_engine: Literal['rust-regex', 'python-re']
84
+ validation_error_cause: bool
85
+ use_attribute_docstrings: bool
86
+ cache_strings: bool | Literal['all', 'keys', 'none']
87
+ validate_by_alias: bool
88
+ validate_by_name: bool
89
+ serialize_by_alias: bool
90
+ url_preserve_empty_path: bool
91
+ polymorphic_serialization: bool
92
+
93
+ def __init__(self, config: ConfigDict | dict[str, Any] | type[Any] | None, *, check: bool = True):
94
+ if check:
95
+ self.config_dict = prepare_config(config)
96
+ else:
97
+ self.config_dict = cast(ConfigDict, config)
98
+
99
+ @classmethod
100
+ def for_model(
101
+ cls,
102
+ bases: tuple[type[Any], ...],
103
+ namespace: dict[str, Any],
104
+ raw_annotations: dict[str, Any],
105
+ kwargs: dict[str, Any],
106
+ ) -> Self:
107
+ """Build a new `ConfigWrapper` instance for a `BaseModel`.
108
+
109
+ The config wrapper built based on (in descending order of priority):
110
+ - options from `kwargs`
111
+ - options from the `namespace`
112
+ - options from the base classes (`bases`)
113
+
114
+ Args:
115
+ bases: A tuple of base classes.
116
+ namespace: The namespace of the class being created.
117
+ raw_annotations: The (non-evaluated) annotations of the model.
118
+ kwargs: The kwargs passed to the class being created.
119
+
120
+ Returns:
121
+ A `ConfigWrapper` instance for `BaseModel`.
122
+ """
123
+ config_new = ConfigDict()
124
+ for base in bases:
125
+ config = getattr(base, 'model_config', None)
126
+ if config:
127
+ config_new.update(config.copy())
128
+
129
+ config_class_from_namespace = namespace.get('Config')
130
+ config_dict_from_namespace = namespace.get('model_config')
131
+
132
+ if raw_annotations.get('model_config') and config_dict_from_namespace is None:
133
+ raise PydanticUserError(
134
+ '`model_config` cannot be used as a model field name. Use `model_config` for model configuration.',
135
+ code='model-config-invalid-field-name',
136
+ )
137
+
138
+ if config_class_from_namespace and config_dict_from_namespace:
139
+ raise PydanticUserError('"Config" and "model_config" cannot be used together', code='config-both')
140
+
141
+ config_from_namespace = config_dict_from_namespace or prepare_config(config_class_from_namespace)
142
+
143
+ config_new.update(config_from_namespace)
144
+
145
+ for k in list(kwargs.keys()):
146
+ if k in config_keys:
147
+ config_new[k] = kwargs.pop(k)
148
+
149
+ return cls(config_new)
150
+
151
+ # we don't show `__getattr__` to type checkers so missing attributes cause errors
152
+ if not TYPE_CHECKING: # pragma: no branch
153
+
154
+ def __getattr__(self, name: str) -> Any:
155
+ try:
156
+ return self.config_dict[name]
157
+ except KeyError:
158
+ try:
159
+ return config_defaults[name]
160
+ except KeyError:
161
+ raise AttributeError(f'Config has no attribute {name!r}') from None
162
+
163
+ def core_config(self, title: str | None) -> core_schema.CoreConfig:
164
+ """Create a pydantic-core config.
165
+
166
+ We don't use getattr here since we don't want to populate with defaults.
167
+
168
+ Args:
169
+ title: The title to use if not set in config.
170
+
171
+ Returns:
172
+ A `CoreConfig` object created from config.
173
+ """
174
+ config = self.config_dict
175
+
176
+ if config.get('schema_generator') is not None:
177
+ warnings.warn(
178
+ 'The `schema_generator` setting has been deprecated since v2.10. This setting no longer has any effect.',
179
+ PydanticDeprecatedSince210,
180
+ stacklevel=2,
181
+ )
182
+
183
+ if (populate_by_name := config.get('populate_by_name')) is not None:
184
+ # We include this patch for backwards compatibility purposes, but this config setting will be deprecated in v3.0, and likely removed in v4.0.
185
+ # Thus, the above warning and this patch can be removed then as well.
186
+ if config.get('validate_by_name') is None:
187
+ config['validate_by_alias'] = True
188
+ config['validate_by_name'] = populate_by_name
189
+
190
+ # We dynamically patch validate_by_name to be True if validate_by_alias is set to False
191
+ # and validate_by_name is not explicitly set.
192
+ if config.get('validate_by_alias') is False and config.get('validate_by_name') is None:
193
+ config['validate_by_name'] = True
194
+
195
+ if (not config.get('validate_by_alias', True)) and (not config.get('validate_by_name', False)):
196
+ raise PydanticUserError(
197
+ 'At least one of `validate_by_alias` or `validate_by_name` must be set to True.',
198
+ code='validate-by-alias-and-name-false',
199
+ )
200
+
201
+ return core_schema.CoreConfig(
202
+ **{ # pyright: ignore[reportArgumentType]
203
+ k: v
204
+ for k, v in (
205
+ ('title', config.get('title') or title or None),
206
+ ('extra_fields_behavior', config.get('extra')),
207
+ ('allow_inf_nan', config.get('allow_inf_nan')),
208
+ ('str_strip_whitespace', config.get('str_strip_whitespace')),
209
+ ('str_to_lower', config.get('str_to_lower')),
210
+ ('str_to_upper', config.get('str_to_upper')),
211
+ ('strict', config.get('strict')),
212
+ ('ser_json_timedelta', config.get('ser_json_timedelta')),
213
+ ('ser_json_temporal', config.get('ser_json_temporal')),
214
+ ('val_temporal_unit', config.get('val_temporal_unit')),
215
+ ('ser_json_bytes', config.get('ser_json_bytes')),
216
+ ('val_json_bytes', config.get('val_json_bytes')),
217
+ ('ser_json_inf_nan', config.get('ser_json_inf_nan')),
218
+ ('from_attributes', config.get('from_attributes')),
219
+ ('loc_by_alias', config.get('loc_by_alias')),
220
+ ('revalidate_instances', config.get('revalidate_instances')),
221
+ ('validate_default', config.get('validate_default')),
222
+ ('str_max_length', config.get('str_max_length')),
223
+ ('str_min_length', config.get('str_min_length')),
224
+ ('hide_input_in_errors', config.get('hide_input_in_errors')),
225
+ ('coerce_numbers_to_str', config.get('coerce_numbers_to_str')),
226
+ ('regex_engine', config.get('regex_engine')),
227
+ ('validation_error_cause', config.get('validation_error_cause')),
228
+ ('cache_strings', config.get('cache_strings')),
229
+ ('validate_by_alias', config.get('validate_by_alias')),
230
+ ('validate_by_name', config.get('validate_by_name')),
231
+ ('serialize_by_alias', config.get('serialize_by_alias')),
232
+ ('url_preserve_empty_path', config.get('url_preserve_empty_path')),
233
+ ('polymorphic_serialization', config.get('polymorphic_serialization')),
234
+ )
235
+ if v is not None
236
+ }
237
+ )
238
+
239
+ def __repr__(self):
240
+ c = ', '.join(f'{k}={v!r}' for k, v in self.config_dict.items())
241
+ return f'ConfigWrapper({c})'
242
+
243
+
244
+ class ConfigWrapperStack:
245
+ """A stack of `ConfigWrapper` instances."""
246
+
247
+ def __init__(self, config_wrapper: ConfigWrapper):
248
+ self._config_wrapper_stack: list[ConfigWrapper] = [config_wrapper]
249
+
250
+ @property
251
+ def tail(self) -> ConfigWrapper:
252
+ return self._config_wrapper_stack[-1]
253
+
254
+ @contextmanager
255
+ def push(self, config_wrapper: ConfigWrapper | ConfigDict | None):
256
+ if config_wrapper is None:
257
+ yield
258
+ return
259
+
260
+ if not isinstance(config_wrapper, ConfigWrapper):
261
+ config_wrapper = ConfigWrapper(config_wrapper, check=False)
262
+
263
+ self._config_wrapper_stack.append(config_wrapper)
264
+ try:
265
+ yield
266
+ finally:
267
+ self._config_wrapper_stack.pop()
268
+
269
+
270
+ config_defaults = ConfigDict(
271
+ title=None,
272
+ str_to_lower=False,
273
+ str_to_upper=False,
274
+ str_strip_whitespace=False,
275
+ str_min_length=0,
276
+ str_max_length=None,
277
+ # let the model / dataclass decide how to handle it
278
+ extra=None,
279
+ frozen=False,
280
+ populate_by_name=False,
281
+ use_enum_values=False,
282
+ validate_assignment=False,
283
+ arbitrary_types_allowed=False,
284
+ from_attributes=False,
285
+ loc_by_alias=True,
286
+ alias_generator=None,
287
+ model_title_generator=None,
288
+ field_title_generator=None,
289
+ ignored_types=(),
290
+ allow_inf_nan=True,
291
+ json_schema_extra=None,
292
+ strict=False,
293
+ revalidate_instances='never',
294
+ ser_json_timedelta='iso8601',
295
+ ser_json_temporal='iso8601',
296
+ val_temporal_unit='infer',
297
+ ser_json_bytes='utf8',
298
+ val_json_bytes='utf8',
299
+ ser_json_inf_nan='null',
300
+ validate_default=False,
301
+ validate_return=False,
302
+ protected_namespaces=('model_validate', 'model_dump'),
303
+ hide_input_in_errors=False,
304
+ json_encoders=None,
305
+ defer_build=False,
306
+ schema_generator=None,
307
+ plugin_settings=None,
308
+ json_schema_serialization_defaults_required=False,
309
+ json_schema_mode_override=None,
310
+ coerce_numbers_to_str=False,
311
+ regex_engine='rust-regex',
312
+ validation_error_cause=False,
313
+ use_attribute_docstrings=False,
314
+ cache_strings=True,
315
+ validate_by_alias=True,
316
+ validate_by_name=False,
317
+ serialize_by_alias=False,
318
+ url_preserve_empty_path=False,
319
+ polymorphic_serialization=False,
320
+ )
321
+
322
+
323
+ def prepare_config(config: ConfigDict | dict[str, Any] | type[Any] | None) -> ConfigDict:
324
+ """Create a `ConfigDict` instance from an existing dict, a class (e.g. old class-based config) or None.
325
+
326
+ Args:
327
+ config: The input config.
328
+
329
+ Returns:
330
+ A ConfigDict object created from config.
331
+ """
332
+ if config is None:
333
+ return ConfigDict()
334
+
335
+ if not isinstance(config, dict):
336
+ warnings.warn(DEPRECATION_MESSAGE, PydanticDeprecatedSince20, stacklevel=4)
337
+ config = {k: getattr(config, k) for k in dir(config) if not k.startswith('__')}
338
+
339
+ config_dict = cast(ConfigDict, config)
340
+ check_deprecated(config_dict)
341
+ return config_dict
342
+
343
+
344
+ config_keys = set(ConfigDict.__annotations__.keys())
345
+
346
+
347
+ V2_REMOVED_KEYS = {
348
+ 'allow_mutation',
349
+ 'error_msg_templates',
350
+ 'fields',
351
+ 'getter_dict',
352
+ 'smart_union',
353
+ 'underscore_attrs_are_private',
354
+ 'json_loads',
355
+ 'json_dumps',
356
+ 'copy_on_model_validation',
357
+ 'post_init_call',
358
+ }
359
+ V2_RENAMED_KEYS = {
360
+ 'allow_population_by_field_name': 'validate_by_name',
361
+ 'anystr_lower': 'str_to_lower',
362
+ 'anystr_strip_whitespace': 'str_strip_whitespace',
363
+ 'anystr_upper': 'str_to_upper',
364
+ 'keep_untouched': 'ignored_types',
365
+ 'max_anystr_length': 'str_max_length',
366
+ 'min_anystr_length': 'str_min_length',
367
+ 'orm_mode': 'from_attributes',
368
+ 'schema_extra': 'json_schema_extra',
369
+ 'validate_all': 'validate_default',
370
+ }
371
+
372
+
373
+ def check_deprecated(config_dict: ConfigDict) -> None:
374
+ """Check for deprecated config keys and warn the user.
375
+
376
+ Args:
377
+ config_dict: The input config.
378
+ """
379
+ deprecated_removed_keys = V2_REMOVED_KEYS & config_dict.keys()
380
+ deprecated_renamed_keys = V2_RENAMED_KEYS.keys() & config_dict.keys()
381
+ if deprecated_removed_keys or deprecated_renamed_keys:
382
+ renamings = {k: V2_RENAMED_KEYS[k] for k in sorted(deprecated_renamed_keys)}
383
+ renamed_bullets = [f'* {k!r} has been renamed to {v!r}' for k, v in renamings.items()]
384
+ removed_bullets = [f'* {k!r} has been removed' for k in sorted(deprecated_removed_keys)]
385
+ message = '\n'.join(['Valid config keys have changed in V2:'] + renamed_bullets + removed_bullets)
386
+ warnings.warn(message, UserWarning)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_core_metadata.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations as _annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, TypedDict, cast
4
+ from warnings import warn
5
+
6
+ if TYPE_CHECKING:
7
+ from ..config import JsonDict, JsonSchemaExtraCallable
8
+ from ._schema_generation_shared import (
9
+ GetJsonSchemaFunction,
10
+ )
11
+
12
+
13
+ class CoreMetadata(TypedDict, total=False):
14
+ """A `TypedDict` for holding the metadata dict of the schema.
15
+
16
+ Attributes:
17
+ pydantic_js_functions: List of JSON schema functions that resolve refs during application.
18
+ pydantic_js_annotation_functions: List of JSON schema functions that don't resolve refs during application.
19
+ pydantic_js_prefer_positional_arguments: Whether JSON schema generator will
20
+ prefer positional over keyword arguments for an 'arguments' schema.
21
+ custom validation function. Only applies to before, plain, and wrap validators.
22
+ pydantic_js_updates: key / value pair updates to apply to the JSON schema for a type.
23
+ pydantic_js_extra: WIP, either key/value pair updates to apply to the JSON schema, or a custom callable.
24
+ pydantic_internal_union_tag_key: Used internally by the `Tag` metadata to specify the tag used for a discriminated union.
25
+ pydantic_internal_union_discriminator: Used internally to specify the discriminator value for a discriminated union
26
+ when the discriminator was applied to a `'definition-ref'` schema, and that reference was missing at the time
27
+ of the annotation application.
28
+
29
+ TODO: Perhaps we should move this structure to pydantic-core. At the moment, though,
30
+ it's easier to iterate on if we leave it in pydantic until we feel there is a semi-stable API.
31
+
32
+ TODO: It's unfortunate how functionally oriented JSON schema generation is, especially that which occurs during
33
+ the core schema generation process. It's inevitable that we need to store some json schema related information
34
+ on core schemas, given that we generate JSON schemas directly from core schemas. That being said, debugging related
35
+ issues is quite difficult when JSON schema information is disguised via dynamically defined functions.
36
+ """
37
+
38
+ pydantic_js_functions: list[GetJsonSchemaFunction]
39
+ pydantic_js_annotation_functions: list[GetJsonSchemaFunction]
40
+ pydantic_js_prefer_positional_arguments: bool
41
+ pydantic_js_updates: JsonDict
42
+ pydantic_js_extra: JsonDict | JsonSchemaExtraCallable
43
+ pydantic_internal_union_tag_key: str
44
+ pydantic_internal_union_discriminator: str
45
+
46
+
47
+ def update_core_metadata(
48
+ core_metadata: Any,
49
+ /,
50
+ *,
51
+ pydantic_js_functions: list[GetJsonSchemaFunction] | None = None,
52
+ pydantic_js_annotation_functions: list[GetJsonSchemaFunction] | None = None,
53
+ pydantic_js_updates: JsonDict | None = None,
54
+ pydantic_js_extra: JsonDict | JsonSchemaExtraCallable | None = None,
55
+ ) -> None:
56
+ from ..json_schema import PydanticJsonSchemaWarning
57
+
58
+ """Update CoreMetadata instance in place. When we make modifications in this function, they
59
+ take effect on the `core_metadata` reference passed in as the first (and only) positional argument.
60
+
61
+ First, cast to `CoreMetadata`, then finish with a cast to `dict[str, Any]` for core schema compatibility.
62
+ We do this here, instead of before / after each call to this function so that this typing hack
63
+ can be easily removed if/when we move `CoreMetadata` to `pydantic-core`.
64
+
65
+ For parameter descriptions, see `CoreMetadata` above.
66
+ """
67
+ core_metadata = cast(CoreMetadata, core_metadata)
68
+
69
+ if pydantic_js_functions:
70
+ core_metadata.setdefault('pydantic_js_functions', []).extend(pydantic_js_functions)
71
+
72
+ if pydantic_js_annotation_functions:
73
+ core_metadata.setdefault('pydantic_js_annotation_functions', []).extend(pydantic_js_annotation_functions)
74
+
75
+ if pydantic_js_updates:
76
+ if (existing_updates := core_metadata.get('pydantic_js_updates')) is not None:
77
+ core_metadata['pydantic_js_updates'] = {**existing_updates, **pydantic_js_updates}
78
+ else:
79
+ core_metadata['pydantic_js_updates'] = pydantic_js_updates
80
+
81
+ if pydantic_js_extra is not None:
82
+ existing_pydantic_js_extra = core_metadata.get('pydantic_js_extra')
83
+ if existing_pydantic_js_extra is None:
84
+ core_metadata['pydantic_js_extra'] = pydantic_js_extra
85
+ if isinstance(existing_pydantic_js_extra, dict):
86
+ if isinstance(pydantic_js_extra, dict):
87
+ core_metadata['pydantic_js_extra'] = {**existing_pydantic_js_extra, **pydantic_js_extra}
88
+ if callable(pydantic_js_extra):
89
+ warn(
90
+ 'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
91
+ 'The `callable` type is being ignored.'
92
+ "If you'd like support for this behavior, please open an issue on pydantic.",
93
+ PydanticJsonSchemaWarning,
94
+ )
95
+ if callable(existing_pydantic_js_extra):
96
+ # if ever there's a case of a callable, we'll just keep the last json schema extra spec
97
+ core_metadata['pydantic_js_extra'] = pydantic_js_extra
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_core_utils.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import Mapping, Sequence
5
+ from typing import TYPE_CHECKING, Any, Union
6
+
7
+ from pydantic_core import CoreSchema, core_schema
8
+ from typing_extensions import TypeGuard, get_args, get_origin
9
+ from typing_inspection import typing_objects
10
+
11
+ from . import _repr
12
+ from ._typing_extra import is_generic_alias
13
+
14
+ if TYPE_CHECKING:
15
+ from rich.console import Console
16
+
17
+ AnyFunctionSchema = Union[
18
+ core_schema.AfterValidatorFunctionSchema,
19
+ core_schema.BeforeValidatorFunctionSchema,
20
+ core_schema.WrapValidatorFunctionSchema,
21
+ core_schema.PlainValidatorFunctionSchema,
22
+ ]
23
+
24
+
25
+ FunctionSchemaWithInnerSchema = Union[
26
+ core_schema.AfterValidatorFunctionSchema,
27
+ core_schema.BeforeValidatorFunctionSchema,
28
+ core_schema.WrapValidatorFunctionSchema,
29
+ ]
30
+
31
+ CoreSchemaField = Union[
32
+ core_schema.ModelField, core_schema.DataclassField, core_schema.TypedDictField, core_schema.ComputedField
33
+ ]
34
+ CoreSchemaOrField = Union[core_schema.CoreSchema, CoreSchemaField]
35
+
36
+ _CORE_SCHEMA_FIELD_TYPES = {'typed-dict-field', 'dataclass-field', 'model-field', 'computed-field'}
37
+ _FUNCTION_WITH_INNER_SCHEMA_TYPES = {'function-before', 'function-after', 'function-wrap'}
38
+ _LIST_LIKE_SCHEMA_WITH_ITEMS_TYPES = {'list', 'set', 'frozenset'}
39
+
40
+
41
+ def is_core_schema(
42
+ schema: CoreSchemaOrField,
43
+ ) -> TypeGuard[CoreSchema]:
44
+ return schema['type'] not in _CORE_SCHEMA_FIELD_TYPES
45
+
46
+
47
+ def is_core_schema_field(
48
+ schema: CoreSchemaOrField,
49
+ ) -> TypeGuard[CoreSchemaField]:
50
+ return schema['type'] in _CORE_SCHEMA_FIELD_TYPES
51
+
52
+
53
+ def is_function_with_inner_schema(
54
+ schema: CoreSchemaOrField,
55
+ ) -> TypeGuard[FunctionSchemaWithInnerSchema]:
56
+ return schema['type'] in _FUNCTION_WITH_INNER_SCHEMA_TYPES
57
+
58
+
59
+ def is_list_like_schema_with_items_schema(
60
+ schema: CoreSchema,
61
+ ) -> TypeGuard[core_schema.ListSchema | core_schema.SetSchema | core_schema.FrozenSetSchema]:
62
+ return schema['type'] in _LIST_LIKE_SCHEMA_WITH_ITEMS_TYPES
63
+
64
+
65
+ def get_type_ref(type_: Any, args_override: tuple[type[Any], ...] | None = None) -> str:
66
+ """Produces the ref to be used for this type by pydantic_core's core schemas.
67
+
68
+ This `args_override` argument was added for the purpose of creating valid recursive references
69
+ when creating generic models without needing to create a concrete class.
70
+ """
71
+ origin = get_origin(type_) or type_
72
+
73
+ args = get_args(type_) if is_generic_alias(type_) else (args_override or ())
74
+ generic_metadata = getattr(type_, '__pydantic_generic_metadata__', None)
75
+ if generic_metadata:
76
+ origin = generic_metadata['origin'] or origin
77
+ args = generic_metadata['args'] or args
78
+
79
+ module_name = getattr(origin, '__module__', '<No __module__>')
80
+ if typing_objects.is_typealiastype(origin):
81
+ type_ref = f'{module_name}.{origin.__name__}:{id(origin)}'
82
+ else:
83
+ try:
84
+ qualname = getattr(origin, '__qualname__', f'<No __qualname__: {origin}>')
85
+ except Exception:
86
+ qualname = getattr(origin, '__qualname__', '<No __qualname__>')
87
+ type_ref = f'{module_name}.{qualname}:{id(origin)}'
88
+
89
+ arg_refs: list[str] = []
90
+ for arg in args:
91
+ if isinstance(arg, str):
92
+ # Handle string literals as a special case; we may be able to remove this special handling if we
93
+ # wrap them in a ForwardRef at some point.
94
+ arg_ref = f'{arg}:str-{id(arg)}'
95
+ else:
96
+ arg_ref = f'{_repr.display_as_type(arg)}:{id(arg)}'
97
+ arg_refs.append(arg_ref)
98
+ if arg_refs:
99
+ type_ref = f'{type_ref}[{",".join(arg_refs)}]'
100
+ return type_ref
101
+
102
+
103
+ def get_ref(s: core_schema.CoreSchema) -> None | str:
104
+ """Get the ref from the schema if it has one.
105
+ This exists just for type checking to work correctly.
106
+ """
107
+ return s.get('ref', None)
108
+
109
+
110
+ def _clean_schema_for_pretty_print(obj: Any, strip_metadata: bool = True) -> Any: # pragma: no cover
111
+ """A utility function to remove irrelevant information from a core schema."""
112
+ if isinstance(obj, Mapping):
113
+ new_dct = {}
114
+ for k, v in obj.items():
115
+ if k == 'metadata' and strip_metadata:
116
+ new_metadata = {}
117
+
118
+ for meta_k, meta_v in v.items():
119
+ if meta_k in ('pydantic_js_functions', 'pydantic_js_annotation_functions'):
120
+ new_metadata['js_metadata'] = '<stripped>'
121
+ else:
122
+ new_metadata[meta_k] = _clean_schema_for_pretty_print(meta_v, strip_metadata=strip_metadata)
123
+
124
+ if list(new_metadata.keys()) == ['js_metadata']:
125
+ new_metadata = {'<stripped>'}
126
+
127
+ new_dct[k] = new_metadata
128
+ # Remove some defaults:
129
+ elif k in ('custom_init', 'root_model') and not v:
130
+ continue
131
+ else:
132
+ new_dct[k] = _clean_schema_for_pretty_print(v, strip_metadata=strip_metadata)
133
+
134
+ return new_dct
135
+ elif isinstance(obj, Sequence) and not isinstance(obj, str):
136
+ return [_clean_schema_for_pretty_print(v, strip_metadata=strip_metadata) for v in obj]
137
+ else:
138
+ return obj
139
+
140
+
141
+ def pretty_print_core_schema(
142
+ val: Any,
143
+ *,
144
+ console: Console | None = None,
145
+ max_depth: int | None = None,
146
+ strip_metadata: bool = True,
147
+ ) -> None: # pragma: no cover
148
+ """Pretty-print a core schema using the `rich` library.
149
+
150
+ Args:
151
+ val: The core schema to print, or a Pydantic model/dataclass/type adapter
152
+ (in which case the cached core schema is fetched and printed).
153
+ console: A rich console to use when printing. Defaults to the global rich console instance.
154
+ max_depth: The number of nesting levels which may be printed.
155
+ strip_metadata: Whether to strip metadata in the output. If `True` any known core metadata
156
+ attributes will be stripped (but custom attributes are kept). Defaults to `True`.
157
+ """
158
+ # lazy import:
159
+ from rich.pretty import pprint
160
+
161
+ # circ. imports:
162
+ from pydantic import BaseModel, TypeAdapter
163
+ from pydantic.dataclasses import is_pydantic_dataclass
164
+
165
+ if (inspect.isclass(val) and issubclass(val, BaseModel)) or is_pydantic_dataclass(val):
166
+ val = val.__pydantic_core_schema__
167
+ if isinstance(val, TypeAdapter):
168
+ val = val.core_schema
169
+ cleaned_schema = _clean_schema_for_pretty_print(val, strip_metadata=strip_metadata)
170
+
171
+ pprint(cleaned_schema, console=console, max_depth=max_depth)
172
+
173
+
174
+ pps = pretty_print_core_schema
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_dataclasses.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private logic for creating pydantic dataclasses."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ import copy
6
+ import dataclasses
7
+ import sys
8
+ import warnings
9
+ from collections.abc import Generator
10
+ from contextlib import contextmanager
11
+ from functools import partial
12
+ from typing import TYPE_CHECKING, Any, ClassVar, Protocol, cast
13
+
14
+ from pydantic_core import (
15
+ ArgsKwargs,
16
+ SchemaSerializer,
17
+ SchemaValidator,
18
+ core_schema,
19
+ )
20
+ from typing_extensions import TypeAlias, TypeIs
21
+
22
+ from ..errors import PydanticUndefinedAnnotation
23
+ from ..fields import FieldInfo
24
+ from ..plugin._schema_validator import PluggableSchemaValidator, create_schema_validator
25
+ from ..warnings import PydanticDeprecatedSince20
26
+ from . import _config, _decorators
27
+ from ._fields import collect_dataclass_fields
28
+ from ._generate_schema import GenerateSchema, InvalidSchemaError
29
+ from ._generics import get_standard_typevars_map
30
+ from ._mock_val_ser import set_dataclass_mocks
31
+ from ._namespace_utils import NsResolver
32
+ from ._signature import generate_pydantic_signature
33
+ from ._utils import LazyClassAttribute
34
+
35
+ if TYPE_CHECKING:
36
+ from _typeshed import DataclassInstance as StandardDataclass
37
+
38
+ from ..config import ConfigDict
39
+
40
+ class PydanticDataclass(StandardDataclass, Protocol):
41
+ """A protocol containing attributes only available once a class has been decorated as a Pydantic dataclass.
42
+
43
+ Attributes:
44
+ __pydantic_config__: Pydantic-specific configuration settings for the dataclass.
45
+ __pydantic_complete__: Whether dataclass building is completed, or if there are still undefined fields.
46
+ __pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.
47
+ __pydantic_decorators__: Metadata containing the decorators defined on the dataclass.
48
+ __pydantic_fields__: Metadata about the fields defined on the dataclass.
49
+ __pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the dataclass.
50
+ __pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the dataclass.
51
+ """
52
+
53
+ __pydantic_config__: ClassVar[ConfigDict]
54
+ __pydantic_complete__: ClassVar[bool]
55
+ __pydantic_core_schema__: ClassVar[core_schema.CoreSchema]
56
+ __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos]
57
+ __pydantic_fields__: ClassVar[dict[str, FieldInfo]]
58
+ __pydantic_serializer__: ClassVar[SchemaSerializer]
59
+ __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator]
60
+
61
+ @classmethod
62
+ def __pydantic_fields_complete__(cls) -> bool: ...
63
+
64
+
65
+ def set_dataclass_fields(
66
+ cls: type[StandardDataclass],
67
+ config_wrapper: _config.ConfigWrapper,
68
+ ns_resolver: NsResolver | None = None,
69
+ ) -> None:
70
+ """Collect and set `cls.__pydantic_fields__`.
71
+
72
+ Args:
73
+ cls: The class.
74
+ config_wrapper: The config wrapper instance.
75
+ ns_resolver: Namespace resolver to use when getting dataclass annotations.
76
+ """
77
+ typevars_map = get_standard_typevars_map(cls)
78
+ fields = collect_dataclass_fields(
79
+ cls, ns_resolver=ns_resolver, typevars_map=typevars_map, config_wrapper=config_wrapper
80
+ )
81
+
82
+ cls.__pydantic_fields__ = fields # type: ignore
83
+
84
+
85
+ def complete_dataclass(
86
+ cls: type[Any],
87
+ config_wrapper: _config.ConfigWrapper,
88
+ *,
89
+ raise_errors: bool = True,
90
+ ns_resolver: NsResolver | None = None,
91
+ _force_build: bool = False,
92
+ ) -> bool:
93
+ """Finish building a pydantic dataclass.
94
+
95
+ This logic is called on a class which has already been wrapped in `dataclasses.dataclass()`.
96
+
97
+ This is somewhat analogous to `pydantic._internal._model_construction.complete_model_class`.
98
+
99
+ Args:
100
+ cls: The class.
101
+ config_wrapper: The config wrapper instance.
102
+ raise_errors: Whether to raise errors, defaults to `True`.
103
+ ns_resolver: The namespace resolver instance to use when collecting dataclass fields
104
+ and during schema building.
105
+ _force_build: Whether to force building the dataclass, no matter if
106
+ [`defer_build`][pydantic.config.ConfigDict.defer_build] is set.
107
+
108
+ Returns:
109
+ `True` if building a pydantic dataclass is successfully completed, `False` otherwise.
110
+
111
+ Raises:
112
+ PydanticUndefinedAnnotation: If `raise_error` is `True` and there is an undefined annotations.
113
+ """
114
+ original_init = cls.__init__
115
+
116
+ # dataclass.__init__ must be defined here so its `__qualname__` can be changed since functions can't be copied,
117
+ # and so that the mock validator is used if building was deferred:
118
+ def __init__(__dataclass_self__: PydanticDataclass, *args: Any, **kwargs: Any) -> None:
119
+ __tracebackhide__ = True
120
+ s = __dataclass_self__
121
+ s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s)
122
+
123
+ __init__.__qualname__ = f'{cls.__qualname__}.__init__'
124
+
125
+ cls.__init__ = __init__ # type: ignore
126
+ cls.__pydantic_config__ = config_wrapper.config_dict # type: ignore
127
+
128
+ set_dataclass_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver)
129
+
130
+ if not _force_build and config_wrapper.defer_build:
131
+ set_dataclass_mocks(cls)
132
+ return False
133
+
134
+ if hasattr(cls, '__post_init_post_parse__'):
135
+ warnings.warn(
136
+ 'Support for `__post_init_post_parse__` has been dropped, the method will not be called',
137
+ PydanticDeprecatedSince20,
138
+ )
139
+
140
+ typevars_map = get_standard_typevars_map(cls)
141
+ gen_schema = GenerateSchema(
142
+ config_wrapper,
143
+ ns_resolver=ns_resolver,
144
+ typevars_map=typevars_map,
145
+ )
146
+
147
+ # set __signature__ attr only for the class, but not for its instances
148
+ # (because instances can define `__call__`, and `inspect.signature` shouldn't
149
+ # use the `__signature__` attribute and instead generate from `__call__`).
150
+ cls.__signature__ = LazyClassAttribute(
151
+ '__signature__',
152
+ partial(
153
+ generate_pydantic_signature,
154
+ # It's important that we reference the `original_init` here,
155
+ # as it is the one synthesized by the stdlib `dataclass` module:
156
+ init=original_init,
157
+ fields=cls.__pydantic_fields__, # type: ignore
158
+ validate_by_name=config_wrapper.validate_by_name,
159
+ extra=config_wrapper.extra,
160
+ is_dataclass=True,
161
+ ),
162
+ )
163
+
164
+ try:
165
+ schema = gen_schema.generate_schema(cls)
166
+ except PydanticUndefinedAnnotation as e:
167
+ if raise_errors:
168
+ raise
169
+ set_dataclass_mocks(cls, f'`{e.name}`')
170
+ return False
171
+
172
+ core_config = config_wrapper.core_config(title=cls.__name__)
173
+
174
+ try:
175
+ schema = gen_schema.clean_schema(schema)
176
+ except InvalidSchemaError:
177
+ set_dataclass_mocks(cls)
178
+ return False
179
+
180
+ # We are about to set all the remaining required properties expected for this cast;
181
+ # __pydantic_decorators__ and __pydantic_fields__ should already be set
182
+ cls = cast('type[PydanticDataclass]', cls)
183
+
184
+ cls.__pydantic_core_schema__ = schema
185
+ cls.__pydantic_validator__ = create_schema_validator(
186
+ schema, cls, cls.__module__, cls.__qualname__, 'dataclass', core_config, config_wrapper.plugin_settings
187
+ )
188
+ cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config)
189
+ cls.__pydantic_complete__ = True
190
+ return True
191
+
192
+
193
+ def is_stdlib_dataclass(cls: type[Any], /) -> TypeIs[type[StandardDataclass]]:
194
+ """Returns `True` if the class is a stdlib dataclass and *not* a Pydantic dataclass.
195
+
196
+ Unlike the stdlib `dataclasses.is_dataclass()` function, this does *not* include subclasses
197
+ of a dataclass that are themselves not dataclasses.
198
+
199
+ Args:
200
+ cls: The class.
201
+
202
+ Returns:
203
+ `True` if the class is a stdlib dataclass, `False` otherwise.
204
+ """
205
+ return '__dataclass_fields__' in cls.__dict__ and not hasattr(cls, '__pydantic_validator__')
206
+
207
+
208
+ def as_dataclass_field(pydantic_field: FieldInfo) -> dataclasses.Field[Any]:
209
+ field_args: dict[str, Any] = {'default': pydantic_field}
210
+
211
+ # Needed because if `doc` is set, the dataclass slots will be a dict (field name -> doc) instead of a tuple:
212
+ if sys.version_info >= (3, 14) and pydantic_field.description is not None:
213
+ field_args['doc'] = pydantic_field.description
214
+
215
+ # Needed as the stdlib dataclass module processes kw_only in a specific way during class construction:
216
+ if sys.version_info >= (3, 10) and pydantic_field.kw_only is not None:
217
+ field_args['kw_only'] = pydantic_field.kw_only
218
+
219
+ # Needed as the stdlib dataclass modules generates `__repr__()` during class construction:
220
+ if pydantic_field.repr is not True:
221
+ field_args['repr'] = pydantic_field.repr
222
+
223
+ return dataclasses.field(**field_args)
224
+
225
+
226
+ DcFields: TypeAlias = dict[str, dataclasses.Field[Any]]
227
+
228
+
229
+ @contextmanager
230
+ def patch_base_fields(cls: type[Any]) -> Generator[None]:
231
+ """Temporarily patch the stdlib dataclasses bases of `cls` if the Pydantic `Field()` function is used.
232
+
233
+ When creating a Pydantic dataclass, it is possible to inherit from stdlib dataclasses, where
234
+ the Pydantic `Field()` function is used. To create this Pydantic dataclass, we first apply
235
+ the stdlib `@dataclass` decorator on it. During the construction of the stdlib dataclass,
236
+ the `kw_only` and `repr` field arguments need to be understood by the stdlib *during* the
237
+ dataclass construction. To do so, we temporarily patch the fields dictionary of the affected
238
+ bases.
239
+
240
+ For instance, with the following example:
241
+
242
+ ```python {test="skip" lint="skip"}
243
+ import dataclasses as stdlib_dc
244
+
245
+ import pydantic
246
+ import pydantic.dataclasses as pydantic_dc
247
+
248
+ @stdlib_dc.dataclass
249
+ class A:
250
+ a: int = pydantic.Field(repr=False)
251
+
252
+ # Notice that the `repr` attribute of the dataclass field is `True`:
253
+ A.__dataclass_fields__['a']
254
+ #> dataclass.Field(default=FieldInfo(repr=False), repr=True, ...)
255
+
256
+ @pydantic_dc.dataclass
257
+ class B(A):
258
+ b: int = pydantic.Field(repr=False)
259
+ ```
260
+
261
+ When passing `B` to the stdlib `@dataclass` decorator, it will look for fields in the parent classes
262
+ and reuse them directly. When this context manager is active, `A` will be temporarily patched to be
263
+ equivalent to:
264
+
265
+ ```python {test="skip" lint="skip"}
266
+ @stdlib_dc.dataclass
267
+ class A:
268
+ a: int = stdlib_dc.field(default=Field(repr=False), repr=False)
269
+ ```
270
+
271
+ !!! note
272
+ This is only applied to the bases of `cls`, and not `cls` itself. The reason is that the Pydantic
273
+ dataclass decorator "owns" `cls` (in the previous example, `B`). As such, we instead modify the fields
274
+ directly (in the previous example, we simply do `setattr(B, 'b', as_dataclass_field(pydantic_field))`).
275
+
276
+ !!! note
277
+ This approach is far from ideal, and can probably be the source of unwanted side effects/race conditions.
278
+ The previous implemented approach was mutating the `__annotations__` dict of `cls`, which is no longer a
279
+ safe operation in Python 3.14+, and resulted in unexpected behavior with field ordering anyway.
280
+ """
281
+ # A list of two-tuples, the first element being a reference to the
282
+ # dataclass fields dictionary, the second element being a mapping between
283
+ # the field names that were modified, and their original `Field`:
284
+ original_fields_list: list[tuple[DcFields, DcFields]] = []
285
+
286
+ for base in cls.__mro__[1:]:
287
+ dc_fields: dict[str, dataclasses.Field[Any]] = base.__dict__.get('__dataclass_fields__', {})
288
+ dc_fields_with_pydantic_field_defaults = {
289
+ field_name: field
290
+ for field_name, field in dc_fields.items()
291
+ if isinstance(field.default, FieldInfo)
292
+ # Only do the patching if one of the affected attributes is set:
293
+ and (field.default.description is not None or field.default.kw_only or field.default.repr is not True)
294
+ }
295
+ if dc_fields_with_pydantic_field_defaults:
296
+ original_fields_list.append((dc_fields, dc_fields_with_pydantic_field_defaults))
297
+ for field_name, field in dc_fields_with_pydantic_field_defaults.items():
298
+ default = cast(FieldInfo, field.default)
299
+ # `dataclasses.Field` isn't documented as working with `copy.copy()`.
300
+ # It is a class with `__slots__`, so should work (and we hope for the best):
301
+ new_dc_field = copy.copy(field)
302
+ # For base fields, no need to set `doc` from `FieldInfo.description`, this is only relevant
303
+ # for the class under construction and handled in `as_dataclass_field()`.
304
+ if sys.version_info >= (3, 10) and default.kw_only:
305
+ new_dc_field.kw_only = True
306
+ if default.repr is not True:
307
+ new_dc_field.repr = default.repr
308
+ dc_fields[field_name] = new_dc_field
309
+
310
+ try:
311
+ yield
312
+ finally:
313
+ for fields, original_fields in original_fields_list:
314
+ for field_name, original_field in original_fields.items():
315
+ fields[field_name] = original_field
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_decorators.py ADDED
@@ -0,0 +1,873 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic related to validators applied to models etc. via the `@field_validator` and `@model_validator` decorators."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ import types
6
+ from collections import deque
7
+ from collections.abc import Iterable
8
+ from copy import copy
9
+ from dataclasses import dataclass, field
10
+ from functools import cached_property, partial, partialmethod
11
+ from inspect import Parameter, Signature, isdatadescriptor, ismethoddescriptor
12
+ from itertools import islice
13
+ from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, Literal, TypeVar, Union
14
+
15
+ from pydantic_core import PydanticUndefined, PydanticUndefinedType, core_schema
16
+ from typing_extensions import Self, TypeAlias, is_typeddict
17
+
18
+ from ..errors import PydanticUserError
19
+ from ._core_utils import get_type_ref
20
+ from ._internal_dataclass import slots_true
21
+ from ._namespace_utils import GlobalsNamespace, MappingNamespace
22
+ from ._typing_extra import get_function_type_hints, signature_no_eval
23
+ from ._utils import can_be_positional
24
+
25
+ if TYPE_CHECKING:
26
+ from ..fields import ComputedFieldInfo
27
+ from ..functional_validators import FieldValidatorModes
28
+ from ._config import ConfigWrapper
29
+
30
+
31
+ @dataclass(**slots_true)
32
+ class ValidatorDecoratorInfo:
33
+ """A container for data from `@validator` so that we can access it
34
+ while building the pydantic-core schema.
35
+
36
+ Attributes:
37
+ decorator_repr: A class variable representing the decorator string, '@validator'.
38
+ fields: A tuple of field names the validator should be called on.
39
+ mode: The proposed validator mode.
40
+ each_item: For complex objects (sets, lists etc.) whether to validate individual
41
+ elements rather than the whole object.
42
+ always: Whether this method and other validators should be called even if the value is missing.
43
+ check_fields: Whether to check that the fields actually exist on the model.
44
+ """
45
+
46
+ decorator_repr: ClassVar[str] = '@validator'
47
+
48
+ fields: tuple[str, ...]
49
+ mode: Literal['before', 'after']
50
+ each_item: bool
51
+ always: bool
52
+ check_fields: bool | None
53
+
54
+
55
+ @dataclass(**slots_true)
56
+ class FieldValidatorDecoratorInfo:
57
+ """A container for data from `@field_validator` so that we can access it
58
+ while building the pydantic-core schema.
59
+
60
+ Attributes:
61
+ decorator_repr: A class variable representing the decorator string, '@field_validator'.
62
+ fields: A tuple of field names the validator should be called on.
63
+ mode: The proposed validator mode.
64
+ check_fields: Whether to check that the fields actually exist on the model.
65
+ json_schema_input_type: The input type of the function. This is only used to generate
66
+ the appropriate JSON Schema (in validation mode) and can only specified
67
+ when `mode` is either `'before'`, `'plain'` or `'wrap'`.
68
+ """
69
+
70
+ decorator_repr: ClassVar[str] = '@field_validator'
71
+
72
+ fields: tuple[str, ...]
73
+ mode: FieldValidatorModes
74
+ check_fields: bool | None
75
+ json_schema_input_type: Any
76
+
77
+
78
+ @dataclass(**slots_true)
79
+ class RootValidatorDecoratorInfo:
80
+ """A container for data from `@root_validator` so that we can access it
81
+ while building the pydantic-core schema.
82
+
83
+ Attributes:
84
+ decorator_repr: A class variable representing the decorator string, '@root_validator'.
85
+ mode: The proposed validator mode.
86
+ """
87
+
88
+ decorator_repr: ClassVar[str] = '@root_validator'
89
+ mode: Literal['before', 'after']
90
+
91
+
92
+ @dataclass(**slots_true)
93
+ class FieldSerializerDecoratorInfo:
94
+ """A container for data from `@field_serializer` so that we can access it
95
+ while building the pydantic-core schema.
96
+
97
+ Attributes:
98
+ decorator_repr: A class variable representing the decorator string, '@field_serializer'.
99
+ fields: A tuple of field names the serializer should be called on.
100
+ mode: The proposed serializer mode.
101
+ return_type: The type of the serializer's return value.
102
+ when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`,
103
+ and `'json-unless-none'`.
104
+ check_fields: Whether to check that the fields actually exist on the model.
105
+ """
106
+
107
+ decorator_repr: ClassVar[str] = '@field_serializer'
108
+ fields: tuple[str, ...]
109
+ mode: Literal['plain', 'wrap']
110
+ return_type: Any
111
+ when_used: core_schema.WhenUsed
112
+ check_fields: bool | None
113
+
114
+
115
+ @dataclass(**slots_true)
116
+ class ModelSerializerDecoratorInfo:
117
+ """A container for data from `@model_serializer` so that we can access it
118
+ while building the pydantic-core schema.
119
+
120
+ Attributes:
121
+ decorator_repr: A class variable representing the decorator string, '@model_serializer'.
122
+ mode: The proposed serializer mode.
123
+ return_type: The type of the serializer's return value.
124
+ when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`,
125
+ and `'json-unless-none'`.
126
+ """
127
+
128
+ decorator_repr: ClassVar[str] = '@model_serializer'
129
+ mode: Literal['plain', 'wrap']
130
+ return_type: Any
131
+ when_used: core_schema.WhenUsed
132
+
133
+
134
+ @dataclass(**slots_true)
135
+ class ModelValidatorDecoratorInfo:
136
+ """A container for data from `@model_validator` so that we can access it
137
+ while building the pydantic-core schema.
138
+
139
+ Attributes:
140
+ decorator_repr: A class variable representing the decorator string, '@model_validator'.
141
+ mode: The proposed serializer mode.
142
+ """
143
+
144
+ decorator_repr: ClassVar[str] = '@model_validator'
145
+ mode: Literal['wrap', 'before', 'after']
146
+
147
+
148
+ DecoratorInfo: TypeAlias = """Union[
149
+ ValidatorDecoratorInfo,
150
+ FieldValidatorDecoratorInfo,
151
+ RootValidatorDecoratorInfo,
152
+ FieldSerializerDecoratorInfo,
153
+ ModelSerializerDecoratorInfo,
154
+ ModelValidatorDecoratorInfo,
155
+ ComputedFieldInfo,
156
+ ]"""
157
+
158
+ ReturnType = TypeVar('ReturnType')
159
+ DecoratedType: TypeAlias = (
160
+ 'Union[classmethod[Any, Any, ReturnType], staticmethod[Any, ReturnType], Callable[..., ReturnType], property]'
161
+ )
162
+
163
+
164
+ @dataclass # can't use slots here since we set attributes on `__post_init__`
165
+ class PydanticDescriptorProxy(Generic[ReturnType]):
166
+ """Wrap a classmethod, staticmethod, property or unbound function
167
+ and act as a descriptor that allows us to detect decorated items
168
+ from the class' attributes.
169
+
170
+ This class' __get__ returns the wrapped item's __get__ result,
171
+ which makes it transparent for classmethods and staticmethods.
172
+
173
+ Attributes:
174
+ wrapped: The decorator that has to be wrapped.
175
+ decorator_info: The decorator info.
176
+ shim: A wrapper function to wrap V1 style function.
177
+ """
178
+
179
+ wrapped: DecoratedType[ReturnType]
180
+ decorator_info: DecoratorInfo
181
+ shim: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None
182
+
183
+ def __post_init__(self):
184
+ for attr in 'setter', 'deleter':
185
+ if hasattr(self.wrapped, attr):
186
+ f = partial(self._call_wrapped_attr, name=attr)
187
+ setattr(self, attr, f)
188
+
189
+ def _call_wrapped_attr(self, func: Callable[[Any], None], *, name: str) -> PydanticDescriptorProxy[ReturnType]:
190
+ self.wrapped = getattr(self.wrapped, name)(func)
191
+ if isinstance(self.wrapped, property):
192
+ # update ComputedFieldInfo.wrapped_property
193
+ from ..fields import ComputedFieldInfo
194
+
195
+ if isinstance(self.decorator_info, ComputedFieldInfo):
196
+ self.decorator_info.wrapped_property = self.wrapped
197
+ return self
198
+
199
+ def __get__(self, obj: object | None, obj_type: type[object] | None = None) -> PydanticDescriptorProxy[ReturnType]:
200
+ try:
201
+ return self.wrapped.__get__(obj, obj_type) # pyright: ignore[reportReturnType]
202
+ except AttributeError:
203
+ # not a descriptor, e.g. a partial object
204
+ return self.wrapped # type: ignore[return-value]
205
+
206
+ def __set_name__(self, instance: Any, name: str) -> None:
207
+ if hasattr(self.wrapped, '__set_name__'):
208
+ self.wrapped.__set_name__(instance, name) # pyright: ignore[reportFunctionMemberAccess]
209
+
210
+ def __getattr__(self, name: str, /) -> Any:
211
+ """Forward checks for __isabstractmethod__ and such."""
212
+ return getattr(self.wrapped, name)
213
+
214
+
215
+ DecoratorInfoType = TypeVar('DecoratorInfoType', bound=DecoratorInfo)
216
+
217
+
218
+ @dataclass(**slots_true)
219
+ class Decorator(Generic[DecoratorInfoType]):
220
+ """A generic container class to join together the decorator metadata
221
+ (metadata from decorator itself, which we have when the
222
+ decorator is called but not when we are building the core-schema)
223
+ and the bound function (which we have after the class itself is created).
224
+
225
+ Attributes:
226
+ cls_ref: The class ref.
227
+ cls_var_name: The decorated function name.
228
+ func: The decorated function.
229
+ shim: A wrapper function to wrap V1 style function.
230
+ info: The decorator info.
231
+ """
232
+
233
+ cls_ref: str
234
+ cls_var_name: str
235
+ func: Callable[..., Any]
236
+ shim: Callable[[Any], Any] | None
237
+ info: DecoratorInfoType
238
+
239
+ @staticmethod
240
+ def build(
241
+ cls_: Any,
242
+ *,
243
+ cls_var_name: str,
244
+ shim: Callable[[Any], Any] | None,
245
+ info: DecoratorInfoType,
246
+ ) -> Decorator[DecoratorInfoType]:
247
+ """Build a new decorator.
248
+
249
+ Args:
250
+ cls_: The class.
251
+ cls_var_name: The decorated function name.
252
+ shim: A wrapper function to wrap V1 style function.
253
+ info: The decorator info.
254
+
255
+ Returns:
256
+ The new decorator instance.
257
+ """
258
+ func = get_attribute_from_bases(cls_, cls_var_name)
259
+ if shim is not None:
260
+ func = shim(func)
261
+ func = unwrap_wrapped_function(func, unwrap_partial=False)
262
+ if not callable(func):
263
+ # TODO most likely this branch can be removed when we drop support for Python 3.12:
264
+ # This branch will get hit for classmethod properties
265
+ attribute = get_attribute_from_base_dicts(cls_, cls_var_name) # prevents the binding call to `__get__`
266
+ if isinstance(attribute, PydanticDescriptorProxy):
267
+ func = unwrap_wrapped_function(attribute.wrapped)
268
+ return Decorator(
269
+ cls_ref=get_type_ref(cls_),
270
+ cls_var_name=cls_var_name,
271
+ func=func,
272
+ shim=shim,
273
+ info=info,
274
+ )
275
+
276
+ def bind_to_cls(self, cls: Any) -> Decorator[DecoratorInfoType]:
277
+ """Bind the decorator to a class.
278
+
279
+ Args:
280
+ cls: the class.
281
+
282
+ Returns:
283
+ The new decorator instance.
284
+ """
285
+ return self.build(
286
+ cls,
287
+ cls_var_name=self.cls_var_name,
288
+ shim=self.shim,
289
+ info=copy(self.info),
290
+ )
291
+
292
+
293
+ def get_bases(tp: type[Any]) -> tuple[type[Any], ...]:
294
+ """Get the base classes of a class or typeddict.
295
+
296
+ Args:
297
+ tp: The type or class to get the bases.
298
+
299
+ Returns:
300
+ The base classes.
301
+ """
302
+ if is_typeddict(tp):
303
+ return tp.__orig_bases__ # type: ignore
304
+ try:
305
+ return tp.__bases__
306
+ except AttributeError:
307
+ return ()
308
+
309
+
310
+ def mro(tp: type[Any]) -> tuple[type[Any], ...]:
311
+ """Calculate the Method Resolution Order of bases using the C3 algorithm.
312
+
313
+ See https://www.python.org/download/releases/2.3/mro/
314
+ """
315
+ # try to use the existing mro, for performance mainly
316
+ # but also because it helps verify the implementation below
317
+ if not is_typeddict(tp):
318
+ try:
319
+ return tp.__mro__
320
+ except AttributeError:
321
+ # GenericAlias and some other cases
322
+ pass
323
+
324
+ bases = get_bases(tp)
325
+ return (tp,) + mro_for_bases(bases)
326
+
327
+
328
+ def mro_for_bases(bases: tuple[type[Any], ...]) -> tuple[type[Any], ...]:
329
+ def merge_seqs(seqs: list[deque[type[Any]]]) -> Iterable[type[Any]]:
330
+ while True:
331
+ non_empty = [seq for seq in seqs if seq]
332
+ if not non_empty:
333
+ # Nothing left to process, we're done.
334
+ return
335
+ candidate: type[Any] | None = None
336
+ for seq in non_empty: # Find merge candidates among seq heads.
337
+ candidate = seq[0]
338
+ not_head = [s for s in non_empty if candidate in islice(s, 1, None)]
339
+ if not_head:
340
+ # Reject the candidate.
341
+ candidate = None
342
+ else:
343
+ break
344
+ if not candidate:
345
+ raise TypeError('Inconsistent hierarchy, no C3 MRO is possible')
346
+ yield candidate
347
+ for seq in non_empty:
348
+ # Remove candidate.
349
+ if seq[0] == candidate:
350
+ seq.popleft()
351
+
352
+ seqs = [deque(mro(base)) for base in bases] + [deque(bases)]
353
+ return tuple(merge_seqs(seqs))
354
+
355
+
356
+ _sentinel = object()
357
+
358
+
359
+ def get_attribute_from_bases(tp: type[Any] | tuple[type[Any], ...], name: str) -> Any:
360
+ """Get the attribute from the next class in the MRO that has it,
361
+ aiming to simulate calling the method on the actual class.
362
+
363
+ The reason for iterating over the mro instead of just getting
364
+ the attribute (which would do that for us) is to support TypedDict,
365
+ which lacks a real __mro__, but can have a virtual one constructed
366
+ from its bases (as done here).
367
+
368
+ Args:
369
+ tp: The type or class to search for the attribute. If a tuple, this is treated as a set of base classes.
370
+ name: The name of the attribute to retrieve.
371
+
372
+ Returns:
373
+ Any: The attribute value, if found.
374
+
375
+ Raises:
376
+ AttributeError: If the attribute is not found in any class in the MRO.
377
+ """
378
+ if isinstance(tp, tuple):
379
+ for base in mro_for_bases(tp):
380
+ attribute = base.__dict__.get(name, _sentinel)
381
+ if attribute is not _sentinel:
382
+ attribute_get = getattr(attribute, '__get__', None)
383
+ if attribute_get is not None:
384
+ return attribute_get(None, tp)
385
+ return attribute
386
+ raise AttributeError(f'{name} not found in {tp}')
387
+ else:
388
+ try:
389
+ return getattr(tp, name)
390
+ except AttributeError:
391
+ return get_attribute_from_bases(mro(tp), name)
392
+
393
+
394
+ def get_attribute_from_base_dicts(tp: type[Any], name: str) -> Any:
395
+ """Get an attribute out of the `__dict__` following the MRO.
396
+ This prevents the call to `__get__` on the descriptor, and allows
397
+ us to get the original function for classmethod properties.
398
+
399
+ Args:
400
+ tp: The type or class to search for the attribute.
401
+ name: The name of the attribute to retrieve.
402
+
403
+ Returns:
404
+ Any: The attribute value, if found.
405
+
406
+ Raises:
407
+ KeyError: If the attribute is not found in any class's `__dict__` in the MRO.
408
+ """
409
+ for base in reversed(mro(tp)):
410
+ if name in base.__dict__:
411
+ return base.__dict__[name]
412
+ return tp.__dict__[name] # raise the error
413
+
414
+
415
+ @dataclass(**slots_true)
416
+ class DecoratorInfos:
417
+ """Mapping of name in the class namespace to decorator info.
418
+
419
+ note that the name in the class namespace is the function or attribute name
420
+ not the field name!
421
+ """
422
+
423
+ validators: dict[str, Decorator[ValidatorDecoratorInfo]] = field(default_factory=dict)
424
+ field_validators: dict[str, Decorator[FieldValidatorDecoratorInfo]] = field(default_factory=dict)
425
+ root_validators: dict[str, Decorator[RootValidatorDecoratorInfo]] = field(default_factory=dict)
426
+ field_serializers: dict[str, Decorator[FieldSerializerDecoratorInfo]] = field(default_factory=dict)
427
+ model_serializers: dict[str, Decorator[ModelSerializerDecoratorInfo]] = field(default_factory=dict)
428
+ model_validators: dict[str, Decorator[ModelValidatorDecoratorInfo]] = field(default_factory=dict)
429
+ computed_fields: dict[str, Decorator[ComputedFieldInfo]] = field(default_factory=dict)
430
+
431
+ @classmethod
432
+ def build(
433
+ cls,
434
+ typ: type[Any],
435
+ # Default to `True` for backwards compatibility:
436
+ replace_wrapped_methods: bool = True,
437
+ ) -> Self:
438
+ """Build a `DecoratorInfos` instance for the given model, dataclass or `TypedDict` type.
439
+
440
+ Decorators from parent classes are included, including "bare" classes (e.g. if `typ`
441
+ is a Pydantic model, non Pydantic parent model classes are also taken into account).
442
+ The collection of the decorators happens by respecting the MRO.
443
+
444
+ If one of the bases has an `__pydantic_decorators__` attribute set, it is assumed to be
445
+ a `DecoratorInfos` instance and is used as-is. The `__pydantic_decorators__` attribute
446
+ is *not* being set on the provided `typ`.
447
+
448
+ Args:
449
+ typ: The model, dataclass or `TypedDict` type to use when building the `DecoratorInfos` instance.
450
+ replace_wrapped_methods: Whether to replace the decorator's wrapped methods on `typ`.
451
+ This is useful e.g. for field validators which are initially class methods. This should
452
+ only be set to `True` if `typ` is a Pydantic model or dataclass (otherwise this results
453
+ in mutations of classes Pydantic doesn't "own").
454
+ """
455
+ # reminder: dicts are ordered and replacement does not alter the order
456
+ res = cls()
457
+ # Iterate over the bases, without the actual `typ`.
458
+ # `1:-1` because we don't need to include `object`/`TypedDict`:
459
+ for base in reversed(mro(typ)[1:-1]):
460
+ existing: DecoratorInfos | None = base.__dict__.get('__pydantic_decorators__')
461
+ if existing is None:
462
+ existing, _ = _decorator_infos_for_class(base, collect_to_replace=False)
463
+ res.validators.update({k: v.bind_to_cls(typ) for k, v in existing.validators.items()})
464
+ res.field_validators.update({k: v.bind_to_cls(typ) for k, v in existing.field_validators.items()})
465
+ res.root_validators.update({k: v.bind_to_cls(typ) for k, v in existing.root_validators.items()})
466
+ res.field_serializers.update({k: v.bind_to_cls(typ) for k, v in existing.field_serializers.items()})
467
+ res.model_serializers.update({k: v.bind_to_cls(typ) for k, v in existing.model_serializers.items()})
468
+ res.model_validators.update({k: v.bind_to_cls(typ) for k, v in existing.model_validators.items()})
469
+ res.computed_fields.update({k: v.bind_to_cls(typ) for k, v in existing.computed_fields.items()})
470
+
471
+ decorator_infos, to_replace = _decorator_infos_for_class(typ, collect_to_replace=True)
472
+
473
+ res.validators.update(decorator_infos.validators)
474
+ res.field_validators.update(decorator_infos.field_validators)
475
+ res.root_validators.update(decorator_infos.root_validators)
476
+ res.field_serializers.update(decorator_infos.field_serializers)
477
+ res.model_serializers.update(decorator_infos.model_serializers)
478
+ res.model_validators.update(decorator_infos.model_validators)
479
+ res.computed_fields.update(decorator_infos.computed_fields)
480
+
481
+ if replace_wrapped_methods and to_replace:
482
+ for name, value in to_replace:
483
+ setattr(typ, name, value)
484
+
485
+ res._validate()
486
+ return res
487
+
488
+ def _validate(self) -> None:
489
+ seen: set[str] = set()
490
+ for field_ser in self.field_serializers.values():
491
+ for f_name in field_ser.info.fields:
492
+ if f_name in seen:
493
+ raise PydanticUserError(
494
+ f'Multiple field serializer functions were defined for field {f_name!r}, this is not allowed.',
495
+ code='multiple-field-serializers',
496
+ )
497
+ seen.add(f_name)
498
+
499
+ def update_from_config(self, config_wrapper: ConfigWrapper) -> None:
500
+ """Update the decorator infos from the configuration of the class they are attached to."""
501
+ for name, computed_field_dec in self.computed_fields.items():
502
+ computed_field_dec.info._update_from_config(config_wrapper, name)
503
+
504
+
505
+ def _decorator_infos_for_class(
506
+ typ: type[Any],
507
+ *,
508
+ collect_to_replace: bool,
509
+ ) -> tuple[DecoratorInfos, list[tuple[str, Any]]]:
510
+ """Collect a `DecoratorInfos` for class, without looking into bases."""
511
+ res = DecoratorInfos()
512
+ to_replace: list[tuple[str, Any]] = []
513
+
514
+ for var_name, var_value in vars(typ).items():
515
+ if isinstance(var_value, PydanticDescriptorProxy):
516
+ info = var_value.decorator_info
517
+ if isinstance(info, ValidatorDecoratorInfo):
518
+ res.validators[var_name] = Decorator.build(typ, cls_var_name=var_name, shim=var_value.shim, info=info)
519
+ elif isinstance(info, FieldValidatorDecoratorInfo):
520
+ res.field_validators[var_name] = Decorator.build(
521
+ typ, cls_var_name=var_name, shim=var_value.shim, info=info
522
+ )
523
+ elif isinstance(info, RootValidatorDecoratorInfo):
524
+ res.root_validators[var_name] = Decorator.build(
525
+ typ, cls_var_name=var_name, shim=var_value.shim, info=info
526
+ )
527
+ elif isinstance(info, FieldSerializerDecoratorInfo):
528
+ res.field_serializers[var_name] = Decorator.build(
529
+ typ, cls_var_name=var_name, shim=var_value.shim, info=info
530
+ )
531
+ elif isinstance(info, ModelValidatorDecoratorInfo):
532
+ res.model_validators[var_name] = Decorator.build(
533
+ typ, cls_var_name=var_name, shim=var_value.shim, info=info
534
+ )
535
+ elif isinstance(info, ModelSerializerDecoratorInfo):
536
+ res.model_serializers[var_name] = Decorator.build(
537
+ typ, cls_var_name=var_name, shim=var_value.shim, info=info
538
+ )
539
+ else:
540
+ from ..fields import ComputedFieldInfo
541
+
542
+ isinstance(var_value, ComputedFieldInfo)
543
+ res.computed_fields[var_name] = Decorator.build(typ, cls_var_name=var_name, shim=None, info=info)
544
+ if collect_to_replace:
545
+ to_replace.append((var_name, var_value.wrapped))
546
+
547
+ return res, to_replace
548
+
549
+
550
+ def inspect_validator(
551
+ validator: Callable[..., Any], *, mode: FieldValidatorModes, type: Literal['field', 'model']
552
+ ) -> bool:
553
+ """Look at a field or model validator function and determine whether it takes an info argument.
554
+
555
+ An error is raised if the function has an invalid signature.
556
+
557
+ Args:
558
+ validator: The validator function to inspect.
559
+ mode: The proposed validator mode.
560
+ type: The type of validator, either 'field' or 'model'.
561
+
562
+ Returns:
563
+ Whether the validator takes an info argument.
564
+ """
565
+ try:
566
+ sig = signature_no_eval(validator)
567
+ except (ValueError, TypeError):
568
+ # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
569
+ # In this case, we assume no info argument is present:
570
+ return False
571
+ n_positional = count_positional_required_params(sig)
572
+ if mode == 'wrap':
573
+ if n_positional == 3:
574
+ return True
575
+ elif n_positional == 2:
576
+ return False
577
+ else:
578
+ assert mode in {'before', 'after', 'plain'}, f"invalid mode: {mode!r}, expected 'before', 'after' or 'plain"
579
+ if n_positional == 2:
580
+ return True
581
+ elif n_positional == 1:
582
+ return False
583
+
584
+ raise PydanticUserError(
585
+ f'Unrecognized {type} validator function signature for {validator} with `mode={mode}`: {sig}',
586
+ code='validator-signature',
587
+ )
588
+
589
+
590
+ def inspect_field_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> tuple[bool, bool]:
591
+ """Look at a field serializer function and determine if it is a field serializer,
592
+ and whether it takes an info argument.
593
+
594
+ An error is raised if the function has an invalid signature.
595
+
596
+ Args:
597
+ serializer: The serializer function to inspect.
598
+ mode: The serializer mode, either 'plain' or 'wrap'.
599
+
600
+ Returns:
601
+ Tuple of (is_field_serializer, info_arg).
602
+ """
603
+ try:
604
+ sig = signature_no_eval(serializer)
605
+ except (ValueError, TypeError):
606
+ # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
607
+ # In this case, we assume no info argument is present and this is not a method:
608
+ return (False, False)
609
+
610
+ first = next(iter(sig.parameters.values()), None)
611
+ is_field_serializer = first is not None and first.name == 'self'
612
+
613
+ n_positional = count_positional_required_params(sig)
614
+ if is_field_serializer:
615
+ # -1 to correct for self parameter
616
+ info_arg = _serializer_info_arg(mode, n_positional - 1)
617
+ else:
618
+ info_arg = _serializer_info_arg(mode, n_positional)
619
+
620
+ if info_arg is None:
621
+ raise PydanticUserError(
622
+ f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}',
623
+ code='field-serializer-signature',
624
+ )
625
+
626
+ return is_field_serializer, info_arg
627
+
628
+
629
+ def inspect_annotated_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool:
630
+ """Look at a serializer function used via `Annotated` and determine whether it takes an info argument.
631
+
632
+ An error is raised if the function has an invalid signature.
633
+
634
+ Args:
635
+ serializer: The serializer function to check.
636
+ mode: The serializer mode, either 'plain' or 'wrap'.
637
+
638
+ Returns:
639
+ info_arg
640
+ """
641
+ try:
642
+ sig = signature_no_eval(serializer)
643
+ except (ValueError, TypeError):
644
+ # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
645
+ # In this case, we assume no info argument is present:
646
+ return False
647
+ info_arg = _serializer_info_arg(mode, count_positional_required_params(sig))
648
+ if info_arg is None:
649
+ raise PydanticUserError(
650
+ f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}',
651
+ code='field-serializer-signature',
652
+ )
653
+ else:
654
+ return info_arg
655
+
656
+
657
+ def inspect_model_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool:
658
+ """Look at a model serializer function and determine whether it takes an info argument.
659
+
660
+ An error is raised if the function has an invalid signature.
661
+
662
+ Args:
663
+ serializer: The serializer function to check.
664
+ mode: The serializer mode, either 'plain' or 'wrap'.
665
+
666
+ Returns:
667
+ `info_arg` - whether the function expects an info argument.
668
+ """
669
+ if isinstance(serializer, (staticmethod, classmethod)) or not is_instance_method_from_sig(serializer):
670
+ raise PydanticUserError(
671
+ '`@model_serializer` must be applied to instance methods', code='model-serializer-instance-method'
672
+ )
673
+
674
+ sig = signature_no_eval(serializer)
675
+ info_arg = _serializer_info_arg(mode, count_positional_required_params(sig))
676
+ if info_arg is None:
677
+ raise PydanticUserError(
678
+ f'Unrecognized model_serializer function signature for {serializer} with `mode={mode}`:{sig}',
679
+ code='model-serializer-signature',
680
+ )
681
+ else:
682
+ return info_arg
683
+
684
+
685
+ def _serializer_info_arg(mode: Literal['plain', 'wrap'], n_positional: int) -> bool | None:
686
+ if mode == 'plain':
687
+ if n_positional == 1:
688
+ # (input_value: Any, /) -> Any
689
+ return False
690
+ elif n_positional == 2:
691
+ # (model: Any, input_value: Any, /) -> Any
692
+ return True
693
+ else:
694
+ assert mode == 'wrap', f"invalid mode: {mode!r}, expected 'plain' or 'wrap'"
695
+ if n_positional == 2:
696
+ # (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
697
+ return False
698
+ elif n_positional == 3:
699
+ # (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any
700
+ return True
701
+
702
+ return None
703
+
704
+
705
+ AnyDecoratorCallable: TypeAlias = (
706
+ 'Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any], Callable[..., Any]]'
707
+ )
708
+
709
+
710
+ def is_instance_method_from_sig(function: AnyDecoratorCallable) -> bool:
711
+ """Whether the function is an instance method.
712
+
713
+ It will consider a function as instance method if the first parameter of
714
+ function is `self`.
715
+
716
+ Args:
717
+ function: The function to check.
718
+
719
+ Returns:
720
+ `True` if the function is an instance method, `False` otherwise.
721
+ """
722
+ sig = signature_no_eval(unwrap_wrapped_function(function))
723
+ first = next(iter(sig.parameters.values()), None)
724
+ if first and first.name == 'self':
725
+ return True
726
+ return False
727
+
728
+
729
+ def ensure_classmethod_based_on_signature(function: AnyDecoratorCallable) -> Any:
730
+ """Apply the `@classmethod` decorator on the function.
731
+
732
+ Args:
733
+ function: The function to apply the decorator on.
734
+
735
+ Return:
736
+ The `@classmethod` decorator applied function.
737
+ """
738
+ if not isinstance(
739
+ unwrap_wrapped_function(function, unwrap_class_static_method=False), classmethod
740
+ ) and _is_classmethod_from_sig(function):
741
+ return classmethod(function) # type: ignore[arg-type]
742
+ return function
743
+
744
+
745
+ def _is_classmethod_from_sig(function: AnyDecoratorCallable) -> bool:
746
+ sig = signature_no_eval(unwrap_wrapped_function(function))
747
+ first = next(iter(sig.parameters.values()), None)
748
+ if first and first.name == 'cls':
749
+ return True
750
+ return False
751
+
752
+
753
+ def unwrap_wrapped_function(
754
+ func: Any,
755
+ *,
756
+ unwrap_partial: bool = True,
757
+ unwrap_class_static_method: bool = True,
758
+ ) -> Any:
759
+ """Recursively unwraps a wrapped function until the underlying function is reached.
760
+ This handles property, functools.partial, functools.partialmethod, staticmethod, and classmethod.
761
+
762
+ Args:
763
+ func: The function to unwrap.
764
+ unwrap_partial: If True (default), unwrap partial and partialmethod decorators.
765
+ unwrap_class_static_method: If True (default), also unwrap classmethod and staticmethod
766
+ decorators. If False, only unwrap partial and partialmethod decorators.
767
+
768
+ Returns:
769
+ The underlying function of the wrapped function.
770
+ """
771
+ # Define the types we want to check against as a single tuple.
772
+ unwrap_types = (
773
+ (property, cached_property)
774
+ + ((partial, partialmethod) if unwrap_partial else ())
775
+ + ((staticmethod, classmethod) if unwrap_class_static_method else ())
776
+ )
777
+
778
+ while isinstance(func, unwrap_types):
779
+ if unwrap_class_static_method and isinstance(func, (classmethod, staticmethod)):
780
+ func = func.__func__
781
+ elif isinstance(func, (partial, partialmethod)):
782
+ func = func.func
783
+ elif isinstance(func, property):
784
+ func = func.fget # arbitrary choice, convenient for computed fields
785
+ else:
786
+ # Make coverage happy as it can only get here in the last possible case
787
+ assert isinstance(func, cached_property)
788
+ func = func.func # type: ignore
789
+
790
+ return func
791
+
792
+
793
+ _function_like = (
794
+ partial,
795
+ partialmethod,
796
+ types.FunctionType,
797
+ types.BuiltinFunctionType,
798
+ types.MethodType,
799
+ types.WrapperDescriptorType,
800
+ types.MethodWrapperType,
801
+ types.MemberDescriptorType,
802
+ )
803
+
804
+
805
+ def get_callable_return_type(
806
+ callable_obj: Any,
807
+ globalns: GlobalsNamespace | None = None,
808
+ localns: MappingNamespace | None = None,
809
+ ) -> Any | PydanticUndefinedType:
810
+ """Get the callable return type.
811
+
812
+ Args:
813
+ callable_obj: The callable to analyze.
814
+ globalns: The globals namespace to use during type annotation evaluation.
815
+ localns: The locals namespace to use during type annotation evaluation.
816
+
817
+ Returns:
818
+ The function return type.
819
+ """
820
+ if isinstance(callable_obj, type):
821
+ # types are callables, and we assume the return type
822
+ # is the type itself (e.g. `int()` results in an instance of `int`).
823
+ return callable_obj
824
+
825
+ if not isinstance(callable_obj, _function_like):
826
+ call_func = getattr(type(callable_obj), '__call__', None) # noqa: B004
827
+ if call_func is not None:
828
+ callable_obj = call_func
829
+
830
+ hints = get_function_type_hints(
831
+ unwrap_wrapped_function(callable_obj),
832
+ include_keys={'return'},
833
+ globalns=globalns,
834
+ localns=localns,
835
+ )
836
+ return hints.get('return', PydanticUndefined)
837
+
838
+
839
+ def count_positional_required_params(sig: Signature) -> int:
840
+ """Get the number of positional (required) arguments of a signature.
841
+
842
+ This function should only be used to inspect signatures of validation and serialization functions.
843
+ The first argument (the value being serialized or validated) is counted as a required argument
844
+ even if a default value exists.
845
+
846
+ Returns:
847
+ The number of positional arguments of a signature.
848
+ """
849
+ parameters = list(sig.parameters.values())
850
+ return sum(
851
+ 1
852
+ for param in parameters
853
+ if can_be_positional(param)
854
+ # First argument is the value being validated/serialized, and can have a default value
855
+ # (e.g. `float`, which has signature `(x=0, /)`). We assume other parameters (the info arg
856
+ # for instance) should be required, and thus without any default value.
857
+ and (param.default is Parameter.empty or param is parameters[0])
858
+ )
859
+
860
+
861
+ def ensure_property(f: Any) -> Any:
862
+ """Ensure that a function is a `property` or `cached_property`, or is a valid descriptor.
863
+
864
+ Args:
865
+ f: The function to check.
866
+
867
+ Returns:
868
+ The function, or a `property` or `cached_property` instance wrapping the function.
869
+ """
870
+ if ismethoddescriptor(f) or isdatadescriptor(f):
871
+ return f
872
+ else:
873
+ return property(f)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_decorators_v1.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic for V1 validators, e.g. `@validator` and `@root_validator`."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ from inspect import Parameter, signature
6
+ from typing import Any, Union, cast
7
+
8
+ from pydantic_core import core_schema
9
+ from typing_extensions import Protocol
10
+
11
+ from ..errors import PydanticUserError
12
+ from ._utils import can_be_positional
13
+
14
+
15
+ class V1OnlyValueValidator(Protocol):
16
+ """A simple validator, supported for V1 validators and V2 validators."""
17
+
18
+ def __call__(self, __value: Any) -> Any: ...
19
+
20
+
21
+ class V1ValidatorWithValues(Protocol):
22
+ """A validator with `values` argument, supported for V1 validators and V2 validators."""
23
+
24
+ def __call__(self, __value: Any, values: dict[str, Any]) -> Any: ...
25
+
26
+
27
+ class V1ValidatorWithValuesKwOnly(Protocol):
28
+ """A validator with keyword only `values` argument, supported for V1 validators and V2 validators."""
29
+
30
+ def __call__(self, __value: Any, *, values: dict[str, Any]) -> Any: ...
31
+
32
+
33
+ class V1ValidatorWithKwargs(Protocol):
34
+ """A validator with `kwargs` argument, supported for V1 validators and V2 validators."""
35
+
36
+ def __call__(self, __value: Any, **kwargs: Any) -> Any: ...
37
+
38
+
39
+ class V1ValidatorWithValuesAndKwargs(Protocol):
40
+ """A validator with `values` and `kwargs` arguments, supported for V1 validators and V2 validators."""
41
+
42
+ def __call__(self, __value: Any, values: dict[str, Any], **kwargs: Any) -> Any: ...
43
+
44
+
45
+ V1Validator = Union[
46
+ V1ValidatorWithValues, V1ValidatorWithValuesKwOnly, V1ValidatorWithKwargs, V1ValidatorWithValuesAndKwargs
47
+ ]
48
+
49
+
50
+ def can_be_keyword(param: Parameter) -> bool:
51
+ return param.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
52
+
53
+
54
+ def make_generic_v1_field_validator(validator: V1Validator) -> core_schema.WithInfoValidatorFunction:
55
+ """Wrap a V1 style field validator for V2 compatibility.
56
+
57
+ Args:
58
+ validator: The V1 style field validator.
59
+
60
+ Returns:
61
+ A wrapped V2 style field validator.
62
+
63
+ Raises:
64
+ PydanticUserError: If the signature is not supported or the parameters are
65
+ not available in Pydantic V2.
66
+ """
67
+ sig = signature(validator)
68
+
69
+ needs_values_kw = False
70
+
71
+ for param_num, (param_name, parameter) in enumerate(sig.parameters.items()):
72
+ if can_be_keyword(parameter) and param_name in ('field', 'config'):
73
+ raise PydanticUserError(
74
+ 'The `field` and `config` parameters are not available in Pydantic V2, '
75
+ 'please use the `info` parameter instead.',
76
+ code='validator-field-config-info',
77
+ )
78
+ if parameter.kind is Parameter.VAR_KEYWORD:
79
+ needs_values_kw = True
80
+ elif can_be_keyword(parameter) and param_name == 'values':
81
+ needs_values_kw = True
82
+ elif can_be_positional(parameter) and param_num == 0:
83
+ # value
84
+ continue
85
+ elif parameter.default is Parameter.empty: # ignore params with defaults e.g. bound by functools.partial
86
+ raise PydanticUserError(
87
+ f'Unsupported signature for V1 style validator {validator}: {sig} is not supported.',
88
+ code='validator-v1-signature',
89
+ )
90
+
91
+ if needs_values_kw:
92
+ # (v, **kwargs), (v, values, **kwargs), (v, *, values, **kwargs) or (v, *, values)
93
+ val1 = cast(V1ValidatorWithValues, validator)
94
+
95
+ def wrapper1(value: Any, info: core_schema.ValidationInfo) -> Any:
96
+ return val1(value, values=info.data)
97
+
98
+ return wrapper1
99
+ else:
100
+ val2 = cast(V1OnlyValueValidator, validator)
101
+
102
+ def wrapper2(value: Any, _: core_schema.ValidationInfo) -> Any:
103
+ return val2(value)
104
+
105
+ return wrapper2
106
+
107
+
108
+ RootValidatorValues = dict[str, Any]
109
+ # technically tuple[model_dict, model_extra, fields_set] | tuple[dataclass_dict, init_vars]
110
+ RootValidatorFieldsTuple = tuple[Any, ...]
111
+
112
+
113
+ class V1RootValidatorFunction(Protocol):
114
+ """A simple root validator, supported for V1 validators and V2 validators."""
115
+
116
+ def __call__(self, __values: RootValidatorValues) -> RootValidatorValues: ...
117
+
118
+
119
+ class V2CoreBeforeRootValidator(Protocol):
120
+ """V2 validator with mode='before'."""
121
+
122
+ def __call__(self, __values: RootValidatorValues, __info: core_schema.ValidationInfo) -> RootValidatorValues: ...
123
+
124
+
125
+ class V2CoreAfterRootValidator(Protocol):
126
+ """V2 validator with mode='after'."""
127
+
128
+ def __call__(
129
+ self, __fields_tuple: RootValidatorFieldsTuple, __info: core_schema.ValidationInfo
130
+ ) -> RootValidatorFieldsTuple: ...
131
+
132
+
133
+ def make_v1_generic_root_validator(
134
+ validator: V1RootValidatorFunction, pre: bool
135
+ ) -> V2CoreBeforeRootValidator | V2CoreAfterRootValidator:
136
+ """Wrap a V1 style root validator for V2 compatibility.
137
+
138
+ Args:
139
+ validator: The V1 style field validator.
140
+ pre: Whether the validator is a pre validator.
141
+
142
+ Returns:
143
+ A wrapped V2 style validator.
144
+ """
145
+ if pre is True:
146
+ # mode='before' for pydantic-core
147
+ def _wrapper1(values: RootValidatorValues, _: core_schema.ValidationInfo) -> RootValidatorValues:
148
+ return validator(values)
149
+
150
+ return _wrapper1
151
+
152
+ # mode='after' for pydantic-core
153
+ def _wrapper2(fields_tuple: RootValidatorFieldsTuple, _: core_schema.ValidationInfo) -> RootValidatorFieldsTuple:
154
+ if len(fields_tuple) == 2:
155
+ # dataclass, this is easy
156
+ values, init_vars = fields_tuple
157
+ values = validator(values)
158
+ return values, init_vars
159
+ else:
160
+ # ugly hack: to match v1 behaviour, we merge values and model_extra, then split them up based on fields
161
+ # afterwards
162
+ model_dict, model_extra, fields_set = fields_tuple
163
+ if model_extra:
164
+ fields = set(model_dict.keys())
165
+ model_dict.update(model_extra)
166
+ model_dict_new = validator(model_dict)
167
+ for k in list(model_dict_new.keys()):
168
+ if k not in fields:
169
+ model_extra[k] = model_dict_new.pop(k)
170
+ else:
171
+ model_dict_new = validator(model_dict)
172
+ return model_dict_new, model_extra, fields_set
173
+
174
+ return _wrapper2
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_discriminated_union.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations as _annotations
2
+
3
+ from collections.abc import Hashable, Sequence
4
+ from typing import TYPE_CHECKING, Any, cast
5
+
6
+ from pydantic_core import CoreSchema, core_schema
7
+
8
+ from ..errors import PydanticUserError
9
+ from . import _core_utils
10
+ from ._core_utils import (
11
+ CoreSchemaField,
12
+ )
13
+
14
+ if TYPE_CHECKING:
15
+ from ..types import Discriminator
16
+ from ._core_metadata import CoreMetadata
17
+
18
+
19
+ class MissingDefinitionForUnionRef(Exception):
20
+ """Raised when applying a discriminated union discriminator to a schema
21
+ requires a definition that is not yet defined
22
+ """
23
+
24
+ def __init__(self, ref: str) -> None:
25
+ self.ref = ref
26
+ super().__init__(f'Missing definition for ref {self.ref!r}')
27
+
28
+
29
+ def set_discriminator_in_metadata(schema: CoreSchema, discriminator: Any) -> None:
30
+ metadata = cast('CoreMetadata', schema.setdefault('metadata', {}))
31
+ metadata['pydantic_internal_union_discriminator'] = discriminator
32
+
33
+
34
+ def apply_discriminator(
35
+ schema: core_schema.CoreSchema,
36
+ discriminator: str | Discriminator,
37
+ definitions: dict[str, core_schema.CoreSchema] | None = None,
38
+ ) -> core_schema.CoreSchema:
39
+ """Applies the discriminator and returns a new core schema.
40
+
41
+ Args:
42
+ schema: The input schema.
43
+ discriminator: The name of the field which will serve as the discriminator.
44
+ definitions: A mapping of schema ref to schema.
45
+
46
+ Returns:
47
+ The new core schema.
48
+
49
+ Raises:
50
+ TypeError:
51
+ - If `discriminator` is used with invalid union variant.
52
+ - If `discriminator` is used with `Union` type with one variant.
53
+ - If `discriminator` value mapped to multiple choices.
54
+ MissingDefinitionForUnionRef:
55
+ If the definition for ref is missing.
56
+ PydanticUserError:
57
+ - If a model in union doesn't have a discriminator field.
58
+ - If discriminator field has a non-string alias.
59
+ - If discriminator fields have different aliases.
60
+ - If discriminator field not of type `Literal`.
61
+ """
62
+ from ..types import Discriminator
63
+
64
+ if isinstance(discriminator, Discriminator):
65
+ if isinstance(discriminator.discriminator, str):
66
+ discriminator = discriminator.discriminator
67
+ else:
68
+ return discriminator._convert_schema(schema)
69
+
70
+ return _ApplyInferredDiscriminator(discriminator, definitions or {}).apply(schema)
71
+
72
+
73
+ class _ApplyInferredDiscriminator:
74
+ """This class is used to convert an input schema containing a union schema into one where that union is
75
+ replaced with a tagged-union, with all the associated debugging and performance benefits.
76
+
77
+ This is done by:
78
+ * Validating that the input schema is compatible with the provided discriminator
79
+ * Introspecting the schema to determine which discriminator values should map to which union choices
80
+ * Handling various edge cases such as 'definitions', 'default', 'nullable' schemas, and more
81
+
82
+ I have chosen to implement the conversion algorithm in this class, rather than a function,
83
+ to make it easier to maintain state while recursively walking the provided CoreSchema.
84
+ """
85
+
86
+ def __init__(self, discriminator: str, definitions: dict[str, core_schema.CoreSchema]):
87
+ # `discriminator` should be the name of the field which will serve as the discriminator.
88
+ # It must be the python name of the field, and *not* the field's alias. Note that as of now,
89
+ # all members of a discriminated union _must_ use a field with the same name as the discriminator.
90
+ # This may change if/when we expose a way to manually specify the TaggedUnionSchema's choices.
91
+ self.discriminator = discriminator
92
+
93
+ # `definitions` should contain a mapping of schema ref to schema for all schemas which might
94
+ # be referenced by some choice
95
+ self.definitions = definitions
96
+
97
+ # `_discriminator_alias` will hold the value, if present, of the alias for the discriminator
98
+ #
99
+ # Note: following the v1 implementation, we currently disallow the use of different aliases
100
+ # for different choices. This is not a limitation of pydantic_core, but if we try to handle
101
+ # this, the inference logic gets complicated very quickly, and could result in confusing
102
+ # debugging challenges for users making subtle mistakes.
103
+ #
104
+ # Rather than trying to do the most powerful inference possible, I think we should eventually
105
+ # expose a way to more-manually control the way the TaggedUnionSchema is constructed through
106
+ # the use of a new type which would be placed as an Annotation on the Union type. This would
107
+ # provide the full flexibility/power of pydantic_core's TaggedUnionSchema where necessary for
108
+ # more complex cases, without over-complicating the inference logic for the common cases.
109
+ self._discriminator_alias: str | None = None
110
+
111
+ # `_should_be_nullable` indicates whether the converted union has `None` as an allowed value.
112
+ # If `None` is an acceptable value of the (possibly-wrapped) union, we ignore it while
113
+ # constructing the TaggedUnionSchema, but set the `_should_be_nullable` attribute to True.
114
+ # Once we have constructed the TaggedUnionSchema, if `_should_be_nullable` is True, we ensure
115
+ # that the final schema gets wrapped as a NullableSchema. This has the same semantics on the
116
+ # python side, but resolves the issue that `None` cannot correspond to any discriminator values.
117
+ self._should_be_nullable = False
118
+
119
+ # `_is_nullable` is used to track if the final produced schema will definitely be nullable;
120
+ # we set it to True if the input schema is wrapped in a nullable schema that we know will be preserved
121
+ # as an indication that, even if None is discovered as one of the union choices, we will not need to wrap
122
+ # the final value in another nullable schema.
123
+ #
124
+ # This is more complicated than just checking for the final outermost schema having type 'nullable' thanks
125
+ # to the possible presence of other wrapper schemas such as DefinitionsSchema, WithDefaultSchema, etc.
126
+ self._is_nullable = False
127
+
128
+ # `_choices_to_handle` serves as a stack of choices to add to the tagged union. Initially, choices
129
+ # from the union in the wrapped schema will be appended to this list, and the recursive choice-handling
130
+ # algorithm may add more choices to this stack as (nested) unions are encountered.
131
+ self._choices_to_handle: list[core_schema.CoreSchema] = []
132
+
133
+ # `_tagged_union_choices` is built during the call to `apply`, and will hold the choices to be included
134
+ # in the output TaggedUnionSchema that will replace the union from the input schema
135
+ self._tagged_union_choices: dict[Hashable, core_schema.CoreSchema] = {}
136
+
137
+ # `_used` is changed to True after applying the discriminator to prevent accidental reuse
138
+ self._used = False
139
+
140
+ def apply(self, schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
141
+ """Return a new CoreSchema based on `schema` that uses a tagged-union with the discriminator provided
142
+ to this class.
143
+
144
+ Args:
145
+ schema: The input schema.
146
+
147
+ Returns:
148
+ The new core schema.
149
+
150
+ Raises:
151
+ TypeError:
152
+ - If `discriminator` is used with invalid union variant.
153
+ - If `discriminator` is used with `Union` type with one variant.
154
+ - If `discriminator` value mapped to multiple choices.
155
+ ValueError:
156
+ If the definition for ref is missing.
157
+ PydanticUserError:
158
+ - If a model in union doesn't have a discriminator field.
159
+ - If discriminator field has a non-string alias.
160
+ - If discriminator fields have different aliases.
161
+ - If discriminator field not of type `Literal`.
162
+ """
163
+ assert not self._used
164
+ schema = self._apply_to_root(schema)
165
+ if self._should_be_nullable and not self._is_nullable:
166
+ schema = core_schema.nullable_schema(schema)
167
+ self._used = True
168
+ return schema
169
+
170
+ def _apply_to_root(self, schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
171
+ """This method handles the outer-most stage of recursion over the input schema:
172
+ unwrapping nullable or definitions schemas, and calling the `_handle_choice`
173
+ method iteratively on the choices extracted (recursively) from the possibly-wrapped union.
174
+ """
175
+ if schema['type'] == 'nullable':
176
+ self._is_nullable = True
177
+ wrapped = self._apply_to_root(schema['schema'])
178
+ nullable_wrapper = schema.copy()
179
+ nullable_wrapper['schema'] = wrapped
180
+ return nullable_wrapper
181
+
182
+ if schema['type'] == 'definitions':
183
+ wrapped = self._apply_to_root(schema['schema'])
184
+ definitions_wrapper = schema.copy()
185
+ definitions_wrapper['schema'] = wrapped
186
+ return definitions_wrapper
187
+
188
+ if schema['type'] == 'definition-ref':
189
+ schema_ref = schema['schema_ref']
190
+ if schema_ref not in self.definitions: # pragma: no cover
191
+ raise MissingDefinitionForUnionRef(schema_ref)
192
+
193
+ def_schema = self.definitions[schema_ref]
194
+ # If using a referenceable union as discriminated (e.g. `type Pet = Cat | Dog; field: Pet = Field(discriminator=...)`):
195
+ if def_schema['type'] == 'union':
196
+ schema = def_schema.copy()
197
+ schema.pop('ref')
198
+
199
+ if schema['type'] != 'union':
200
+ # If the schema is not a union, it probably means it just had a single member and
201
+ # was flattened by pydantic_core.
202
+ # However, it still may make sense to apply the discriminator to this schema,
203
+ # as a way to get discriminated-union-style error messages, so we allow this here.
204
+ schema = core_schema.union_schema([schema])
205
+
206
+ # Reverse the choices list before extending the stack so that they get handled in the order they occur
207
+ choices_schemas = [v[0] if isinstance(v, tuple) else v for v in schema['choices'][::-1]]
208
+ self._choices_to_handle.extend(choices_schemas)
209
+ while self._choices_to_handle:
210
+ choice = self._choices_to_handle.pop()
211
+ self._handle_choice(choice)
212
+
213
+ if self._discriminator_alias is not None and self._discriminator_alias != self.discriminator:
214
+ # * We need to annotate `discriminator` as a union here to handle both branches of this conditional
215
+ # * We need to annotate `discriminator` as list[list[str | int]] and not list[list[str]] due to the
216
+ # invariance of list, and because list[list[str | int]] is the type of the discriminator argument
217
+ # to tagged_union_schema below
218
+ # * See the docstring of pydantic_core.core_schema.tagged_union_schema for more details about how to
219
+ # interpret the value of the discriminator argument to tagged_union_schema. (The list[list[str]] here
220
+ # is the appropriate way to provide a list of fallback attributes to check for a discriminator value.)
221
+ discriminator: str | list[list[str | int]] = [[self.discriminator], [self._discriminator_alias]]
222
+ else:
223
+ discriminator = self.discriminator
224
+ return core_schema.tagged_union_schema(
225
+ choices=self._tagged_union_choices,
226
+ discriminator=discriminator,
227
+ custom_error_type=schema.get('custom_error_type'),
228
+ custom_error_message=schema.get('custom_error_message'),
229
+ custom_error_context=schema.get('custom_error_context'),
230
+ strict=False,
231
+ from_attributes=True,
232
+ ref=schema.get('ref'),
233
+ metadata=schema.get('metadata'),
234
+ serialization=schema.get('serialization'),
235
+ )
236
+
237
+ def _handle_choice(self, choice: core_schema.CoreSchema) -> None:
238
+ """This method handles the "middle" stage of recursion over the input schema.
239
+ Specifically, it is responsible for handling each choice of the outermost union
240
+ (and any "coalesced" choices obtained from inner unions).
241
+
242
+ Here, "handling" entails:
243
+ * Coalescing nested unions and compatible tagged-unions
244
+ * Tracking the presence of 'none' and 'nullable' schemas occurring as choices
245
+ * Validating that each allowed discriminator value maps to a unique choice
246
+ * Updating the _tagged_union_choices mapping that will ultimately be used to build the TaggedUnionSchema.
247
+ """
248
+ if choice['type'] == 'definition-ref':
249
+ if choice['schema_ref'] not in self.definitions:
250
+ raise MissingDefinitionForUnionRef(choice['schema_ref'])
251
+
252
+ if choice['type'] == 'none':
253
+ self._should_be_nullable = True
254
+ elif choice['type'] == 'definitions':
255
+ self._handle_choice(choice['schema'])
256
+ elif choice['type'] == 'nullable':
257
+ self._should_be_nullable = True
258
+ self._handle_choice(choice['schema']) # unwrap the nullable schema
259
+ elif choice['type'] == 'union':
260
+ # Reverse the choices list before extending the stack so that they get handled in the order they occur
261
+ choices_schemas = [v[0] if isinstance(v, tuple) else v for v in choice['choices'][::-1]]
262
+ self._choices_to_handle.extend(choices_schemas)
263
+ elif choice['type'] not in {
264
+ 'model',
265
+ 'typed-dict',
266
+ 'tagged-union',
267
+ 'lax-or-strict',
268
+ 'dataclass',
269
+ 'dataclass-args',
270
+ 'definition-ref',
271
+ } and not _core_utils.is_function_with_inner_schema(choice):
272
+ # We should eventually handle 'definition-ref' as well
273
+ err_str = f'The core schema type {choice["type"]!r} is not a valid discriminated union variant.'
274
+ if choice['type'] == 'list':
275
+ err_str += (
276
+ ' If you are making use of a list of union types, make sure the discriminator is applied to the '
277
+ 'union type and not the list (e.g. `list[Annotated[<T> | <U>, Field(discriminator=...)]]`).'
278
+ )
279
+ raise TypeError(err_str)
280
+ else:
281
+ if choice['type'] == 'tagged-union' and self._is_discriminator_shared(choice):
282
+ # In this case, this inner tagged-union is compatible with the outer tagged-union,
283
+ # and its choices can be coalesced into the outer TaggedUnionSchema.
284
+ subchoices = [x for x in choice['choices'].values() if not isinstance(x, (str, int))]
285
+ # Reverse the choices list before extending the stack so that they get handled in the order they occur
286
+ self._choices_to_handle.extend(subchoices[::-1])
287
+ return
288
+
289
+ inferred_discriminator_values = self._infer_discriminator_values_for_choice(choice, source_name=None)
290
+ self._set_unique_choice_for_values(choice, inferred_discriminator_values)
291
+
292
+ def _is_discriminator_shared(self, choice: core_schema.TaggedUnionSchema) -> bool:
293
+ """This method returns a boolean indicating whether the discriminator for the `choice`
294
+ is the same as that being used for the outermost tagged union. This is used to
295
+ determine whether this TaggedUnionSchema choice should be "coalesced" into the top level,
296
+ or whether it should be treated as a separate (nested) choice.
297
+ """
298
+ inner_discriminator = choice['discriminator']
299
+ return inner_discriminator == self.discriminator or (
300
+ isinstance(inner_discriminator, list)
301
+ and (self.discriminator in inner_discriminator or [self.discriminator] in inner_discriminator)
302
+ )
303
+
304
+ def _infer_discriminator_values_for_choice( # noqa C901
305
+ self, choice: core_schema.CoreSchema, source_name: str | None
306
+ ) -> list[str | int]:
307
+ """This function recurses over `choice`, extracting all discriminator values that should map to this choice.
308
+
309
+ `model_name` is accepted for the purpose of producing useful error messages.
310
+ """
311
+ if choice['type'] == 'definitions':
312
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=source_name)
313
+
314
+ elif _core_utils.is_function_with_inner_schema(choice):
315
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=source_name)
316
+
317
+ elif choice['type'] == 'lax-or-strict':
318
+ return sorted(
319
+ set(
320
+ self._infer_discriminator_values_for_choice(choice['lax_schema'], source_name=None)
321
+ + self._infer_discriminator_values_for_choice(choice['strict_schema'], source_name=None)
322
+ )
323
+ )
324
+
325
+ elif choice['type'] == 'tagged-union':
326
+ values: list[str | int] = []
327
+ # Ignore str/int "choices" since these are just references to other choices
328
+ subchoices = [x for x in choice['choices'].values() if not isinstance(x, (str, int))]
329
+ for subchoice in subchoices:
330
+ subchoice_values = self._infer_discriminator_values_for_choice(subchoice, source_name=None)
331
+ values.extend(subchoice_values)
332
+ return values
333
+
334
+ elif choice['type'] == 'union':
335
+ values = []
336
+ for subchoice in choice['choices']:
337
+ subchoice_schema = subchoice[0] if isinstance(subchoice, tuple) else subchoice
338
+ subchoice_values = self._infer_discriminator_values_for_choice(subchoice_schema, source_name=None)
339
+ values.extend(subchoice_values)
340
+ return values
341
+
342
+ elif choice['type'] == 'nullable':
343
+ self._should_be_nullable = True
344
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=None)
345
+
346
+ elif choice['type'] == 'model':
347
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=choice['cls'].__name__)
348
+
349
+ elif choice['type'] == 'dataclass':
350
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=choice['cls'].__name__)
351
+
352
+ elif choice['type'] == 'model-fields':
353
+ return self._infer_discriminator_values_for_model_choice(choice, source_name=source_name)
354
+
355
+ elif choice['type'] == 'dataclass-args':
356
+ return self._infer_discriminator_values_for_dataclass_choice(choice, source_name=source_name)
357
+
358
+ elif choice['type'] == 'typed-dict':
359
+ return self._infer_discriminator_values_for_typed_dict_choice(choice, source_name=source_name)
360
+
361
+ elif choice['type'] == 'definition-ref':
362
+ schema_ref = choice['schema_ref']
363
+ if schema_ref not in self.definitions:
364
+ raise MissingDefinitionForUnionRef(schema_ref)
365
+ return self._infer_discriminator_values_for_choice(self.definitions[schema_ref], source_name=source_name)
366
+ else:
367
+ err_str = f'The core schema type {choice["type"]!r} is not a valid discriminated union variant.'
368
+ if choice['type'] == 'list':
369
+ err_str += (
370
+ ' If you are making use of a list of union types, make sure the discriminator is applied to the '
371
+ 'union type and not the list (e.g. `list[Annotated[<T> | <U>, Field(discriminator=...)]]`).'
372
+ )
373
+ raise TypeError(err_str)
374
+
375
+ def _infer_discriminator_values_for_typed_dict_choice(
376
+ self, choice: core_schema.TypedDictSchema, source_name: str | None = None
377
+ ) -> list[str | int]:
378
+ """This method just extracts the _infer_discriminator_values_for_choice logic specific to TypedDictSchema
379
+ for the sake of readability.
380
+ """
381
+ source = 'TypedDict' if source_name is None else f'TypedDict {source_name!r}'
382
+ field = choice['fields'].get(self.discriminator)
383
+ if field is None:
384
+ raise PydanticUserError(
385
+ f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field'
386
+ )
387
+ return self._infer_discriminator_values_for_field(field, source)
388
+
389
+ def _infer_discriminator_values_for_model_choice(
390
+ self, choice: core_schema.ModelFieldsSchema, source_name: str | None = None
391
+ ) -> list[str | int]:
392
+ source = 'ModelFields' if source_name is None else f'Model {source_name!r}'
393
+ field = choice['fields'].get(self.discriminator)
394
+ if field is None:
395
+ raise PydanticUserError(
396
+ f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field'
397
+ )
398
+ return self._infer_discriminator_values_for_field(field, source)
399
+
400
+ def _infer_discriminator_values_for_dataclass_choice(
401
+ self, choice: core_schema.DataclassArgsSchema, source_name: str | None = None
402
+ ) -> list[str | int]:
403
+ source = 'DataclassArgs' if source_name is None else f'Dataclass {source_name!r}'
404
+ for field in choice['fields']:
405
+ if field['name'] == self.discriminator:
406
+ break
407
+ else:
408
+ raise PydanticUserError(
409
+ f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field'
410
+ )
411
+ return self._infer_discriminator_values_for_field(field, source)
412
+
413
+ def _infer_discriminator_values_for_field(self, field: CoreSchemaField, source: str) -> list[str | int]:
414
+ if field['type'] == 'computed-field':
415
+ # This should never occur as a discriminator, as it is only relevant to serialization
416
+ return []
417
+ alias = field.get('validation_alias', self.discriminator)
418
+ if not isinstance(alias, str):
419
+ raise PydanticUserError(
420
+ f'Alias {alias!r} is not supported in a discriminated union', code='discriminator-alias-type'
421
+ )
422
+ if self._discriminator_alias is None:
423
+ self._discriminator_alias = alias
424
+ elif self._discriminator_alias != alias:
425
+ raise PydanticUserError(
426
+ f'Aliases for discriminator {self.discriminator!r} must be the same '
427
+ f'(got {alias}, {self._discriminator_alias})',
428
+ code='discriminator-alias',
429
+ )
430
+ return self._infer_discriminator_values_for_inner_schema(field['schema'], source)
431
+
432
+ def _infer_discriminator_values_for_inner_schema(
433
+ self, schema: core_schema.CoreSchema, source: str
434
+ ) -> list[str | int]:
435
+ """When inferring discriminator values for a field, we typically extract the expected values from a literal
436
+ schema. This function does that, but also handles nested unions and defaults.
437
+ """
438
+ if schema['type'] == 'literal':
439
+ return schema['expected']
440
+
441
+ elif schema['type'] == 'union':
442
+ # Generally when multiple values are allowed they should be placed in a single `Literal`, but
443
+ # we add this case to handle the situation where a field is annotated as a `Union` of `Literal`s.
444
+ # For example, this lets us handle `Union[Literal['key'], Union[Literal['Key'], Literal['KEY']]]`
445
+ values: list[Any] = []
446
+ for choice in schema['choices']:
447
+ choice_schema = choice[0] if isinstance(choice, tuple) else choice
448
+ choice_values = self._infer_discriminator_values_for_inner_schema(choice_schema, source)
449
+ values.extend(choice_values)
450
+ return values
451
+
452
+ elif schema['type'] == 'default':
453
+ # This will happen if the field has a default value; we ignore it while extracting the discriminator values
454
+ return self._infer_discriminator_values_for_inner_schema(schema['schema'], source)
455
+
456
+ elif schema['type'] == 'function-after':
457
+ # After validators don't affect the discriminator values
458
+ return self._infer_discriminator_values_for_inner_schema(schema['schema'], source)
459
+
460
+ elif schema['type'] == 'model' and schema.get('root_model'):
461
+ # Support RootModel[Literal[...]] as discriminator field type
462
+ return self._infer_discriminator_values_for_inner_schema(schema['schema'], source)
463
+
464
+ elif schema['type'] in {'function-before', 'function-wrap', 'function-plain'}:
465
+ validator_type = repr(schema['type'].split('-')[1])
466
+ raise PydanticUserError(
467
+ f'Cannot use a mode={validator_type} validator in the'
468
+ f' discriminator field {self.discriminator!r} of {source}',
469
+ code='discriminator-validator',
470
+ )
471
+
472
+ else:
473
+ raise PydanticUserError(
474
+ f'{source} needs field {self.discriminator!r} to be of type `Literal`',
475
+ code='discriminator-needs-literal',
476
+ )
477
+
478
+ def _set_unique_choice_for_values(self, choice: core_schema.CoreSchema, values: Sequence[str | int]) -> None:
479
+ """This method updates `self.tagged_union_choices` so that all provided (discriminator) `values` map to the
480
+ provided `choice`, validating that none of these values already map to another (different) choice.
481
+ """
482
+ for discriminator_value in values:
483
+ if discriminator_value in self._tagged_union_choices:
484
+ # It is okay if `value` is already in tagged_union_choices as long as it maps to the same value.
485
+ # Because tagged_union_choices may map values to other values, we need to walk the choices dict
486
+ # until we get to a "real" choice, and confirm that is equal to the one assigned.
487
+ existing_choice = self._tagged_union_choices[discriminator_value]
488
+ if existing_choice != choice:
489
+ raise TypeError(
490
+ f'Value {discriminator_value!r} for discriminator '
491
+ f'{self.discriminator!r} mapped to multiple choices'
492
+ )
493
+ else:
494
+ self._tagged_union_choices[discriminator_value] = choice
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_docs_extraction.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities related to attribute docstring extraction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import inspect
7
+ import sys
8
+ import textwrap
9
+ from typing import Any
10
+
11
+
12
+ class DocstringVisitor(ast.NodeVisitor):
13
+ def __init__(self) -> None:
14
+ super().__init__()
15
+
16
+ self.target: str | None = None
17
+ self.attrs: dict[str, str] = {}
18
+ self.previous_node_type: type[ast.AST] | None = None
19
+
20
+ def visit(self, node: ast.AST) -> Any:
21
+ node_result = super().visit(node)
22
+ self.previous_node_type = type(node)
23
+ return node_result
24
+
25
+ def visit_AnnAssign(self, node: ast.AnnAssign) -> Any:
26
+ if isinstance(node.target, ast.Name):
27
+ self.target = node.target.id
28
+
29
+ def visit_Expr(self, node: ast.Expr) -> Any:
30
+ if (
31
+ isinstance(node.value, ast.Constant)
32
+ and isinstance(node.value.value, str)
33
+ and self.previous_node_type is ast.AnnAssign
34
+ ):
35
+ docstring = inspect.cleandoc(node.value.value)
36
+ if self.target:
37
+ self.attrs[self.target] = docstring
38
+ self.target = None
39
+
40
+
41
+ def _dedent_source_lines(source: list[str]) -> str:
42
+ # Required for nested class definitions, e.g. in a function block
43
+ dedent_source = textwrap.dedent(''.join(source))
44
+ if dedent_source.startswith((' ', '\t')):
45
+ # We are in the case where there's a dedented (usually multiline) string
46
+ # at a lower indentation level than the class itself. We wrap our class
47
+ # in a function as a workaround.
48
+ dedent_source = f'def dedent_workaround():\n{dedent_source}'
49
+ return dedent_source
50
+
51
+
52
+ def _extract_source_from_frame(cls: type[Any]) -> list[str] | None:
53
+ frame = inspect.currentframe()
54
+
55
+ while frame:
56
+ if inspect.getmodule(frame) is inspect.getmodule(cls):
57
+ lnum = frame.f_lineno
58
+ try:
59
+ lines, _ = inspect.findsource(frame)
60
+ except OSError: # pragma: no cover
61
+ # Source can't be retrieved (maybe because running in an interactive terminal),
62
+ # we don't want to error here.
63
+ pass
64
+ else:
65
+ block_lines = inspect.getblock(lines[lnum - 1 :])
66
+ dedent_source = _dedent_source_lines(block_lines)
67
+ try:
68
+ block_tree = ast.parse(dedent_source)
69
+ except SyntaxError:
70
+ pass
71
+ else:
72
+ stmt = block_tree.body[0]
73
+ if isinstance(stmt, ast.FunctionDef) and stmt.name == 'dedent_workaround':
74
+ # `_dedent_source_lines` wrapped the class around the workaround function
75
+ stmt = stmt.body[0]
76
+ if isinstance(stmt, ast.ClassDef) and stmt.name == cls.__name__:
77
+ return block_lines
78
+
79
+ frame = frame.f_back
80
+
81
+
82
+ def extract_docstrings_from_cls(cls: type[Any], use_inspect: bool = False) -> dict[str, str]:
83
+ """Map model attributes and their corresponding docstring.
84
+
85
+ Args:
86
+ cls: The class of the Pydantic model to inspect.
87
+ use_inspect: Whether to skip usage of frames to find the object and use
88
+ the `inspect` module instead.
89
+
90
+ Returns:
91
+ A mapping containing attribute names and their corresponding docstring.
92
+ """
93
+ if use_inspect or sys.version_info >= (3, 13):
94
+ # On Python < 3.13, `inspect.getsourcelines()` might not work as expected
95
+ # if two classes have the same name in the same source file.
96
+ # On Python 3.13+, it will use the new `__firstlineno__` class attribute,
97
+ # making it way more robust.
98
+ try:
99
+ source, _ = inspect.getsourcelines(cls)
100
+ except OSError: # pragma: no cover
101
+ return {}
102
+ else:
103
+ # TODO remove this implementation when we drop support for Python 3.12:
104
+ source = _extract_source_from_frame(cls)
105
+
106
+ if not source:
107
+ return {}
108
+
109
+ dedent_source = _dedent_source_lines(source)
110
+
111
+ visitor = DocstringVisitor()
112
+ visitor.visit(ast.parse(dedent_source))
113
+ return visitor.attrs
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_fields.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private logic related to fields (the `Field()` function and `FieldInfo` class), and arguments to `Annotated`."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ import dataclasses
6
+ import warnings
7
+ from collections.abc import Mapping
8
+ from functools import cache
9
+ from inspect import Parameter, ismethoddescriptor
10
+ from re import Pattern
11
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
12
+
13
+ from pydantic_core import PydanticUndefined
14
+ from typing_extensions import TypeIs
15
+ from typing_inspection.introspection import AnnotationSource
16
+
17
+ from pydantic import PydanticDeprecatedSince211
18
+ from pydantic.errors import PydanticUserError
19
+
20
+ from ..aliases import AliasGenerator
21
+ from . import _generics, _typing_extra
22
+ from ._config import ConfigWrapper
23
+ from ._docs_extraction import extract_docstrings_from_cls
24
+ from ._import_utils import import_cached_base_model, import_cached_field_info
25
+ from ._internal_dataclass import slots_true
26
+ from ._namespace_utils import NsResolver
27
+ from ._repr import Representation
28
+ from ._utils import can_be_positional, get_first_not_none
29
+
30
+ if TYPE_CHECKING:
31
+ from annotated_types import BaseMetadata
32
+
33
+ from ..fields import FieldInfo
34
+ from ..main import BaseModel
35
+ from ._dataclasses import PydanticDataclass, StandardDataclass
36
+ from ._decorators import DecoratorInfos
37
+
38
+
39
+ class PydanticMetadata(Representation):
40
+ """Base class for annotation markers like `Strict`."""
41
+
42
+ __slots__ = ()
43
+
44
+
45
+ @dataclasses.dataclass(**slots_true) # TODO: make kw_only when we drop support for 3.9.
46
+ class PydanticExtraInfo:
47
+ # TODO: make use of PEP 747:
48
+ annotation: Any
49
+ complete: bool
50
+
51
+
52
+ def pydantic_general_metadata(**metadata: Any) -> BaseMetadata:
53
+ """Create a new `_PydanticGeneralMetadata` class with the given metadata.
54
+
55
+ Args:
56
+ **metadata: The metadata to add.
57
+
58
+ Returns:
59
+ The new `_PydanticGeneralMetadata` class.
60
+ """
61
+ return _general_metadata_cls()(metadata) # type: ignore
62
+
63
+
64
+ @cache
65
+ def _general_metadata_cls() -> type[BaseMetadata]:
66
+ """Do it this way to avoid importing `annotated_types` at import time."""
67
+ from annotated_types import BaseMetadata
68
+
69
+ class _PydanticGeneralMetadata(PydanticMetadata, BaseMetadata):
70
+ """Pydantic general metadata like `max_digits`."""
71
+
72
+ def __init__(self, metadata: Any):
73
+ self.__dict__ = metadata
74
+
75
+ return _PydanticGeneralMetadata # type: ignore
76
+
77
+
78
+ def _check_protected_namespaces(
79
+ protected_namespaces: tuple[str | Pattern[str], ...],
80
+ ann_name: str,
81
+ bases: tuple[type[Any], ...],
82
+ cls_name: str,
83
+ ) -> None:
84
+ BaseModel = import_cached_base_model()
85
+
86
+ for protected_namespace in protected_namespaces:
87
+ ns_violation = False
88
+ if isinstance(protected_namespace, Pattern):
89
+ ns_violation = protected_namespace.match(ann_name) is not None
90
+ elif isinstance(protected_namespace, str):
91
+ ns_violation = ann_name.startswith(protected_namespace)
92
+
93
+ if ns_violation:
94
+ for b in bases:
95
+ if hasattr(b, ann_name):
96
+ if not (issubclass(b, BaseModel) and ann_name in getattr(b, '__pydantic_fields__', {})):
97
+ raise ValueError(
98
+ f'Field {ann_name!r} conflicts with member {getattr(b, ann_name)}'
99
+ f' of protected namespace {protected_namespace!r}.'
100
+ )
101
+ else:
102
+ valid_namespaces: list[str] = []
103
+ for pn in protected_namespaces:
104
+ if isinstance(pn, Pattern):
105
+ if not pn.match(ann_name):
106
+ valid_namespaces.append(f're.compile({pn.pattern!r})')
107
+ else:
108
+ if not ann_name.startswith(pn):
109
+ valid_namespaces.append(f"'{pn}'")
110
+
111
+ valid_namespaces_str = f'({", ".join(valid_namespaces)}{",)" if len(valid_namespaces) == 1 else ")"}'
112
+
113
+ warnings.warn(
114
+ f'Field {ann_name!r} in {cls_name!r} conflicts with protected namespace {protected_namespace!r}.\n\n'
115
+ f"You may be able to solve this by setting the 'protected_namespaces' configuration to {valid_namespaces_str}.",
116
+ UserWarning,
117
+ stacklevel=5,
118
+ )
119
+
120
+
121
+ def _update_fields_from_docstrings(cls: type[Any], fields: dict[str, FieldInfo], use_inspect: bool = False) -> None:
122
+ fields_docs = extract_docstrings_from_cls(cls, use_inspect=use_inspect)
123
+ for ann_name, field_info in fields.items():
124
+ if field_info.description is None and ann_name in fields_docs:
125
+ field_info.description = fields_docs[ann_name]
126
+
127
+
128
+ def _apply_field_title_generator_to_field_info(
129
+ title_generator: Callable[[str, FieldInfo], str],
130
+ field_name: str,
131
+ field_info: FieldInfo,
132
+ ):
133
+ if field_info.title is None:
134
+ title = title_generator(field_name, field_info)
135
+ if not isinstance(title, str):
136
+ raise TypeError(f'field_title_generator {title_generator} must return str, not {title.__class__}')
137
+
138
+ field_info.title = title
139
+
140
+
141
+ def _apply_alias_generator_to_field_info(
142
+ alias_generator: Callable[[str], str] | AliasGenerator, field_name: str, field_info: FieldInfo
143
+ ):
144
+ """Apply an alias generator to aliases on a `FieldInfo` instance if appropriate.
145
+
146
+ Args:
147
+ alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
148
+ field_name: The name of the field from which to generate the alias.
149
+ field_info: The `FieldInfo` instance to which the alias generator is (maybe) applied.
150
+ """
151
+ # Apply an alias_generator if
152
+ # 1. An alias is not specified
153
+ # 2. An alias is specified, but the priority is <= 1
154
+ if (
155
+ field_info.alias_priority is None
156
+ or field_info.alias_priority <= 1
157
+ or field_info.alias is None
158
+ or field_info.validation_alias is None
159
+ or field_info.serialization_alias is None
160
+ ):
161
+ alias, validation_alias, serialization_alias = None, None, None
162
+
163
+ if isinstance(alias_generator, AliasGenerator):
164
+ alias, validation_alias, serialization_alias = alias_generator.generate_aliases(field_name)
165
+ elif callable(alias_generator):
166
+ alias = alias_generator(field_name)
167
+ if not isinstance(alias, str):
168
+ raise TypeError(f'alias_generator {alias_generator} must return str, not {alias.__class__}')
169
+
170
+ # if priority is not set, we set to 1
171
+ # which supports the case where the alias_generator from a child class is used
172
+ # to generate an alias for a field in a parent class
173
+ if field_info.alias_priority is None or field_info.alias_priority <= 1:
174
+ field_info.alias_priority = 1
175
+
176
+ # if the priority is 1, then we set the aliases to the generated alias
177
+ if field_info.alias_priority == 1:
178
+ field_info.serialization_alias = get_first_not_none(serialization_alias, alias)
179
+ field_info.validation_alias = get_first_not_none(validation_alias, alias)
180
+ field_info.alias = alias
181
+
182
+ # if any of the aliases are not set, then we set them to the corresponding generated alias
183
+ if field_info.alias is None:
184
+ field_info.alias = alias
185
+ if field_info.serialization_alias is None:
186
+ field_info.serialization_alias = get_first_not_none(serialization_alias, alias)
187
+ if field_info.validation_alias is None:
188
+ field_info.validation_alias = get_first_not_none(validation_alias, alias)
189
+
190
+
191
+ def update_field_from_config(config_wrapper: ConfigWrapper, field_name: str, field_info: FieldInfo) -> None:
192
+ """Update the `FieldInfo` instance from the configuration set on the model it belongs to.
193
+
194
+ This will apply the title and alias generators from the configuration.
195
+
196
+ Args:
197
+ config_wrapper: The configuration from the model.
198
+ field_name: The field name the `FieldInfo` instance is attached to.
199
+ field_info: The `FieldInfo` instance to update.
200
+ """
201
+ field_title_generator = field_info.field_title_generator or config_wrapper.field_title_generator
202
+ if field_title_generator is not None:
203
+ _apply_field_title_generator_to_field_info(field_title_generator, field_name, field_info)
204
+ if config_wrapper.alias_generator is not None:
205
+ _apply_alias_generator_to_field_info(config_wrapper.alias_generator, field_name, field_info)
206
+
207
+
208
+ _deprecated_method_names = {'dict', 'json', 'copy', '_iter', '_copy_and_set_values', '_calculate_keys'}
209
+
210
+ _deprecated_classmethod_names = {
211
+ 'parse_obj',
212
+ 'parse_raw',
213
+ 'parse_file',
214
+ 'from_orm',
215
+ 'construct',
216
+ 'schema',
217
+ 'schema_json',
218
+ 'validate',
219
+ 'update_forward_refs',
220
+ '_get_value',
221
+ }
222
+
223
+
224
+ def collect_model_fields( # noqa: C901
225
+ cls: type[BaseModel],
226
+ config_wrapper: ConfigWrapper,
227
+ ns_resolver: NsResolver,
228
+ *,
229
+ typevars_map: Mapping[TypeVar, Any] | None = None,
230
+ ) -> tuple[dict[str, FieldInfo], PydanticExtraInfo | None, set[str]]:
231
+ """Collect the fields and class variables names of a nascent Pydantic model.
232
+
233
+ The fields collection process is *lenient*, meaning it won't error if string annotations
234
+ fail to evaluate. If this happens, the original annotation (and assigned value, if any)
235
+ is stored on the created `FieldInfo` instance.
236
+
237
+ The `rebuild_model_fields()` should be called at a later point (e.g. when rebuilding the model),
238
+ and will make use of these stored attributes.
239
+
240
+ Args:
241
+ cls: BaseModel or dataclass.
242
+ config_wrapper: The config wrapper instance.
243
+ ns_resolver: Namespace resolver to use when getting model annotations.
244
+ typevars_map: A dictionary mapping type variables to their concrete types.
245
+
246
+ Returns:
247
+ A three-tuple containing the model fields, the `PydanticExtraInfo` instance if the `__pydantic_extra__` annotation is set,
248
+ and class variables names.
249
+
250
+ Raises:
251
+ NameError:
252
+ - If there is a conflict between a field name and protected namespaces.
253
+ - If there is a field other than `root` in `RootModel`.
254
+ - If a field shadows an attribute in the parent model.
255
+ """
256
+ FieldInfo_ = import_cached_field_info()
257
+ BaseModel_ = import_cached_base_model()
258
+
259
+ bases = cls.__bases__
260
+ parent_fields_lookup: dict[str, FieldInfo] = {}
261
+ for base in reversed(bases):
262
+ if model_fields := getattr(base, '__pydantic_fields__', None):
263
+ parent_fields_lookup.update(model_fields)
264
+
265
+ type_hints = _typing_extra.get_model_type_hints(cls, ns_resolver=ns_resolver)
266
+
267
+ # `cls_annotations` is only used to determine if an annotation comes from a parent class
268
+ cls_annotations = _typing_extra.safe_get_annotations(cls)
269
+
270
+ fields: dict[str, FieldInfo] = {}
271
+
272
+ class_vars: set[str] = set()
273
+ for ann_name, (ann_type, evaluated) in type_hints.items():
274
+ if ann_name == 'model_config':
275
+ # We never want to treat `model_config` as a field
276
+ # Note: we may need to change this logic if/when we introduce a `BareModel` class with no
277
+ # protected namespaces (where `model_config` might be allowed as a field name)
278
+ continue
279
+
280
+ _check_protected_namespaces(
281
+ protected_namespaces=config_wrapper.protected_namespaces,
282
+ ann_name=ann_name,
283
+ bases=bases,
284
+ cls_name=cls.__name__,
285
+ )
286
+
287
+ if _typing_extra.is_classvar_annotation(ann_type):
288
+ class_vars.add(ann_name)
289
+ continue
290
+
291
+ assigned_value = getattr(cls, ann_name, PydanticUndefined)
292
+ if assigned_value is not PydanticUndefined and (
293
+ # One of the deprecated instance methods was used as a field name (e.g. `dict()`):
294
+ any(getattr(BaseModel_, depr_name, None) is assigned_value for depr_name in _deprecated_method_names)
295
+ # One of the deprecated class methods was used as a field name (e.g. `schema()`):
296
+ or (
297
+ hasattr(assigned_value, '__func__')
298
+ and any(
299
+ getattr(getattr(BaseModel_, depr_name, None), '__func__', None) is assigned_value.__func__ # pyright: ignore[reportAttributeAccessIssue]
300
+ for depr_name in _deprecated_classmethod_names
301
+ )
302
+ )
303
+ ):
304
+ # Then `assigned_value` would be the method, even though no default was specified:
305
+ assigned_value = PydanticUndefined
306
+
307
+ if not is_valid_field_name(ann_name):
308
+ continue
309
+ if cls.__pydantic_root_model__ and ann_name != 'root':
310
+ raise NameError(
311
+ f"Unexpected field with name {ann_name!r}; only 'root' is allowed as a field of a `RootModel`"
312
+ )
313
+
314
+ for base in bases:
315
+ if hasattr(base, ann_name):
316
+ if ann_name not in cls_annotations:
317
+ # Don't warn when a field exists in a parent class but has not been defined in the current class
318
+ continue
319
+
320
+ # when building a generic model with `MyModel[int]`, the generic_origin check makes sure we don't get
321
+ # "... shadows an attribute" warnings
322
+ generic_origin = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin')
323
+ if base is generic_origin:
324
+ # Don't warn when "shadowing" of attributes in parametrized generics
325
+ continue
326
+
327
+ dataclass_fields = {
328
+ field.name for field in (dataclasses.fields(base) if dataclasses.is_dataclass(base) else ())
329
+ }
330
+ if ann_name in dataclass_fields:
331
+ # Don't warn when inheriting stdlib dataclasses whose fields are "shadowed" by defaults being set
332
+ # on the class instance.
333
+ continue
334
+
335
+ warnings.warn(
336
+ f'Field name "{ann_name}" in "{cls.__qualname__}" shadows an attribute in parent '
337
+ f'"{base.__qualname__}"',
338
+ UserWarning,
339
+ stacklevel=4,
340
+ )
341
+
342
+ if assigned_value is PydanticUndefined: # no assignment, just a plain annotation
343
+ if ann_name in cls_annotations or ann_name not in parent_fields_lookup:
344
+ # field is either:
345
+ # - present in the current model's annotations (and *not* from parent classes)
346
+ # - not found on any base classes; this seems to be caused by fields not getting
347
+ # generated due to models not being fully defined while initializing recursive models.
348
+ # Nothing stops us from just creating a `FieldInfo` for this type hint, so we do this.
349
+ field_info = FieldInfo_.from_annotation(ann_type, _source=AnnotationSource.CLASS)
350
+ field_info._original_annotation = ann_type
351
+ if not evaluated:
352
+ field_info._complete = False
353
+ # Store the original annotation that should be used to rebuild
354
+ # the field info later:
355
+ else:
356
+ # The field was present on one of the (possibly multiple) base classes, we make a copy directly from it.
357
+ parent_field_info = parent_fields_lookup[ann_name]._copy()
358
+
359
+ # The only case where substituting the type variables is relevant (i.e. when `typevars_map` is not empty)
360
+ # is when a generic class is parameterized (e.g. `MyGenericModel[int, str]`), which creates a new class object
361
+ # (unlike the stdlib genercis that create a generic alias). In this case, we are guaranteed to only have to copy
362
+ # from the origin/parent model (e.g. `MyGenericModel`).
363
+ if typevars_map:
364
+ field_info = _recreate_field_info(
365
+ parent_field_info, ns_resolver=ns_resolver, typevars_map=typevars_map, lenient=True
366
+ )
367
+ else:
368
+ field_info = parent_field_info
369
+
370
+ else: # An assigned value is present (either the default value, or a `Field()` function)
371
+ if isinstance(assigned_value, FieldInfo_) and ismethoddescriptor(assigned_value.default):
372
+ # `assigned_value` was fetched using `getattr`, which triggers a call to `__get__`
373
+ # for descriptors, so we do the same if the `= field(default=...)` form is used.
374
+ # Note that we only do this for method descriptors for now, we might want to
375
+ # extend this to any descriptor in the future (by simply checking for
376
+ # `hasattr(assigned_value.default, '__get__')`).
377
+ default = assigned_value.default.__get__(None, cls)
378
+ assigned_value.default = default
379
+ assigned_value._attributes_set['default'] = default
380
+
381
+ field_info = FieldInfo_.from_annotated_attribute(ann_type, assigned_value, _source=AnnotationSource.CLASS)
382
+
383
+ # Store the original annotation and assignment value that could be used to rebuild the field info later.
384
+ field_info._original_assignment = assigned_value
385
+ field_info._original_annotation = ann_type
386
+ if not evaluated:
387
+ field_info._complete = False
388
+ elif 'final' in field_info._qualifiers and not field_info.is_required():
389
+ warnings.warn(
390
+ f'Annotation {ann_name!r} is marked as final and has a default value. Pydantic treats {ann_name!r} as a '
391
+ 'class variable, but it will be considered as a normal field in V3 to be aligned with dataclasses. If you '
392
+ f'still want {ann_name!r} to be considered as a class variable, annotate it as: `ClassVar[<type>] = <default>.`',
393
+ category=PydanticDeprecatedSince211,
394
+ # Incorrect when `create_model` is used, but the chance that final with a default is used is low in that case:
395
+ stacklevel=4,
396
+ )
397
+ class_vars.add(ann_name)
398
+ continue
399
+
400
+ # attributes which are fields are removed from the class namespace:
401
+ # 1. To match the behaviour of annotation-only fields
402
+ # 2. To avoid false positives in the NameError check above
403
+ try:
404
+ delattr(cls, ann_name)
405
+ except AttributeError:
406
+ pass # indicates the attribute was on a parent class
407
+
408
+ # Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__
409
+ # to make sure the decorators have already been built for this exact class
410
+ decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__']
411
+ if ann_name in decorators.computed_fields:
412
+ raise TypeError(
413
+ f'Field {ann_name!r} of class {cls.__name__!r} overrides symbol of same name in a parent class. '
414
+ 'This override with a computed_field is incompatible.'
415
+ )
416
+ fields[ann_name] = field_info
417
+
418
+ if field_info._complete:
419
+ # If not complete, this will be called in `rebuild_model_fields()`:
420
+ update_field_from_config(config_wrapper, ann_name, field_info)
421
+
422
+ if config_wrapper.use_attribute_docstrings:
423
+ _update_fields_from_docstrings(cls, fields)
424
+
425
+ pydantic_extra_info: PydanticExtraInfo | None = None
426
+ if '__pydantic_extra__' in type_hints:
427
+ ann, complete = type_hints['__pydantic_extra__']
428
+ pydantic_extra_info = PydanticExtraInfo(
429
+ annotation=ann,
430
+ complete=complete,
431
+ )
432
+
433
+ return fields, pydantic_extra_info, class_vars
434
+
435
+
436
+ def rebuild_model_fields(
437
+ cls: type[BaseModel],
438
+ *,
439
+ config_wrapper: ConfigWrapper,
440
+ ns_resolver: NsResolver,
441
+ typevars_map: Mapping[TypeVar, Any],
442
+ ) -> tuple[dict[str, FieldInfo], PydanticExtraInfo | None]:
443
+ """Rebuild the (already present) model fields by trying to reevaluate annotations.
444
+
445
+ This function should be called whenever a model with incomplete fields is encountered.
446
+
447
+ Returns:
448
+ A two-tuple, the first element being the rebuilt fields, the second element being
449
+ the rebuild `PydanticExtraInfo` instance, if available.
450
+
451
+ Raises:
452
+ NameError: If one of the annotations failed to evaluate.
453
+
454
+ Note:
455
+ This function *doesn't* mutate the model fields in place, as it can be called during
456
+ schema generation, where you don't want to mutate other model's fields.
457
+ """
458
+ rebuilt_fields: dict[str, FieldInfo] = {}
459
+ with ns_resolver.push(cls):
460
+ for f_name, field_info in cls.__pydantic_fields__.items():
461
+ if field_info._complete:
462
+ rebuilt_fields[f_name] = field_info
463
+ else:
464
+ new_field = _recreate_field_info(
465
+ field_info, ns_resolver=ns_resolver, typevars_map=typevars_map, lenient=False
466
+ )
467
+ update_field_from_config(config_wrapper, f_name, new_field)
468
+ rebuilt_fields[f_name] = new_field
469
+
470
+ if cls.__pydantic_extra_info__ is not None and not cls.__pydantic_extra_info__.complete:
471
+ rebuilt_extra_info = PydanticExtraInfo(
472
+ annotation=_typing_extra.eval_type(
473
+ cls.__pydantic_extra_info__.annotation, *ns_resolver.types_namespace
474
+ ),
475
+ complete=True,
476
+ )
477
+ else:
478
+ rebuilt_extra_info = cls.__pydantic_extra_info__
479
+
480
+ return rebuilt_fields, rebuilt_extra_info
481
+
482
+
483
+ def _recreate_field_info(
484
+ field_info: FieldInfo,
485
+ ns_resolver: NsResolver,
486
+ typevars_map: Mapping[TypeVar, Any],
487
+ *,
488
+ lenient: bool,
489
+ ) -> FieldInfo:
490
+ FieldInfo_ = import_cached_field_info()
491
+
492
+ existing_desc = field_info.description
493
+ if lenient:
494
+ ann = _generics.replace_types(field_info._original_annotation, typevars_map)
495
+ ann, evaluated = _typing_extra.try_eval_type(
496
+ ann,
497
+ *ns_resolver.types_namespace,
498
+ )
499
+ else:
500
+ # Not the best pattern, maybe we could ship our own `eval_type()`,
501
+ # that would replace the type variables on the fly during evaluation.
502
+ ann = _typing_extra.eval_type(
503
+ field_info._original_annotation,
504
+ *ns_resolver.types_namespace,
505
+ )
506
+ ann = _generics.replace_types(ann, typevars_map)
507
+ ann = _typing_extra.eval_type(
508
+ ann,
509
+ *ns_resolver.types_namespace,
510
+ )
511
+ evaluated = True
512
+
513
+ if (assign := field_info._original_assignment) is PydanticUndefined:
514
+ new_field = FieldInfo_.from_annotation(ann, _source=AnnotationSource.CLASS)
515
+ else:
516
+ new_field = FieldInfo_.from_annotated_attribute(ann, assign, _source=AnnotationSource.CLASS)
517
+ new_field._original_assignment = assign
518
+ new_field._original_annotation = ann
519
+ # The description might come from the docstring if `use_attribute_docstrings` was `True`:
520
+ new_field.description = new_field.description if new_field.description is not None else existing_desc
521
+ if not evaluated:
522
+ new_field._complete = False
523
+
524
+ return new_field
525
+
526
+
527
+ def collect_dataclass_fields(
528
+ cls: type[StandardDataclass],
529
+ *,
530
+ config_wrapper: ConfigWrapper,
531
+ ns_resolver: NsResolver | None = None,
532
+ typevars_map: dict[Any, Any] | None = None,
533
+ ) -> dict[str, FieldInfo]:
534
+ """Collect the fields of a dataclass.
535
+
536
+ Args:
537
+ cls: dataclass.
538
+ config_wrapper: The config wrapper instance.
539
+ ns_resolver: Namespace resolver to use when getting dataclass annotations.
540
+ Defaults to an empty instance.
541
+ typevars_map: A dictionary mapping type variables to their concrete types.
542
+
543
+ Returns:
544
+ The dataclass fields.
545
+ """
546
+ FieldInfo_ = import_cached_field_info()
547
+
548
+ fields: dict[str, FieldInfo] = {}
549
+ ns_resolver = ns_resolver or NsResolver()
550
+ dataclass_fields = cls.__dataclass_fields__
551
+
552
+ # The logic here is similar to `_typing_extra.get_cls_type_hints`,
553
+ # although we do it manually as stdlib dataclasses already have annotations
554
+ # collected in each class:
555
+ for base in reversed(cls.__mro__):
556
+ if not dataclasses.is_dataclass(base):
557
+ continue
558
+
559
+ with ns_resolver.push(base):
560
+ for ann_name, dataclass_field in dataclass_fields.items():
561
+ base_anns = _typing_extra.safe_get_annotations(base)
562
+
563
+ if ann_name not in base_anns:
564
+ # `__dataclass_fields__`contains every field, even the ones from base classes.
565
+ # Only collect the ones defined on `base`.
566
+ continue
567
+
568
+ globalns, localns = ns_resolver.types_namespace
569
+ ann_type, evaluated = _typing_extra.try_eval_type(dataclass_field.type, globalns, localns)
570
+
571
+ if _typing_extra.is_classvar_annotation(ann_type):
572
+ continue
573
+
574
+ if (
575
+ not dataclass_field.init
576
+ and dataclass_field.default is dataclasses.MISSING
577
+ and dataclass_field.default_factory is dataclasses.MISSING
578
+ ):
579
+ # TODO: We should probably do something with this so that validate_assignment behaves properly
580
+ # Issue: https://github.com/pydantic/pydantic/issues/5470
581
+ continue
582
+
583
+ if isinstance(dataclass_field.default, FieldInfo_):
584
+ if dataclass_field.default.init_var:
585
+ if dataclass_field.default.init is False:
586
+ raise PydanticUserError(
587
+ f'Dataclass field {ann_name} has init=False and init_var=True, but these are mutually exclusive.',
588
+ code='clashing-init-and-init-var',
589
+ )
590
+
591
+ # TODO: same note as above re validate_assignment
592
+ continue
593
+ field_info = FieldInfo_.from_annotated_attribute(
594
+ ann_type, dataclass_field.default, _source=AnnotationSource.DATACLASS
595
+ )
596
+ field_info._original_assignment = dataclass_field.default
597
+ else:
598
+ field_info = FieldInfo_.from_annotated_attribute(
599
+ ann_type, dataclass_field, _source=AnnotationSource.DATACLASS
600
+ )
601
+ field_info._original_assignment = dataclass_field
602
+
603
+ if not evaluated:
604
+ field_info._complete = False
605
+ field_info._original_annotation = ann_type
606
+
607
+ fields[ann_name] = field_info
608
+ update_field_from_config(config_wrapper, ann_name, field_info)
609
+
610
+ if field_info.default is not PydanticUndefined and isinstance(
611
+ getattr(cls, ann_name, field_info), FieldInfo_
612
+ ):
613
+ # We need this to fix the default when the "default" from __dataclass_fields__ is a pydantic.FieldInfo
614
+ setattr(cls, ann_name, field_info.default)
615
+
616
+ if typevars_map:
617
+ for field in fields.values():
618
+ # We don't pass any ns, as `field.annotation`
619
+ # was already evaluated. TODO: is this method relevant?
620
+ # Can't we juste use `_generics.replace_types`?
621
+ field.apply_typevars_map(typevars_map)
622
+
623
+ if config_wrapper.use_attribute_docstrings:
624
+ _update_fields_from_docstrings(
625
+ cls,
626
+ fields,
627
+ # We can't rely on the (more reliable) frame inspection method
628
+ # for stdlib dataclasses:
629
+ use_inspect=not hasattr(cls, '__is_pydantic_dataclass__'),
630
+ )
631
+
632
+ return fields
633
+
634
+
635
+ def rebuild_dataclass_fields(
636
+ cls: type[PydanticDataclass],
637
+ *,
638
+ config_wrapper: ConfigWrapper,
639
+ ns_resolver: NsResolver,
640
+ typevars_map: Mapping[TypeVar, Any],
641
+ ) -> dict[str, FieldInfo]:
642
+ """Rebuild the (already present) dataclass fields by trying to reevaluate annotations.
643
+
644
+ This function should be called whenever a dataclass with incomplete fields is encountered.
645
+
646
+ Raises:
647
+ NameError: If one of the annotations failed to evaluate.
648
+
649
+ Note:
650
+ This function *doesn't* mutate the dataclass fields in place, as it can be called during
651
+ schema generation, where you don't want to mutate other dataclass's fields.
652
+ """
653
+ FieldInfo_ = import_cached_field_info()
654
+
655
+ rebuilt_fields: dict[str, FieldInfo] = {}
656
+ with ns_resolver.push(cls):
657
+ for f_name, field_info in cls.__pydantic_fields__.items():
658
+ if field_info._complete:
659
+ rebuilt_fields[f_name] = field_info
660
+ else:
661
+ existing_desc = field_info.description
662
+ ann = _typing_extra.eval_type(
663
+ field_info._original_annotation,
664
+ *ns_resolver.types_namespace,
665
+ )
666
+ ann = _generics.replace_types(ann, typevars_map)
667
+ new_field = FieldInfo_.from_annotated_attribute(
668
+ ann,
669
+ field_info._original_assignment,
670
+ _source=AnnotationSource.DATACLASS,
671
+ )
672
+
673
+ # The description might come from the docstring if `use_attribute_docstrings` was `True`:
674
+ new_field.description = new_field.description if new_field.description is not None else existing_desc
675
+ update_field_from_config(config_wrapper, f_name, new_field)
676
+ rebuilt_fields[f_name] = new_field
677
+
678
+ return rebuilt_fields
679
+
680
+
681
+ def is_valid_field_name(name: str) -> bool:
682
+ return not name.startswith('_')
683
+
684
+
685
+ def is_valid_privateattr_name(name: str) -> bool:
686
+ return name.startswith('_') and not name.startswith('__')
687
+
688
+
689
+ def takes_validated_data_argument(
690
+ default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any],
691
+ ) -> TypeIs[Callable[[dict[str, Any]], Any]]:
692
+ """Whether the provided default factory callable has a validated data parameter."""
693
+ try:
694
+ sig = _typing_extra.signature_no_eval(default_factory)
695
+ except (ValueError, TypeError):
696
+ # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
697
+ # In this case, we assume no data argument is present:
698
+ return False
699
+
700
+ parameters = list(sig.parameters.values())
701
+
702
+ return len(parameters) == 1 and can_be_positional(parameters[0]) and parameters[0].default is Parameter.empty
703
+
704
+
705
+ def resolve_default_value(
706
+ default: Any,
707
+ default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None,
708
+ *,
709
+ validated_data: dict[str, Any] | None = None,
710
+ call_default_factory: bool = False,
711
+ ) -> Any:
712
+ """Resolve the default value using either a static default or a default_factory."""
713
+ from ._utils import smart_deepcopy
714
+
715
+ if default_factory is None:
716
+ return smart_deepcopy(default)
717
+ if call_default_factory:
718
+ if takes_validated_data_argument(default_factory=default_factory):
719
+ fac = cast('Callable[[dict[str, Any]], Any]', default_factory)
720
+ if validated_data is None:
721
+ raise ValueError(
722
+ "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default()'."
723
+ )
724
+ return fac(validated_data)
725
+ else:
726
+ fac = cast('Callable[[], Any]', default_factory)
727
+ return fac()
728
+
729
+ return PydanticUndefined
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_forward_ref.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations as _annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Union
5
+
6
+
7
+ @dataclass
8
+ class PydanticRecursiveRef:
9
+ type_ref: str
10
+
11
+ __name__ = 'PydanticRecursiveRef'
12
+ __hash__ = object.__hash__
13
+
14
+ def __call__(self) -> None:
15
+ """Defining __call__ is necessary for the `typing` module to let you use an instance of
16
+ this class as the result of resolving a standard ForwardRef.
17
+ """
18
+
19
+ def __or__(self, other):
20
+ return Union[self, other] # type: ignore
21
+
22
+ def __ror__(self, other):
23
+ return Union[other, self] # type: ignore
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_generate_schema.py ADDED
The diff for this file is too large to render. See raw diff
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_generics.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import operator
4
+ import sys
5
+ import types
6
+ import typing
7
+ from collections import ChainMap
8
+ from collections.abc import Iterator, Mapping
9
+ from contextlib import contextmanager
10
+ from contextvars import ContextVar
11
+ from functools import reduce
12
+ from itertools import zip_longest
13
+ from types import prepare_class
14
+ from typing import TYPE_CHECKING, Annotated, Any, TypedDict, TypeVar, cast
15
+ from weakref import WeakValueDictionary
16
+
17
+ import typing_extensions
18
+ from typing_inspection import typing_objects
19
+ from typing_inspection.introspection import is_union_origin
20
+
21
+ from . import _typing_extra
22
+ from ._core_utils import get_type_ref
23
+ from ._forward_ref import PydanticRecursiveRef
24
+ from ._utils import all_identical, is_model_class
25
+
26
+ if TYPE_CHECKING:
27
+ from ..main import BaseModel
28
+
29
+ GenericTypesCacheKey = tuple[Any, Any, tuple[Any, ...]]
30
+
31
+ # Note: We want to remove LimitedDict, but to do this, we'd need to improve the handling of generics caching.
32
+ # Right now, to handle recursive generics, we some types must remain cached for brief periods without references.
33
+ # By chaining the WeakValuesDict with a LimitedDict, we have a way to retain caching for all types with references,
34
+ # while also retaining a limited number of types even without references. This is generally enough to build
35
+ # specific recursive generic models without losing required items out of the cache.
36
+
37
+ KT = TypeVar('KT')
38
+ VT = TypeVar('VT')
39
+ _LIMITED_DICT_SIZE = 100
40
+
41
+
42
+ class LimitedDict(dict[KT, VT]):
43
+ def __init__(self, size_limit: int = _LIMITED_DICT_SIZE) -> None:
44
+ self.size_limit = size_limit
45
+ super().__init__()
46
+
47
+ def __setitem__(self, key: KT, value: VT, /) -> None:
48
+ super().__setitem__(key, value)
49
+ if len(self) > self.size_limit:
50
+ excess = len(self) - self.size_limit + self.size_limit // 10
51
+ to_remove = list(self.keys())[:excess]
52
+ for k in to_remove:
53
+ del self[k]
54
+
55
+
56
+ # weak dictionaries allow the dynamically created parametrized versions of generic models to get collected
57
+ # once they are no longer referenced by the caller.
58
+ GenericTypesCache = WeakValueDictionary[GenericTypesCacheKey, 'type[BaseModel]']
59
+
60
+ if TYPE_CHECKING:
61
+
62
+ class DeepChainMap(ChainMap[KT, VT]): # type: ignore
63
+ ...
64
+
65
+ else:
66
+
67
+ class DeepChainMap(ChainMap):
68
+ """Variant of ChainMap that allows direct updates to inner scopes.
69
+
70
+ Taken from https://docs.python.org/3/library/collections.html#collections.ChainMap,
71
+ with some light modifications for this use case.
72
+ """
73
+
74
+ def clear(self) -> None:
75
+ for mapping in self.maps:
76
+ mapping.clear()
77
+
78
+ def __setitem__(self, key: KT, value: VT) -> None:
79
+ for mapping in self.maps:
80
+ mapping[key] = value
81
+
82
+ def __delitem__(self, key: KT) -> None:
83
+ hit = False
84
+ for mapping in self.maps:
85
+ if key in mapping:
86
+ del mapping[key]
87
+ hit = True
88
+ if not hit:
89
+ raise KeyError(key)
90
+
91
+
92
+ # Despite the fact that LimitedDict _seems_ no longer necessary, I'm very nervous to actually remove it
93
+ # and discover later on that we need to re-add all this infrastructure...
94
+ # _GENERIC_TYPES_CACHE = DeepChainMap(GenericTypesCache(), LimitedDict())
95
+
96
+ _GENERIC_TYPES_CACHE = GenericTypesCache()
97
+
98
+
99
+ class PydanticGenericMetadata(TypedDict):
100
+ origin: type[BaseModel] | None # analogous to typing._GenericAlias.__origin__
101
+ args: tuple[Any, ...] # analogous to typing._GenericAlias.__args__
102
+ parameters: tuple[TypeVar, ...] # analogous to typing.Generic.__parameters__
103
+
104
+
105
+ def create_generic_submodel(
106
+ model_name: str, origin: type[BaseModel], args: tuple[Any, ...], params: tuple[Any, ...]
107
+ ) -> type[BaseModel]:
108
+ """Dynamically create a submodel of a provided (generic) BaseModel.
109
+
110
+ This is used when producing concrete parametrizations of generic models. This function
111
+ only *creates* the new subclass; the schema/validators/serialization must be updated to
112
+ reflect a concrete parametrization elsewhere.
113
+
114
+ Args:
115
+ model_name: The name of the newly created model.
116
+ origin: The base class for the new model to inherit from.
117
+ args: A tuple of generic metadata arguments.
118
+ params: A tuple of generic metadata parameters.
119
+
120
+ Returns:
121
+ The created submodel.
122
+ """
123
+ namespace: dict[str, Any] = {'__module__': origin.__module__}
124
+ bases = (origin,)
125
+ meta, ns, kwds = prepare_class(model_name, bases)
126
+ namespace.update(ns)
127
+ created_model = meta(
128
+ model_name,
129
+ bases,
130
+ namespace,
131
+ __pydantic_generic_metadata__={
132
+ 'origin': origin,
133
+ 'args': args,
134
+ 'parameters': params,
135
+ },
136
+ __pydantic_reset_parent_namespace__=False,
137
+ **kwds,
138
+ )
139
+
140
+ model_module, called_globally = _get_caller_frame_info(depth=3)
141
+ if called_globally: # create global reference and therefore allow pickling
142
+ object_by_reference = None
143
+ reference_name = model_name
144
+ reference_module_globals = sys.modules[created_model.__module__].__dict__
145
+ while object_by_reference is not created_model:
146
+ object_by_reference = reference_module_globals.setdefault(reference_name, created_model)
147
+ reference_name += '_'
148
+
149
+ return created_model
150
+
151
+
152
+ def _get_caller_frame_info(depth: int = 2) -> tuple[str | None, bool]:
153
+ """Used inside a function to check whether it was called globally.
154
+
155
+ Args:
156
+ depth: The depth to get the frame.
157
+
158
+ Returns:
159
+ A tuple contains `module_name` and `called_globally`.
160
+
161
+ Raises:
162
+ RuntimeError: If the function is not called inside a function.
163
+ """
164
+ try:
165
+ previous_caller_frame = sys._getframe(depth)
166
+ except ValueError as e:
167
+ raise RuntimeError('This function must be used inside another function') from e
168
+ except AttributeError: # sys module does not have _getframe function, so there's nothing we can do about it
169
+ return None, False
170
+ frame_globals = previous_caller_frame.f_globals
171
+ return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals
172
+
173
+
174
+ DictValues: type[Any] = {}.values().__class__
175
+
176
+
177
+ def iter_contained_typevars(v: Any) -> Iterator[TypeVar]:
178
+ """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found.
179
+
180
+ This is inspired as an alternative to directly accessing the `__parameters__` attribute of a GenericAlias,
181
+ since __parameters__ of (nested) generic BaseModel subclasses won't show up in that list.
182
+ """
183
+ if isinstance(v, TypeVar):
184
+ yield v
185
+ elif is_model_class(v):
186
+ yield from v.__pydantic_generic_metadata__['parameters']
187
+ elif isinstance(v, (DictValues, list)):
188
+ for var in v:
189
+ yield from iter_contained_typevars(var)
190
+ else:
191
+ args = get_args(v)
192
+ for arg in args:
193
+ yield from iter_contained_typevars(arg)
194
+
195
+
196
+ def get_args(v: Any) -> Any:
197
+ pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None)
198
+ if pydantic_generic_metadata:
199
+ return pydantic_generic_metadata.get('args')
200
+ return typing_extensions.get_args(v)
201
+
202
+
203
+ def get_origin(v: Any) -> Any:
204
+ pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None)
205
+ if pydantic_generic_metadata:
206
+ return pydantic_generic_metadata.get('origin')
207
+ return typing_extensions.get_origin(v)
208
+
209
+
210
+ def get_standard_typevars_map(cls: Any) -> dict[TypeVar, Any] | None:
211
+ """Package a generic type's typevars and parametrization (if present) into a dictionary compatible with the
212
+ `replace_types` function. Specifically, this works with standard typing generics and typing._GenericAlias.
213
+ """
214
+ origin = get_origin(cls)
215
+ if origin is None:
216
+ return None
217
+ if not hasattr(origin, '__parameters__'):
218
+ return None
219
+
220
+ # In this case, we know that cls is a _GenericAlias, and origin is the generic type
221
+ # So it is safe to access cls.__args__ and origin.__parameters__
222
+ args: tuple[Any, ...] = cls.__args__ # type: ignore
223
+ parameters: tuple[TypeVar, ...] = origin.__parameters__
224
+ return dict(zip(parameters, args))
225
+
226
+
227
+ def get_model_typevars_map(cls: type[BaseModel]) -> dict[TypeVar, Any]:
228
+ """Package a generic BaseModel's typevars and concrete parametrization (if present) into a dictionary compatible
229
+ with the `replace_types` function.
230
+
231
+ Since BaseModel.__class_getitem__ does not produce a typing._GenericAlias, and the BaseModel generic info is
232
+ stored in the __pydantic_generic_metadata__ attribute, we need special handling here.
233
+ """
234
+ # TODO: This could be unified with `get_standard_typevars_map` if we stored the generic metadata
235
+ # in the __origin__, __args__, and __parameters__ attributes of the model.
236
+ generic_metadata = cls.__pydantic_generic_metadata__
237
+ origin = generic_metadata['origin']
238
+ args = generic_metadata['args']
239
+ if not args:
240
+ # No need to go into `iter_contained_typevars`:
241
+ return {}
242
+ return dict(zip(iter_contained_typevars(origin), args))
243
+
244
+
245
+ def replace_types(type_: Any, type_map: Mapping[TypeVar, Any] | None) -> Any:
246
+ """Return type with all occurrences of `type_map` keys recursively replaced with their values.
247
+
248
+ Args:
249
+ type_: The class or generic alias.
250
+ type_map: Mapping from `TypeVar` instance to concrete types.
251
+
252
+ Returns:
253
+ A new type representing the basic structure of `type_` with all
254
+ `typevar_map` keys recursively replaced.
255
+
256
+ Example:
257
+ ```python
258
+ from typing import Union
259
+
260
+ from pydantic._internal._generics import replace_types
261
+
262
+ replace_types(tuple[str, Union[list[str], float]], {str: int})
263
+ #> tuple[int, Union[list[int], float]]
264
+ ```
265
+ """
266
+ if not type_map:
267
+ return type_
268
+
269
+ type_args = get_args(type_)
270
+ origin_type = get_origin(type_)
271
+
272
+ if typing_objects.is_annotated(origin_type):
273
+ annotated_type, *annotations = type_args
274
+ annotated_type = replace_types(annotated_type, type_map)
275
+ # TODO remove parentheses when we drop support for Python 3.10:
276
+ return Annotated[(annotated_type, *annotations)]
277
+
278
+ # Having type args is a good indicator that this is a typing special form
279
+ # instance or a generic alias of some sort.
280
+ if type_args:
281
+ resolved_type_args = tuple(replace_types(arg, type_map) for arg in type_args)
282
+ if all_identical(type_args, resolved_type_args):
283
+ # If all arguments are the same, there is no need to modify the
284
+ # type or create a new object at all
285
+ return type_
286
+
287
+ if (
288
+ origin_type is not None
289
+ and isinstance(type_, _typing_extra.typing_base)
290
+ and not isinstance(origin_type, _typing_extra.typing_base)
291
+ and getattr(type_, '_name', None) is not None
292
+ ):
293
+ # In python < 3.9 generic aliases don't exist so any of these like `list`,
294
+ # `type` or `collections.abc.Callable` need to be translated.
295
+ # See: https://www.python.org/dev/peps/pep-0585
296
+ origin_type = getattr(typing, type_._name)
297
+ assert origin_type is not None
298
+
299
+ if is_union_origin(origin_type):
300
+ if any(typing_objects.is_any(arg) for arg in resolved_type_args):
301
+ # `Any | T` ~ `Any`:
302
+ resolved_type_args = (Any,)
303
+ # `Never | T` ~ `T`:
304
+ resolved_type_args = tuple(
305
+ arg
306
+ for arg in resolved_type_args
307
+ if not (typing_objects.is_noreturn(arg) or typing_objects.is_never(arg))
308
+ )
309
+
310
+ # PEP-604 syntax (e.g. `list | str`) is represented with a types.UnionType object that does not
311
+ # implement `__getitem__()`. In Python 3.14+, `typing.Union` and `types.UnionType` are the same,
312
+ # and we instead rely on `typing.Union` as it implicitly converts string annotations to `ForwardRef`
313
+ # instances (this is to avoid type errors as per https://github.com/python/cpython/pull/105366).
314
+ # TODO remove type ignore comment when we drop support for Python 3.9 (https://github.com/microsoft/pyright/issues/11241):
315
+ if (3, 10) <= sys.version_info < (3, 14) and origin_type is types.UnionType: # pyright: ignore[reportAttributeAccessIssue]
316
+ return reduce(operator.or_, resolved_type_args)
317
+ # NotRequired[T] and Required[T] don't support tuple type resolved_type_args, hence the condition below
318
+ return origin_type[resolved_type_args[0] if len(resolved_type_args) == 1 else resolved_type_args]
319
+
320
+ # We handle pydantic generic models separately as they don't have the same
321
+ # semantics as "typing" classes or generic aliases
322
+
323
+ if not origin_type and is_model_class(type_):
324
+ parameters = type_.__pydantic_generic_metadata__['parameters']
325
+ if not parameters:
326
+ return type_
327
+ resolved_type_args = tuple(replace_types(t, type_map) for t in parameters)
328
+ if all_identical(parameters, resolved_type_args):
329
+ return type_
330
+ return type_[resolved_type_args]
331
+
332
+ # Handle special case for typehints that can have lists as arguments.
333
+ # `typing.Callable[[int, str], int]` is an example for this.
334
+ if isinstance(type_, list):
335
+ resolved_list = [replace_types(element, type_map) for element in type_]
336
+ if all_identical(type_, resolved_list):
337
+ return type_
338
+ return resolved_list
339
+
340
+ # If all else fails, we try to resolve the type directly and otherwise just
341
+ # return the input with no modifications.
342
+ return type_map.get(type_, type_)
343
+
344
+
345
+ def map_generic_model_arguments(cls: type[BaseModel], args: tuple[Any, ...]) -> dict[TypeVar, Any]:
346
+ """Return a mapping between the parameters of a generic model and the provided arguments during parameterization.
347
+
348
+ Raises:
349
+ TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments).
350
+
351
+ Example:
352
+ ```python {test="skip" lint="skip"}
353
+ class Model[T, U, V = int](BaseModel): ...
354
+
355
+ map_generic_model_arguments(Model, (str, bytes))
356
+ #> {T: str, U: bytes, V: int}
357
+
358
+ map_generic_model_arguments(Model, (str,))
359
+ #> TypeError: Too few arguments for <class '__main__.Model'>; actual 1, expected at least 2
360
+
361
+ map_generic_model_arguments(Model, (str, bytes, int, complex))
362
+ #> TypeError: Too many arguments for <class '__main__.Model'>; actual 4, expected 3
363
+ ```
364
+
365
+ Note:
366
+ This function is analogous to the private `typing._check_generic_specialization` function.
367
+ """
368
+ parameters = cls.__pydantic_generic_metadata__['parameters']
369
+ expected_len = len(parameters)
370
+ typevars_map: dict[TypeVar, Any] = {}
371
+
372
+ _missing = object()
373
+ for parameter, argument in zip_longest(parameters, args, fillvalue=_missing):
374
+ if parameter is _missing:
375
+ raise TypeError(f'Too many arguments for {cls}; actual {len(args)}, expected {expected_len}')
376
+
377
+ if argument is _missing:
378
+ param = cast(TypeVar, parameter)
379
+ try:
380
+ has_default = param.has_default() # pyright: ignore[reportAttributeAccessIssue]
381
+ except AttributeError:
382
+ # Happens if using `typing.TypeVar` (and not `typing_extensions`) on Python < 3.13.
383
+ has_default = False
384
+ if has_default:
385
+ # The default might refer to other type parameters. For an example, see:
386
+ # https://typing.python.org/en/latest/spec/generics.html#type-parameters-as-parameters-to-generics
387
+ typevars_map[param] = replace_types(param.__default__, typevars_map) # pyright: ignore[reportAttributeAccessIssue]
388
+ else:
389
+ expected_len -= sum(hasattr(p, 'has_default') and p.has_default() for p in parameters) # pyright: ignore[reportAttributeAccessIssue]
390
+ raise TypeError(f'Too few arguments for {cls}; actual {len(args)}, expected at least {expected_len}')
391
+ else:
392
+ param = cast(TypeVar, parameter)
393
+ typevars_map[param] = argument
394
+
395
+ return typevars_map
396
+
397
+
398
+ _generic_recursion_cache: ContextVar[set[str] | None] = ContextVar('_generic_recursion_cache', default=None)
399
+
400
+
401
+ @contextmanager
402
+ def generic_recursion_self_type(
403
+ origin: type[BaseModel], args: tuple[Any, ...]
404
+ ) -> Iterator[PydanticRecursiveRef | None]:
405
+ """This contextmanager should be placed around the recursive calls used to build a generic type,
406
+ and accept as arguments the generic origin type and the type arguments being passed to it.
407
+
408
+ If the same origin and arguments are observed twice, it implies that a self-reference placeholder
409
+ can be used while building the core schema, and will produce a schema_ref that will be valid in the
410
+ final parent schema.
411
+ """
412
+ previously_seen_type_refs = _generic_recursion_cache.get()
413
+ if previously_seen_type_refs is None:
414
+ previously_seen_type_refs = set()
415
+ token = _generic_recursion_cache.set(previously_seen_type_refs)
416
+ else:
417
+ token = None
418
+
419
+ try:
420
+ type_ref = get_type_ref(origin, args_override=args)
421
+ if type_ref in previously_seen_type_refs:
422
+ self_type = PydanticRecursiveRef(type_ref=type_ref)
423
+ yield self_type
424
+ else:
425
+ previously_seen_type_refs.add(type_ref)
426
+ yield
427
+ previously_seen_type_refs.remove(type_ref)
428
+ finally:
429
+ if token:
430
+ _generic_recursion_cache.reset(token)
431
+
432
+
433
+ def recursively_defined_type_refs() -> set[str]:
434
+ visited = _generic_recursion_cache.get()
435
+ if not visited:
436
+ return set() # not in a generic recursion, so there are no types
437
+
438
+ return visited.copy() # don't allow modifications
439
+
440
+
441
+ def get_cached_generic_type_early(parent: type[BaseModel], typevar_values: Any) -> type[BaseModel] | None:
442
+ """The use of a two-stage cache lookup approach was necessary to have the highest performance possible for
443
+ repeated calls to `__class_getitem__` on generic types (which may happen in tighter loops during runtime),
444
+ while still ensuring that certain alternative parametrizations ultimately resolve to the same type.
445
+
446
+ As a concrete example, this approach was necessary to make Model[List[T]][int] equal to Model[List[int]].
447
+ The approach could be modified to not use two different cache keys at different points, but the
448
+ _early_cache_key is optimized to be as quick to compute as possible (for repeated-access speed), and the
449
+ _late_cache_key is optimized to be as "correct" as possible, so that two types that will ultimately be the
450
+ same after resolving the type arguments will always produce cache hits.
451
+
452
+ If we wanted to move to only using a single cache key per type, we would either need to always use the
453
+ slower/more computationally intensive logic associated with _late_cache_key, or would need to accept
454
+ that Model[List[T]][int] is a different type than Model[List[T]][int]. Because we rely on subclass relationships
455
+ during validation, I think it is worthwhile to ensure that types that are functionally equivalent are actually
456
+ equal.
457
+ """
458
+ return _GENERIC_TYPES_CACHE.get(_early_cache_key(parent, typevar_values))
459
+
460
+
461
+ def get_cached_generic_type_late(
462
+ parent: type[BaseModel], typevar_values: Any, origin: type[BaseModel], args: tuple[Any, ...]
463
+ ) -> type[BaseModel] | None:
464
+ """See the docstring of `get_cached_generic_type_early` for more information about the two-stage cache lookup."""
465
+ cached = _GENERIC_TYPES_CACHE.get(_late_cache_key(origin, args, typevar_values))
466
+ if cached is not None:
467
+ set_cached_generic_type(parent, typevar_values, cached, origin, args)
468
+ return cached
469
+
470
+
471
+ def set_cached_generic_type(
472
+ parent: type[BaseModel],
473
+ typevar_values: tuple[Any, ...],
474
+ type_: type[BaseModel],
475
+ origin: type[BaseModel] | None = None,
476
+ args: tuple[Any, ...] | None = None,
477
+ ) -> None:
478
+ """See the docstring of `get_cached_generic_type_early` for more information about why items are cached with
479
+ two different keys.
480
+ """
481
+ _GENERIC_TYPES_CACHE[_early_cache_key(parent, typevar_values)] = type_
482
+ if len(typevar_values) == 1:
483
+ _GENERIC_TYPES_CACHE[_early_cache_key(parent, typevar_values[0])] = type_
484
+ if origin and args:
485
+ _GENERIC_TYPES_CACHE[_late_cache_key(origin, args, typevar_values)] = type_
486
+
487
+
488
+ def _union_orderings_key(typevar_values: Any) -> Any:
489
+ """This is intended to help differentiate between Union types with the same arguments in different order.
490
+
491
+ Thanks to caching internal to the `typing` module, it is not possible to distinguish between
492
+ List[Union[int, float]] and List[Union[float, int]] (and similarly for other "parent" origins besides List)
493
+ because `typing` considers Union[int, float] to be equal to Union[float, int].
494
+
495
+ However, you _can_ distinguish between (top-level) Union[int, float] vs. Union[float, int].
496
+ Because we parse items as the first Union type that is successful, we get slightly more consistent behavior
497
+ if we make an effort to distinguish the ordering of items in a union. It would be best if we could _always_
498
+ get the exact-correct order of items in the union, but that would require a change to the `typing` module itself.
499
+ (See https://github.com/python/cpython/issues/86483 for reference.)
500
+ """
501
+ if isinstance(typevar_values, tuple):
502
+ return tuple(_union_orderings_key(value) for value in typevar_values)
503
+ elif typing_objects.is_union(typing_extensions.get_origin(typevar_values)):
504
+ return get_args(typevar_values)
505
+ else:
506
+ return ()
507
+
508
+
509
+ def _early_cache_key(cls: type[BaseModel], typevar_values: Any) -> GenericTypesCacheKey:
510
+ """This is intended for minimal computational overhead during lookups of cached types.
511
+
512
+ Note that this is overly simplistic, and it's possible that two different cls/typevar_values
513
+ inputs would ultimately result in the same type being created in BaseModel.__class_getitem__.
514
+ To handle this, we have a fallback _late_cache_key that is checked later if the _early_cache_key
515
+ lookup fails, and should result in a cache hit _precisely_ when the inputs to __class_getitem__
516
+ would result in the same type.
517
+ """
518
+ return cls, typevar_values, _union_orderings_key(typevar_values)
519
+
520
+
521
+ def _late_cache_key(origin: type[BaseModel], args: tuple[Any, ...], typevar_values: Any) -> GenericTypesCacheKey:
522
+ """This is intended for use later in the process of creating a new type, when we have more information
523
+ about the exact args that will be passed. If it turns out that a different set of inputs to
524
+ __class_getitem__ resulted in the same inputs to the generic type creation process, we can still
525
+ return the cached type, and update the cache with the _early_cache_key as well.
526
+ """
527
+ # The _union_orderings_key is placed at the start here to ensure there cannot be a collision with an
528
+ # _early_cache_key, as that function will always produce a BaseModel subclass as the first item in the key,
529
+ # whereas this function will always produce a tuple as the first item in the key.
530
+ return _union_orderings_key(typevar_values), origin, args
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_git.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Git utilities, adopted from mypy's git utilities (https://github.com/python/mypy/blob/master/mypy/git.py)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+
9
+ def is_git_repo(dir: Path) -> bool:
10
+ """Is the given directory version-controlled with git?"""
11
+ return dir.joinpath('.git').exists()
12
+
13
+
14
+ def have_git() -> bool: # pragma: no cover
15
+ """Can we run the git executable?"""
16
+ try:
17
+ subprocess.check_output(['git', '--help'])
18
+ return True
19
+ except subprocess.CalledProcessError:
20
+ return False
21
+ except OSError:
22
+ return False
23
+
24
+
25
+ def git_revision(dir: Path) -> str:
26
+ """Get the SHA-1 of the HEAD of a git repository."""
27
+ return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=dir).decode('utf-8').strip()
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_import_utils.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import cache
2
+ from typing import TYPE_CHECKING
3
+
4
+ if TYPE_CHECKING:
5
+ from pydantic import BaseModel
6
+ from pydantic.fields import FieldInfo
7
+
8
+
9
+ @cache
10
+ def import_cached_base_model() -> type['BaseModel']:
11
+ from pydantic import BaseModel
12
+
13
+ return BaseModel
14
+
15
+
16
+ @cache
17
+ def import_cached_field_info() -> type['FieldInfo']:
18
+ from pydantic.fields import FieldInfo
19
+
20
+ return FieldInfo
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_internal_dataclass.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ # `slots` is available on Python >= 3.10
4
+ if sys.version_info >= (3, 10):
5
+ slots_true = {'slots': True}
6
+ else:
7
+ slots_true = {}
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_known_annotated_metadata.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections import defaultdict
4
+ from collections.abc import Iterable
5
+ from copy import copy
6
+ from functools import lru_cache, partial
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from pydantic_core import CoreSchema, PydanticCustomError, ValidationError, to_jsonable_python
10
+ from pydantic_core import core_schema as cs
11
+
12
+ from ._fields import PydanticMetadata
13
+ from ._import_utils import import_cached_field_info
14
+
15
+ if TYPE_CHECKING:
16
+ pass
17
+
18
+ STRICT = {'strict'}
19
+ FAIL_FAST = {'fail_fast'}
20
+ LENGTH_CONSTRAINTS = {'min_length', 'max_length'}
21
+ INEQUALITY = {'le', 'ge', 'lt', 'gt'}
22
+ NUMERIC_CONSTRAINTS = {'multiple_of', *INEQUALITY}
23
+ ALLOW_INF_NAN = {'allow_inf_nan'}
24
+
25
+ STR_CONSTRAINTS = {
26
+ *LENGTH_CONSTRAINTS,
27
+ *STRICT,
28
+ 'strip_whitespace',
29
+ 'to_lower',
30
+ 'to_upper',
31
+ 'pattern',
32
+ 'coerce_numbers_to_str',
33
+ 'ascii_only',
34
+ }
35
+ BYTES_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
36
+
37
+ LIST_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
38
+ TUPLE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
39
+ SET_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
40
+ DICT_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
41
+ GENERATOR_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
42
+ SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST}
43
+
44
+ FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
45
+ DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS}
46
+ INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
47
+ BOOL_CONSTRAINTS = STRICT
48
+ UUID_CONSTRAINTS = STRICT
49
+
50
+ DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
51
+ TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
52
+ TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
53
+ LAX_OR_STRICT_CONSTRAINTS = STRICT
54
+ ENUM_CONSTRAINTS = STRICT
55
+ COMPLEX_CONSTRAINTS = STRICT
56
+
57
+ UNION_CONSTRAINTS = {'union_mode'}
58
+ URL_CONSTRAINTS = {
59
+ 'max_length',
60
+ 'allowed_schemes',
61
+ 'host_required',
62
+ 'default_host',
63
+ 'default_port',
64
+ 'default_path',
65
+ }
66
+
67
+ TEXT_SCHEMA_TYPES = ('str', 'bytes', 'url', 'multi-host-url')
68
+ SEQUENCE_SCHEMA_TYPES = ('list', 'tuple', 'set', 'frozenset', 'generator', *TEXT_SCHEMA_TYPES)
69
+ NUMERIC_SCHEMA_TYPES = ('float', 'int', 'date', 'time', 'timedelta', 'datetime')
70
+
71
+ CONSTRAINTS_TO_ALLOWED_SCHEMAS: dict[str, set[str]] = defaultdict(set)
72
+
73
+ constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [
74
+ (STR_CONSTRAINTS, TEXT_SCHEMA_TYPES),
75
+ (BYTES_CONSTRAINTS, ('bytes',)),
76
+ (LIST_CONSTRAINTS, ('list',)),
77
+ (TUPLE_CONSTRAINTS, ('tuple',)),
78
+ (SET_CONSTRAINTS, ('set', 'frozenset')),
79
+ (DICT_CONSTRAINTS, ('dict',)),
80
+ (GENERATOR_CONSTRAINTS, ('generator',)),
81
+ (FLOAT_CONSTRAINTS, ('float',)),
82
+ (INT_CONSTRAINTS, ('int',)),
83
+ (DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime', 'timedelta')),
84
+ # TODO: this is a bit redundant, we could probably avoid some of these
85
+ (STRICT, (*TEXT_SCHEMA_TYPES, *SEQUENCE_SCHEMA_TYPES, *NUMERIC_SCHEMA_TYPES, 'typed-dict', 'model')),
86
+ (UNION_CONSTRAINTS, ('union',)),
87
+ (URL_CONSTRAINTS, ('url', 'multi-host-url')),
88
+ (BOOL_CONSTRAINTS, ('bool',)),
89
+ (UUID_CONSTRAINTS, ('uuid',)),
90
+ (LAX_OR_STRICT_CONSTRAINTS, ('lax-or-strict',)),
91
+ (ENUM_CONSTRAINTS, ('enum',)),
92
+ (DECIMAL_CONSTRAINTS, ('decimal',)),
93
+ (COMPLEX_CONSTRAINTS, ('complex',)),
94
+ ]
95
+
96
+ for constraints, schemas in constraint_schema_pairings:
97
+ for c in constraints:
98
+ CONSTRAINTS_TO_ALLOWED_SCHEMAS[c].update(schemas)
99
+
100
+
101
+ def as_jsonable_value(v: Any) -> Any:
102
+ if type(v) not in (int, str, float, bytes, bool, type(None)):
103
+ return to_jsonable_python(v)
104
+ return v
105
+
106
+
107
+ def expand_grouped_metadata(annotations: Iterable[Any]) -> Iterable[Any]:
108
+ """Expand the annotations.
109
+
110
+ Args:
111
+ annotations: An iterable of annotations.
112
+
113
+ Returns:
114
+ An iterable of expanded annotations.
115
+
116
+ Example:
117
+ ```python
118
+ from annotated_types import Ge, Len
119
+
120
+ from pydantic._internal._known_annotated_metadata import expand_grouped_metadata
121
+
122
+ print(list(expand_grouped_metadata([Ge(4), Len(5)])))
123
+ #> [Ge(ge=4), MinLen(min_length=5)]
124
+ ```
125
+ """
126
+ import annotated_types as at
127
+
128
+ FieldInfo = import_cached_field_info()
129
+
130
+ for annotation in annotations:
131
+ if isinstance(annotation, at.GroupedMetadata):
132
+ yield from annotation
133
+ elif isinstance(annotation, FieldInfo):
134
+ yield from annotation.metadata
135
+ # this is a bit problematic in that it results in duplicate metadata
136
+ # all of our "consumers" can handle it, but it is not ideal
137
+ # we probably should split up FieldInfo into:
138
+ # - annotated types metadata
139
+ # - individual metadata known only to Pydantic
140
+ annotation = copy(annotation)
141
+ annotation.metadata = []
142
+ yield annotation
143
+ else:
144
+ yield annotation
145
+
146
+
147
+ @lru_cache
148
+ def _get_at_to_constraint_map() -> dict[type, str]:
149
+ """Return a mapping of annotated types to constraints.
150
+
151
+ Normally, we would define a mapping like this in the module scope, but we can't do that
152
+ because we don't permit module level imports of `annotated_types`, in an attempt to speed up
153
+ the import time of `pydantic`. We still only want to have this dictionary defined in one place,
154
+ so we use this function to cache the result.
155
+ """
156
+ import annotated_types as at
157
+
158
+ return {
159
+ at.Gt: 'gt',
160
+ at.Ge: 'ge',
161
+ at.Lt: 'lt',
162
+ at.Le: 'le',
163
+ at.MultipleOf: 'multiple_of',
164
+ at.MinLen: 'min_length',
165
+ at.MaxLen: 'max_length',
166
+ }
167
+
168
+
169
+ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | None: # noqa: C901
170
+ """Apply `annotation` to `schema` if it is an annotation we know about (Gt, Le, etc.).
171
+ Otherwise return `None`.
172
+
173
+ This does not handle all known annotations. If / when it does, it can always
174
+ return a CoreSchema and return the unmodified schema if the annotation should be ignored.
175
+
176
+ Assumes that GroupedMetadata has already been expanded via `expand_grouped_metadata`.
177
+
178
+ Args:
179
+ annotation: The annotation.
180
+ schema: The schema.
181
+
182
+ Returns:
183
+ An updated schema with annotation if it is an annotation we know about, `None` otherwise.
184
+
185
+ Raises:
186
+ RuntimeError: If a constraint can't be applied to a specific schema type.
187
+ ValueError: If an unknown constraint is encountered.
188
+ """
189
+ import annotated_types as at
190
+
191
+ from ._validators import NUMERIC_VALIDATOR_LOOKUP, forbid_inf_nan_check
192
+
193
+ schema = schema.copy()
194
+ schema_update, other_metadata = collect_known_metadata([annotation])
195
+ schema_type = schema['type']
196
+
197
+ chain_schema_constraints: set[str] = {
198
+ 'pattern',
199
+ 'strip_whitespace',
200
+ 'to_lower',
201
+ 'to_upper',
202
+ 'coerce_numbers_to_str',
203
+ 'ascii_only',
204
+ }
205
+ chain_schema_steps: list[CoreSchema] = []
206
+
207
+ for constraint, value in schema_update.items():
208
+ if constraint not in CONSTRAINTS_TO_ALLOWED_SCHEMAS:
209
+ raise ValueError(f'Unknown constraint {constraint}')
210
+ allowed_schemas = CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint]
211
+
212
+ # if it becomes necessary to handle more than one constraint
213
+ # in this recursive case with function-after or function-wrap, we should refactor
214
+ # this is a bit challenging because we sometimes want to apply constraints to the inner schema,
215
+ # whereas other times we want to wrap the existing schema with a new one that enforces a new constraint.
216
+ if schema_type in {'function-before', 'function-wrap', 'function-after'} and constraint == 'strict':
217
+ schema['schema'] = apply_known_metadata(annotation, schema['schema']) # type: ignore # schema is function schema
218
+ return schema
219
+
220
+ # if we're allowed to apply constraint directly to the schema, like le to int, do that
221
+ if schema_type in allowed_schemas:
222
+ if constraint == 'union_mode' and schema_type == 'union':
223
+ schema['mode'] = value # type: ignore # schema is UnionSchema
224
+ else:
225
+ schema[constraint] = value
226
+ continue
227
+
228
+ # else, apply a function after validator to the schema to enforce the corresponding constraint
229
+ if constraint in chain_schema_constraints:
230
+
231
+ def _apply_constraint_with_incompatibility_info(
232
+ value: Any, handler: cs.ValidatorFunctionWrapHandler
233
+ ) -> Any:
234
+ try:
235
+ x = handler(value)
236
+ except ValidationError as ve:
237
+ # if the error is about the type, it's likely that the constraint is incompatible the type of the field
238
+ # for example, the following invalid schema wouldn't be caught during schema build, but rather at this point
239
+ # with a cryptic 'string_type' error coming from the string validator,
240
+ # that we'd rather express as a constraint incompatibility error (TypeError)
241
+ # Annotated[list[int], Field(pattern='abc')]
242
+ if 'type' in ve.errors()[0]['type']:
243
+ raise TypeError(
244
+ f"Unable to apply constraint '{constraint}' to supplied value {value} for schema of type '{schema_type}'" # noqa: B023
245
+ )
246
+ raise ve
247
+ return x
248
+
249
+ chain_schema_steps.append(
250
+ cs.no_info_wrap_validator_function(
251
+ _apply_constraint_with_incompatibility_info, cs.str_schema(**{constraint: value})
252
+ )
253
+ )
254
+ elif constraint in NUMERIC_VALIDATOR_LOOKUP:
255
+ if constraint in LENGTH_CONSTRAINTS:
256
+ inner_schema = schema
257
+ while inner_schema['type'] in {'function-before', 'function-wrap', 'function-after'}:
258
+ inner_schema = inner_schema['schema'] # type: ignore
259
+ inner_schema_type = inner_schema['type']
260
+ if inner_schema_type == 'list' or (
261
+ inner_schema_type == 'json-or-python' and inner_schema['json_schema']['type'] == 'list' # type: ignore
262
+ ):
263
+ js_constraint_key = 'minItems' if constraint == 'min_length' else 'maxItems'
264
+ else:
265
+ js_constraint_key = 'minLength' if constraint == 'min_length' else 'maxLength'
266
+ else:
267
+ js_constraint_key = constraint
268
+
269
+ schema = cs.no_info_after_validator_function(
270
+ partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schema
271
+ )
272
+ metadata = schema.get('metadata', {})
273
+ if (existing_json_schema_updates := metadata.get('pydantic_js_updates')) is not None:
274
+ metadata['pydantic_js_updates'] = {
275
+ **existing_json_schema_updates,
276
+ **{js_constraint_key: as_jsonable_value(value)},
277
+ }
278
+ else:
279
+ metadata['pydantic_js_updates'] = {js_constraint_key: as_jsonable_value(value)}
280
+ schema['metadata'] = metadata
281
+ elif constraint == 'allow_inf_nan' and value is False:
282
+ schema = cs.no_info_after_validator_function(
283
+ forbid_inf_nan_check,
284
+ schema,
285
+ )
286
+ else:
287
+ # It's rare that we'd get here, but it's possible if we add a new constraint and forget to handle it
288
+ # Most constraint errors are caught at runtime during attempted application
289
+ raise RuntimeError(f"Unable to apply constraint '{constraint}' to schema of type '{schema_type}'")
290
+
291
+ for annotation in other_metadata:
292
+ if (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
293
+ constraint = at_to_constraint_map[annotation_type]
294
+ validator = NUMERIC_VALIDATOR_LOOKUP.get(constraint)
295
+ if validator is None:
296
+ raise ValueError(f'Unknown constraint {constraint}')
297
+ schema = cs.no_info_after_validator_function(
298
+ partial(validator, {constraint: getattr(annotation, constraint)}), schema
299
+ )
300
+ continue
301
+ elif isinstance(annotation, (at.Predicate, at.Not)):
302
+ predicate_name = f'{annotation.func.__qualname__!r} ' if hasattr(annotation.func, '__qualname__') else ''
303
+
304
+ # Note: B023 is ignored because even though we iterate over `other_metadata`, it is guaranteed
305
+ # to be of length 1. `apply_known_metadata()` is called from `GenerateSchema`, where annotations
306
+ # were already expanded via `expand_grouped_metadata()`. Confusing, but this falls into the annotations
307
+ # refactor.
308
+ if isinstance(annotation, at.Predicate):
309
+
310
+ def val_func(v: Any) -> Any:
311
+ predicate_satisfied = annotation.func(v) # noqa: B023
312
+ if not predicate_satisfied:
313
+ raise PydanticCustomError(
314
+ 'predicate_failed',
315
+ f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
316
+ )
317
+ return v
318
+
319
+ else:
320
+
321
+ def val_func(v: Any) -> Any:
322
+ predicate_satisfied = annotation.func(v) # noqa: B023
323
+ if predicate_satisfied:
324
+ raise PydanticCustomError(
325
+ 'not_operation_failed',
326
+ f'Not of {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
327
+ )
328
+ return v
329
+
330
+ schema = cs.no_info_after_validator_function(val_func, schema)
331
+ else:
332
+ # ignore any other unknown metadata
333
+ return None
334
+
335
+ if chain_schema_steps:
336
+ chain_schema_steps = [schema] + chain_schema_steps
337
+ return cs.chain_schema(chain_schema_steps)
338
+
339
+ return schema
340
+
341
+
342
+ def collect_known_metadata(annotations: Iterable[Any]) -> tuple[dict[str, Any], list[Any]]:
343
+ """Split `annotations` into known metadata and unknown annotations.
344
+
345
+ Args:
346
+ annotations: An iterable of annotations.
347
+
348
+ Returns:
349
+ A tuple contains a dict of known metadata and a list of unknown annotations.
350
+
351
+ Example:
352
+ ```python
353
+ from annotated_types import Gt, Len
354
+
355
+ from pydantic._internal._known_annotated_metadata import collect_known_metadata
356
+
357
+ print(collect_known_metadata([Gt(1), Len(42), ...]))
358
+ #> ({'gt': 1, 'min_length': 42}, [Ellipsis])
359
+ ```
360
+ """
361
+ annotations = expand_grouped_metadata(annotations)
362
+
363
+ res: dict[str, Any] = {}
364
+ remaining: list[Any] = []
365
+
366
+ for annotation in annotations:
367
+ # isinstance(annotation, PydanticMetadata) also covers ._fields:_PydanticGeneralMetadata
368
+ if isinstance(annotation, PydanticMetadata):
369
+ res.update(annotation.__dict__)
370
+ # we don't use dataclasses.asdict because that recursively calls asdict on the field values
371
+ elif (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
372
+ constraint = at_to_constraint_map[annotation_type]
373
+ res[constraint] = getattr(annotation, constraint)
374
+ elif isinstance(annotation, type) and issubclass(annotation, PydanticMetadata):
375
+ # also support PydanticMetadata classes being used without initialisation,
376
+ # e.g. `Annotated[int, Strict]` as well as `Annotated[int, Strict()]`
377
+ res.update({k: v for k, v in vars(annotation).items() if not k.startswith('_')})
378
+ else:
379
+ remaining.append(annotation)
380
+ # Nones can sneak in but pydantic-core will reject them
381
+ # it'd be nice to clean things up so we don't put in None (we probably don't _need_ to, it was just easier)
382
+ # but this is simple enough to kick that can down the road
383
+ res = {k: v for k, v in res.items() if v is not None}
384
+ return res, remaining
385
+
386
+
387
+ def check_metadata(metadata: dict[str, Any], allowed: Iterable[str], source_type: Any) -> None:
388
+ """A small utility function to validate that the given metadata can be applied to the target.
389
+ More than saving lines of code, this gives us a consistent error message for all of our internal implementations.
390
+
391
+ Args:
392
+ metadata: A dict of metadata.
393
+ allowed: An iterable of allowed metadata.
394
+ source_type: The source type.
395
+
396
+ Raises:
397
+ TypeError: If there is metadatas that can't be applied on source type.
398
+ """
399
+ unknown = metadata.keys() - set(allowed)
400
+ if unknown:
401
+ raise TypeError(
402
+ f'The following constraints cannot be applied to {source_type!r}: {", ".join([f"{k!r}" for k in unknown])}'
403
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_mock_val_ser.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator, Mapping
4
+ from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, TypeVar, Union
5
+
6
+ from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator
7
+
8
+ from ..errors import PydanticErrorCodes, PydanticUserError
9
+ from ..plugin._schema_validator import PluggableSchemaValidator
10
+
11
+ if TYPE_CHECKING:
12
+ from ..dataclasses import PydanticDataclass
13
+ from ..main import BaseModel
14
+ from ..type_adapter import TypeAdapter
15
+
16
+
17
+ ValSer = TypeVar('ValSer', bound=Union[SchemaValidator, PluggableSchemaValidator, SchemaSerializer])
18
+ T = TypeVar('T')
19
+
20
+
21
+ class MockCoreSchema(Mapping[str, Any]):
22
+ """Mocker for `pydantic_core.CoreSchema` which optionally attempts to
23
+ rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails.
24
+ """
25
+
26
+ __slots__ = '_error_message', '_code', '_attempt_rebuild', '_built_memo'
27
+
28
+ def __init__(
29
+ self,
30
+ error_message: str,
31
+ *,
32
+ code: PydanticErrorCodes,
33
+ attempt_rebuild: Callable[[], CoreSchema | None] | None = None,
34
+ ) -> None:
35
+ self._error_message = error_message
36
+ self._code: PydanticErrorCodes = code
37
+ self._attempt_rebuild = attempt_rebuild
38
+ self._built_memo: CoreSchema | None = None
39
+
40
+ def __getitem__(self, key: str) -> Any:
41
+ return self._get_built().__getitem__(key)
42
+
43
+ def __len__(self) -> int:
44
+ return self._get_built().__len__()
45
+
46
+ def __iter__(self) -> Iterator[str]:
47
+ return self._get_built().__iter__()
48
+
49
+ def _get_built(self) -> CoreSchema:
50
+ if self._built_memo is not None:
51
+ return self._built_memo
52
+
53
+ if self._attempt_rebuild:
54
+ schema = self._attempt_rebuild()
55
+ if schema is not None:
56
+ self._built_memo = schema
57
+ return schema
58
+ raise PydanticUserError(self._error_message, code=self._code)
59
+
60
+ def rebuild(self) -> CoreSchema | None:
61
+ self._built_memo = None
62
+ if self._attempt_rebuild:
63
+ schema = self._attempt_rebuild()
64
+ if schema is not None:
65
+ return schema
66
+ else:
67
+ raise PydanticUserError(self._error_message, code=self._code)
68
+ return None
69
+
70
+
71
+ class MockValSer(Generic[ValSer]):
72
+ """Mocker for `pydantic_core.SchemaValidator` or `pydantic_core.SchemaSerializer` which optionally attempts to
73
+ rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails.
74
+ """
75
+
76
+ __slots__ = '_error_message', '_code', '_val_or_ser', '_attempt_rebuild'
77
+
78
+ def __init__(
79
+ self,
80
+ error_message: str,
81
+ *,
82
+ code: PydanticErrorCodes,
83
+ val_or_ser: Literal['validator', 'serializer'],
84
+ attempt_rebuild: Callable[[], ValSer | None] | None = None,
85
+ ) -> None:
86
+ self._error_message = error_message
87
+ self._val_or_ser = SchemaValidator if val_or_ser == 'validator' else SchemaSerializer
88
+ self._code: PydanticErrorCodes = code
89
+ self._attempt_rebuild = attempt_rebuild
90
+
91
+ def __getattr__(self, item: str) -> None:
92
+ __tracebackhide__ = True
93
+ if self._attempt_rebuild:
94
+ val_ser = self._attempt_rebuild()
95
+ if val_ser is not None:
96
+ return getattr(val_ser, item)
97
+
98
+ # raise an AttributeError if `item` doesn't exist
99
+ getattr(self._val_or_ser, item)
100
+ raise PydanticUserError(self._error_message, code=self._code)
101
+
102
+ def rebuild(self) -> ValSer | None:
103
+ if self._attempt_rebuild:
104
+ val_ser = self._attempt_rebuild()
105
+ if val_ser is not None:
106
+ return val_ser
107
+ else:
108
+ raise PydanticUserError(self._error_message, code=self._code)
109
+ return None
110
+
111
+
112
+ def set_type_adapter_mocks(adapter: TypeAdapter) -> None:
113
+ """Set `core_schema`, `validator` and `serializer` to mock core types on a type adapter instance.
114
+
115
+ Args:
116
+ adapter: The type adapter instance to set the mocks on
117
+ """
118
+ type_repr = str(adapter._type)
119
+ undefined_type_error_message = (
120
+ f'`TypeAdapter[{type_repr}]` is not fully defined; you should define `{type_repr}` and all referenced types,'
121
+ f' then call `.rebuild()` on the instance.'
122
+ )
123
+
124
+ def attempt_rebuild_fn(attr_fn: Callable[[TypeAdapter], T]) -> Callable[[], T | None]:
125
+ def handler() -> T | None:
126
+ if adapter.rebuild(raise_errors=False, _parent_namespace_depth=5) is not False:
127
+ return attr_fn(adapter)
128
+ return None
129
+
130
+ return handler
131
+
132
+ adapter.core_schema = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
133
+ undefined_type_error_message,
134
+ code='class-not-fully-defined',
135
+ attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.core_schema),
136
+ )
137
+ adapter.validator = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
138
+ undefined_type_error_message,
139
+ code='class-not-fully-defined',
140
+ val_or_ser='validator',
141
+ attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.validator),
142
+ )
143
+ adapter.serializer = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
144
+ undefined_type_error_message,
145
+ code='class-not-fully-defined',
146
+ val_or_ser='serializer',
147
+ attempt_rebuild=attempt_rebuild_fn(lambda ta: ta.serializer),
148
+ )
149
+
150
+
151
+ def set_model_mocks(cls: type[BaseModel], undefined_name: str = 'all referenced types') -> None:
152
+ """Set `__pydantic_core_schema__`, `__pydantic_validator__` and `__pydantic_serializer__` to mock core types on a model.
153
+
154
+ Args:
155
+ cls: The model class to set the mocks on
156
+ undefined_name: Name of the undefined thing, used in error messages
157
+ """
158
+ undefined_type_error_message = (
159
+ f'`{cls.__name__}` is not fully defined; you should define {undefined_name},'
160
+ f' then call `{cls.__name__}.model_rebuild()`.'
161
+ )
162
+
163
+ def attempt_rebuild_fn(attr_fn: Callable[[type[BaseModel]], T]) -> Callable[[], T | None]:
164
+ def handler() -> T | None:
165
+ if cls.model_rebuild(raise_errors=False, _parent_namespace_depth=5) is not False:
166
+ return attr_fn(cls)
167
+ return None
168
+
169
+ return handler
170
+
171
+ cls.__pydantic_core_schema__ = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
172
+ undefined_type_error_message,
173
+ code='class-not-fully-defined',
174
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__),
175
+ )
176
+ cls.__pydantic_validator__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
177
+ undefined_type_error_message,
178
+ code='class-not-fully-defined',
179
+ val_or_ser='validator',
180
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__),
181
+ )
182
+ cls.__pydantic_serializer__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
183
+ undefined_type_error_message,
184
+ code='class-not-fully-defined',
185
+ val_or_ser='serializer',
186
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__),
187
+ )
188
+
189
+
190
+ def set_dataclass_mocks(cls: type[PydanticDataclass], undefined_name: str = 'all referenced types') -> None:
191
+ """Set `__pydantic_validator__` and `__pydantic_serializer__` to `MockValSer`s on a dataclass.
192
+
193
+ Args:
194
+ cls: The model class to set the mocks on
195
+ undefined_name: Name of the undefined thing, used in error messages
196
+ """
197
+ from ..dataclasses import rebuild_dataclass
198
+
199
+ undefined_type_error_message = (
200
+ f'`{cls.__name__}` is not fully defined; you should define {undefined_name},'
201
+ f' then call `pydantic.dataclasses.rebuild_dataclass({cls.__name__})`.'
202
+ )
203
+
204
+ def attempt_rebuild_fn(attr_fn: Callable[[type[PydanticDataclass]], T]) -> Callable[[], T | None]:
205
+ def handler() -> T | None:
206
+ if rebuild_dataclass(cls, raise_errors=False, _parent_namespace_depth=5) is not False:
207
+ return attr_fn(cls)
208
+ return None
209
+
210
+ return handler
211
+
212
+ cls.__pydantic_core_schema__ = MockCoreSchema( # pyright: ignore[reportAttributeAccessIssue]
213
+ undefined_type_error_message,
214
+ code='class-not-fully-defined',
215
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__),
216
+ )
217
+ cls.__pydantic_validator__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
218
+ undefined_type_error_message,
219
+ code='class-not-fully-defined',
220
+ val_or_ser='validator',
221
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__),
222
+ )
223
+ cls.__pydantic_serializer__ = MockValSer( # pyright: ignore[reportAttributeAccessIssue]
224
+ undefined_type_error_message,
225
+ code='class-not-fully-defined',
226
+ val_or_ser='serializer',
227
+ attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__),
228
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_model_construction.py ADDED
@@ -0,0 +1,868 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private logic for creating models."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ import operator
6
+ import sys
7
+ import typing
8
+ import warnings
9
+ import weakref
10
+ from abc import ABCMeta
11
+ from functools import cache, partial, wraps
12
+ from types import FunctionType
13
+ from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, NoReturn, TypeVar, cast
14
+
15
+ from pydantic_core import PydanticUndefined, SchemaSerializer
16
+ from typing_extensions import TypeAliasType, dataclass_transform, deprecated, get_args, get_origin
17
+ from typing_inspection import typing_objects
18
+
19
+ from ..errors import PydanticUndefinedAnnotation, PydanticUserError
20
+ from ..plugin._schema_validator import create_schema_validator
21
+ from ..warnings import GenericBeforeBaseModelWarning, PydanticDeprecatedSince20
22
+ from ._config import ConfigWrapper
23
+ from ._decorators import DecoratorInfos, PydanticDescriptorProxy, get_attribute_from_bases, unwrap_wrapped_function
24
+ from ._fields import collect_model_fields, is_valid_field_name, is_valid_privateattr_name, rebuild_model_fields
25
+ from ._generate_schema import GenerateSchema, InvalidSchemaError
26
+ from ._generics import PydanticGenericMetadata, get_model_typevars_map
27
+ from ._import_utils import import_cached_base_model, import_cached_field_info
28
+ from ._mock_val_ser import set_model_mocks
29
+ from ._namespace_utils import NsResolver
30
+ from ._signature import generate_pydantic_signature
31
+ from ._typing_extra import (
32
+ _make_forward_ref,
33
+ eval_type_backport,
34
+ is_classvar_annotation,
35
+ parent_frame_namespace,
36
+ )
37
+ from ._utils import LazyClassAttribute, SafeGetItemProxy
38
+
39
+ if TYPE_CHECKING:
40
+ from ..fields import Field as PydanticModelField
41
+ from ..fields import FieldInfo, ModelPrivateAttr
42
+ from ..fields import PrivateAttr as PydanticModelPrivateAttr
43
+ from ..main import BaseModel
44
+ from ._fields import PydanticExtraInfo
45
+ else:
46
+ PydanticModelField = object()
47
+ PydanticModelPrivateAttr = object()
48
+
49
+ object_setattr = object.__setattr__
50
+
51
+
52
+ class _ModelNamespaceDict(dict):
53
+ """A dictionary subclass that intercepts attribute setting on model classes and
54
+ warns about overriding of decorators.
55
+ """
56
+
57
+ def __setitem__(self, k: str, v: object) -> None:
58
+ existing: Any = self.get(k, None)
59
+ if existing and v is not existing and isinstance(existing, PydanticDescriptorProxy):
60
+ warnings.warn(
61
+ f'`{k}` overrides an existing Pydantic `{existing.decorator_info.decorator_repr}` decorator',
62
+ stacklevel=2,
63
+ )
64
+
65
+ return super().__setitem__(k, v)
66
+
67
+
68
+ def NoInitField(
69
+ *,
70
+ init: Literal[False] = False,
71
+ ) -> Any:
72
+ """Only for typing purposes. Used as default value of `__pydantic_fields_set__`,
73
+ `__pydantic_extra__`, `__pydantic_private__`, so they could be ignored when
74
+ synthesizing the `__init__` signature.
75
+ """
76
+
77
+
78
+ # For ModelMetaclass.register():
79
+ _T = TypeVar('_T')
80
+
81
+
82
+ @dataclass_transform(kw_only_default=True, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr, NoInitField))
83
+ class ModelMetaclass(ABCMeta):
84
+ def __new__(
85
+ mcs,
86
+ cls_name: str,
87
+ bases: tuple[type[Any], ...],
88
+ namespace: dict[str, Any],
89
+ __pydantic_generic_metadata__: PydanticGenericMetadata | None = None,
90
+ __pydantic_reset_parent_namespace__: bool = True,
91
+ _create_model_module: str | None = None,
92
+ **kwargs: Any,
93
+ ) -> type:
94
+ """Metaclass for creating Pydantic models.
95
+
96
+ Args:
97
+ cls_name: The name of the class to be created.
98
+ bases: The base classes of the class to be created.
99
+ namespace: The attribute dictionary of the class to be created.
100
+ __pydantic_generic_metadata__: Metadata for generic models.
101
+ __pydantic_reset_parent_namespace__: Reset parent namespace.
102
+ _create_model_module: The module of the class to be created, if created by `create_model`.
103
+ **kwargs: Catch-all for any other keyword arguments.
104
+
105
+ Returns:
106
+ The new class created by the metaclass.
107
+ """
108
+ # Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we rely on the fact
109
+ # that `BaseModel` itself won't have any bases, but any subclass of it will, to determine whether the `__new__`
110
+ # call we're in the middle of is for the `BaseModel` class.
111
+ if bases:
112
+ raw_annotations: dict[str, Any]
113
+ if sys.version_info >= (3, 14):
114
+ if (
115
+ '__annotations__' in namespace
116
+ ): # `from __future__ import annotations` was used in the model's module
117
+ raw_annotations = namespace['__annotations__']
118
+ else:
119
+ # See https://docs.python.org/3.14/library/annotationlib.html#using-annotations-in-a-metaclass:
120
+ from annotationlib import Format, call_annotate_function, get_annotate_from_class_namespace
121
+
122
+ if annotate := get_annotate_from_class_namespace(namespace):
123
+ raw_annotations = call_annotate_function(annotate, format=Format.FORWARDREF)
124
+ else:
125
+ raw_annotations = {}
126
+ else:
127
+ raw_annotations = namespace.get('__annotations__', {})
128
+
129
+ base_field_names, class_vars, base_private_attributes = mcs._collect_bases_data(bases)
130
+
131
+ config_wrapper = ConfigWrapper.for_model(bases, namespace, raw_annotations, kwargs)
132
+ namespace['model_config'] = config_wrapper.config_dict
133
+ private_attributes = inspect_namespace(
134
+ namespace, raw_annotations, config_wrapper.ignored_types, class_vars, base_field_names
135
+ )
136
+ if private_attributes or base_private_attributes:
137
+ original_model_post_init = get_model_post_init(namespace, bases)
138
+ if original_model_post_init is not None:
139
+ # if there are private attributes and a model_post_init function, we handle both
140
+
141
+ @wraps(original_model_post_init)
142
+ def wrapped_model_post_init(self: BaseModel, context: Any, /) -> None:
143
+ """We need to both initialize private attributes and call the user-defined model_post_init
144
+ method.
145
+ """
146
+ init_private_attributes(self, context)
147
+ original_model_post_init(self, context)
148
+
149
+ namespace['model_post_init'] = wrapped_model_post_init
150
+ else:
151
+ namespace['model_post_init'] = init_private_attributes
152
+
153
+ namespace['__class_vars__'] = class_vars
154
+ namespace['__private_attributes__'] = {**base_private_attributes, **private_attributes}
155
+
156
+ cls = cast('type[BaseModel]', super().__new__(mcs, cls_name, bases, namespace, **kwargs))
157
+ BaseModel_ = import_cached_base_model()
158
+
159
+ mro = cls.__mro__
160
+ if Generic in mro and mro.index(Generic) < mro.index(BaseModel_):
161
+ warnings.warn(
162
+ GenericBeforeBaseModelWarning(
163
+ 'Classes should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) '
164
+ 'for pydantic generics to work properly.'
165
+ ),
166
+ stacklevel=2,
167
+ )
168
+
169
+ cls.__pydantic_custom_init__ = not getattr(cls.__init__, '__pydantic_base_init__', False)
170
+ cls.__pydantic_post_init__ = (
171
+ None if cls.model_post_init is BaseModel_.model_post_init else 'model_post_init'
172
+ )
173
+
174
+ cls.__pydantic_setattr_handlers__ = {}
175
+
176
+ cls.__pydantic_decorators__ = DecoratorInfos.build(cls, replace_wrapped_methods=True)
177
+ cls.__pydantic_decorators__.update_from_config(config_wrapper)
178
+
179
+ # Use the getattr below to grab the __parameters__ from the `typing.Generic` parent class
180
+ if __pydantic_generic_metadata__:
181
+ cls.__pydantic_generic_metadata__ = __pydantic_generic_metadata__
182
+ else:
183
+ parent_parameters = getattr(cls, '__pydantic_generic_metadata__', {}).get('parameters', ())
184
+ parameters = getattr(cls, '__parameters__', None) or parent_parameters
185
+ if parameters and parent_parameters and not all(x in parameters for x in parent_parameters):
186
+ from ..root_model import RootModelRootType
187
+
188
+ missing_parameters = tuple(x for x in parameters if x not in parent_parameters)
189
+ if RootModelRootType in parent_parameters and RootModelRootType not in parameters:
190
+ # This is a special case where the user has subclassed RootModel, but has not parameterized
191
+ # RootModel with the generic type identifiers being used. Ex:
192
+ # class MyModel(RootModel, Generic[T]):
193
+ # root: T
194
+ # Should instead just be:
195
+ # class MyModel(RootModel[T]):
196
+ # root: T
197
+ parameters_str = ', '.join([x.__name__ for x in missing_parameters])
198
+ error_message = (
199
+ f'{cls.__name__} is a subclass of `RootModel`, but does not include the generic type identifier(s) '
200
+ f'{parameters_str} in its parameters. '
201
+ f'You should parametrize RootModel directly, e.g., `class {cls.__name__}(RootModel[{parameters_str}]): ...`.'
202
+ )
203
+ else:
204
+ combined_parameters = parent_parameters + missing_parameters
205
+ parameters_str = ', '.join([str(x) for x in combined_parameters])
206
+ generic_type_label = f'typing.Generic[{parameters_str}]'
207
+ error_message = (
208
+ f'All parameters must be present on typing.Generic;'
209
+ f' you should inherit from {generic_type_label}.'
210
+ )
211
+ if Generic not in bases: # pragma: no cover
212
+ # We raise an error here not because it is desirable, but because some cases are mishandled.
213
+ # It would be nice to remove this error and still have things behave as expected, it's just
214
+ # challenging because we are using a custom `__class_getitem__` to parametrize generic models,
215
+ # and not returning a typing._GenericAlias from it.
216
+ bases_str = ', '.join([x.__name__ for x in bases] + [generic_type_label])
217
+ error_message += (
218
+ f' Note: `typing.Generic` must go last: `class {cls.__name__}({bases_str}): ...`)'
219
+ )
220
+ raise TypeError(error_message)
221
+
222
+ cls.__pydantic_generic_metadata__ = {
223
+ 'origin': None,
224
+ 'args': (),
225
+ 'parameters': parameters,
226
+ }
227
+
228
+ cls.__pydantic_complete__ = False # Ensure this specific class gets completed
229
+
230
+ # preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487
231
+ # for attributes not in `new_namespace` (e.g. private attributes)
232
+ for name, obj in private_attributes.items():
233
+ obj.__set_name__(cls, name)
234
+
235
+ if __pydantic_reset_parent_namespace__:
236
+ cls.__pydantic_parent_namespace__ = build_lenient_weakvaluedict(parent_frame_namespace())
237
+ parent_namespace: dict[str, Any] | None = getattr(cls, '__pydantic_parent_namespace__', None)
238
+ if isinstance(parent_namespace, dict):
239
+ parent_namespace = unpack_lenient_weakvaluedict(parent_namespace)
240
+
241
+ ns_resolver = NsResolver(parent_namespace=parent_namespace)
242
+
243
+ set_model_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver)
244
+
245
+ # This is also set in `complete_model_class()`, after schema gen because they are recreated.
246
+ # We set them here as well for backwards compatibility:
247
+ cls.__pydantic_computed_fields__ = {
248
+ k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()
249
+ }
250
+
251
+ if config_wrapper.defer_build:
252
+ set_model_mocks(cls)
253
+ else:
254
+ # Any operation that requires accessing the field infos instances should be put inside
255
+ # `complete_model_class()`:
256
+ complete_model_class(
257
+ cls,
258
+ config_wrapper,
259
+ ns_resolver,
260
+ raise_errors=False,
261
+ create_model_module=_create_model_module,
262
+ )
263
+
264
+ if config_wrapper.frozen and '__hash__' not in namespace:
265
+ set_default_hash_func(cls, bases)
266
+
267
+ # using super(cls, cls) on the next line ensures we only call the parent class's __pydantic_init_subclass__
268
+ # I believe the `type: ignore` is only necessary because mypy doesn't realize that this code branch is
269
+ # only hit for _proper_ subclasses of BaseModel
270
+ super(cls, cls).__pydantic_init_subclass__(**kwargs) # type: ignore[misc]
271
+ return cls
272
+ else:
273
+ # These are instance variables, but have been assigned to `NoInitField` to trick the type checker.
274
+ for instance_slot in '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__':
275
+ namespace.pop(
276
+ instance_slot,
277
+ None, # In case the metaclass is used with a class other than `BaseModel`.
278
+ )
279
+ namespace.get('__annotations__', {}).clear()
280
+ return super().__new__(mcs, cls_name, bases, namespace, **kwargs)
281
+
282
+ if not TYPE_CHECKING: # pragma: no branch
283
+ # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
284
+
285
+ def __getattr__(self, item: str) -> Any:
286
+ """This is necessary to keep attribute access working for class attribute access."""
287
+ private_attributes = self.__dict__.get('__private_attributes__')
288
+ if private_attributes and item in private_attributes:
289
+ return private_attributes[item]
290
+ raise AttributeError(item)
291
+
292
+ @classmethod
293
+ def __prepare__(cls, *args: Any, **kwargs: Any) -> dict[str, object]:
294
+ return _ModelNamespaceDict()
295
+
296
+ # Due to performance and memory issues, in the ABCMeta.__subclasscheck__ implementation, we don't support
297
+ # registered virtual subclasses. See https://github.com/python/cpython/issues/92810#issuecomment-2762454345.
298
+ # This may change once CPython is fixed (possibly in 3.15), in which case we should conditionally
299
+ # define `register()`.
300
+ def register(self, subclass: type[_T]) -> type[_T]:
301
+ warnings.warn(
302
+ f"For performance reasons, virtual subclasses registered using '{self.__qualname__}.register()' "
303
+ "are not supported in 'isinstance()' and 'issubclass()' checks.",
304
+ stacklevel=2,
305
+ )
306
+ return super().register(subclass)
307
+
308
+ __instancecheck__ = type.__instancecheck__ # pyright: ignore[reportAssignmentType]
309
+ __subclasscheck__ = type.__subclasscheck__ # pyright: ignore[reportAssignmentType]
310
+
311
+ @staticmethod
312
+ def _collect_bases_data(bases: tuple[type[Any], ...]) -> tuple[set[str], set[str], dict[str, ModelPrivateAttr]]:
313
+ BaseModel = import_cached_base_model()
314
+
315
+ field_names: set[str] = set()
316
+ class_vars: set[str] = set()
317
+ private_attributes: dict[str, ModelPrivateAttr] = {}
318
+ for base in bases:
319
+ if issubclass(base, BaseModel) and base is not BaseModel:
320
+ # model_fields might not be defined yet in the case of generics, so we use getattr here:
321
+ field_names.update(getattr(base, '__pydantic_fields__', {}).keys())
322
+ class_vars.update(base.__class_vars__)
323
+ private_attributes.update(base.__private_attributes__)
324
+ return field_names, class_vars, private_attributes
325
+
326
+ @property
327
+ @deprecated(
328
+ 'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.', category=None
329
+ )
330
+ def __fields__(self) -> dict[str, FieldInfo]:
331
+ warnings.warn(
332
+ 'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.',
333
+ PydanticDeprecatedSince20,
334
+ stacklevel=2,
335
+ )
336
+ return getattr(self, '__pydantic_fields__', {})
337
+
338
+ @property
339
+ def __pydantic_fields_complete__(self) -> bool:
340
+ """Whether the fields were successfully collected (i.e. type hints were successfully resolved).
341
+
342
+ This is a private attribute, not meant to be used outside Pydantic.
343
+ """
344
+ if '__pydantic_fields__' not in self.__dict__:
345
+ return False
346
+
347
+ field_infos = cast('dict[str, FieldInfo]', self.__pydantic_fields__) # pyright: ignore[reportAttributeAccessIssue]
348
+
349
+ pydantic_extra_info = cast('PydanticExtraInfo | None', self.__pydantic_extra_info__) # pyright: ignore[reportAttributeAccessIssue]
350
+ if pydantic_extra_info is not None:
351
+ extra_complete = pydantic_extra_info.complete
352
+ else:
353
+ extra_complete = True
354
+
355
+ return all(field_info._complete for field_info in field_infos.values()) and extra_complete
356
+
357
+ def __dir__(self) -> list[str]:
358
+ attributes = list(super().__dir__())
359
+ if '__fields__' in attributes:
360
+ attributes.remove('__fields__')
361
+ return attributes
362
+
363
+
364
+ def init_private_attributes(self: BaseModel, context: Any, /) -> None:
365
+ """This function is meant to behave like a BaseModel method to initialize private attributes.
366
+
367
+ It takes context as an argument since that's what pydantic-core passes when calling it.
368
+
369
+ Args:
370
+ self: The BaseModel instance.
371
+ context: The context.
372
+ """
373
+ if getattr(self, '__pydantic_private__', None) is None:
374
+ pydantic_private = {}
375
+ for name, private_attr in self.__private_attributes__.items():
376
+ # Avoid needlessly creating a new dict for the validated data:
377
+ if private_attr.default_factory_takes_validated_data:
378
+ default = private_attr.get_default(
379
+ call_default_factory=True, validated_data={**self.__dict__, **pydantic_private}
380
+ )
381
+ else:
382
+ default = private_attr.get_default(call_default_factory=True)
383
+ if default is not PydanticUndefined:
384
+ pydantic_private[name] = default
385
+ object_setattr(self, '__pydantic_private__', pydantic_private)
386
+
387
+
388
+ def get_model_post_init(namespace: dict[str, Any], bases: tuple[type[Any], ...]) -> Callable[..., Any] | None:
389
+ """Get the `model_post_init` method from the namespace or the class bases, or `None` if not defined."""
390
+ if 'model_post_init' in namespace:
391
+ return namespace['model_post_init']
392
+
393
+ BaseModel = import_cached_base_model()
394
+
395
+ model_post_init = get_attribute_from_bases(bases, 'model_post_init')
396
+ if model_post_init is not BaseModel.model_post_init:
397
+ return model_post_init
398
+
399
+
400
+ def inspect_namespace( # noqa C901
401
+ namespace: dict[str, Any],
402
+ raw_annotations: dict[str, Any],
403
+ ignored_types: tuple[type[Any], ...],
404
+ base_class_vars: set[str],
405
+ base_class_fields: set[str],
406
+ ) -> dict[str, ModelPrivateAttr]:
407
+ """Iterate over the namespace and:
408
+ * gather private attributes
409
+ * check for items which look like fields but are not (e.g. have no annotation) and warn.
410
+
411
+ Args:
412
+ namespace: The attribute dictionary of the class to be created.
413
+ raw_annotations: The (non-evaluated) annotations of the model.
414
+ ignored_types: A tuple of ignore types.
415
+ base_class_vars: A set of base class class variables.
416
+ base_class_fields: A set of base class fields.
417
+
418
+ Returns:
419
+ A dict containing private attributes info.
420
+
421
+ Raises:
422
+ TypeError: If there is a `__root__` field in model.
423
+ NameError: If private attribute name is invalid.
424
+ PydanticUserError:
425
+ - If a field does not have a type annotation.
426
+ - If a field on base class was overridden by a non-annotated attribute.
427
+ """
428
+ from ..fields import ModelPrivateAttr, PrivateAttr
429
+
430
+ FieldInfo = import_cached_field_info()
431
+
432
+ all_ignored_types = ignored_types + default_ignored_types()
433
+
434
+ private_attributes: dict[str, ModelPrivateAttr] = {}
435
+
436
+ if '__root__' in raw_annotations or '__root__' in namespace:
437
+ raise TypeError("To define root models, use `pydantic.RootModel` rather than a field called '__root__'")
438
+
439
+ ignored_names: set[str] = set()
440
+ for var_name, value in list(namespace.items()):
441
+ if var_name == 'model_config' or var_name == '__pydantic_extra__':
442
+ continue
443
+ elif (
444
+ isinstance(value, type)
445
+ and value.__module__ == namespace['__module__']
446
+ and '__qualname__' in namespace
447
+ and value.__qualname__.startswith(f'{namespace["__qualname__"]}.')
448
+ ):
449
+ # `value` is a nested type defined in this namespace; don't error
450
+ continue
451
+ elif isinstance(value, all_ignored_types) or value.__class__.__module__ == 'functools':
452
+ ignored_names.add(var_name)
453
+ continue
454
+ elif isinstance(value, ModelPrivateAttr):
455
+ if var_name.startswith('__'):
456
+ raise NameError(
457
+ 'Private attributes must not use dunder names;'
458
+ f' use a single underscore prefix instead of {var_name!r}.'
459
+ )
460
+ elif is_valid_field_name(var_name):
461
+ raise NameError(
462
+ 'Private attributes must not use valid field names;'
463
+ f' use sunder names, e.g. {"_" + var_name!r} instead of {var_name!r}.'
464
+ )
465
+ private_attributes[var_name] = value
466
+ del namespace[var_name]
467
+ elif isinstance(value, FieldInfo) and not is_valid_field_name(var_name):
468
+ suggested_name = var_name.lstrip('_') or 'my_field' # don't suggest '' for all-underscore name
469
+ raise NameError(
470
+ f'Fields must not use names with leading underscores;'
471
+ f' e.g., use {suggested_name!r} instead of {var_name!r}.'
472
+ )
473
+
474
+ elif var_name.startswith('__'):
475
+ continue
476
+ elif is_valid_privateattr_name(var_name):
477
+ if var_name not in raw_annotations or not is_classvar_annotation(raw_annotations[var_name]):
478
+ private_attributes[var_name] = cast(ModelPrivateAttr, PrivateAttr(default=value))
479
+ del namespace[var_name]
480
+ elif var_name in base_class_vars:
481
+ continue
482
+ elif var_name not in raw_annotations:
483
+ if var_name in base_class_fields:
484
+ raise PydanticUserError(
485
+ f'Field {var_name!r} defined on a base class was overridden by a non-annotated attribute. '
486
+ f'All field definitions, including overrides, require a type annotation.',
487
+ code='model-field-overridden',
488
+ )
489
+ elif isinstance(value, FieldInfo):
490
+ raise PydanticUserError(
491
+ f'Field {var_name!r} requires a type annotation', code='model-field-missing-annotation'
492
+ )
493
+ else:
494
+ raise PydanticUserError(
495
+ f'A non-annotated attribute was detected: `{var_name} = {value!r}`. All model fields require a '
496
+ f'type annotation; if `{var_name}` is not meant to be a field, you may be able to resolve this '
497
+ f"error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`.",
498
+ code='model-field-missing-annotation',
499
+ )
500
+
501
+ for ann_name, ann_type in raw_annotations.items():
502
+ if (
503
+ is_valid_privateattr_name(ann_name)
504
+ and ann_name not in private_attributes
505
+ and ann_name not in ignored_names
506
+ # This condition can be a false negative when `ann_type` is stringified,
507
+ # but it is handled in most cases in `set_model_fields`:
508
+ and not is_classvar_annotation(ann_type)
509
+ and ann_type not in all_ignored_types
510
+ and getattr(ann_type, '__module__', None) != 'functools'
511
+ ):
512
+ if isinstance(ann_type, str):
513
+ # Walking up the frames to get the module namespace where the model is defined
514
+ # (as the model class wasn't created yet, we unfortunately can't use `cls.__module__`):
515
+ frame = sys._getframe(2)
516
+ if frame is not None:
517
+ try:
518
+ ann_type = eval_type_backport(
519
+ _make_forward_ref(ann_type, is_argument=False, is_class=True),
520
+ globalns=frame.f_globals,
521
+ localns=frame.f_locals,
522
+ )
523
+ except (NameError, TypeError):
524
+ pass
525
+
526
+ if typing_objects.is_annotated(get_origin(ann_type)):
527
+ _, *metadata = get_args(ann_type)
528
+ private_attr = next((v for v in metadata if isinstance(v, ModelPrivateAttr)), None)
529
+ if private_attr is not None:
530
+ private_attributes[ann_name] = private_attr
531
+ continue
532
+ private_attributes[ann_name] = PrivateAttr()
533
+
534
+ return private_attributes
535
+
536
+
537
+ def set_default_hash_func(cls: type[BaseModel], bases: tuple[type[Any], ...]) -> None:
538
+ base_hash_func = get_attribute_from_bases(bases, '__hash__')
539
+ new_hash_func = make_hash_func(cls)
540
+ if base_hash_func in {None, object.__hash__} or getattr(base_hash_func, '__code__', None) == new_hash_func.__code__:
541
+ # If `__hash__` is some default, we generate a hash function.
542
+ # It will be `None` if not overridden from BaseModel.
543
+ # It may be `object.__hash__` if there is another
544
+ # parent class earlier in the bases which doesn't override `__hash__` (e.g. `typing.Generic`).
545
+ # It may be a value set by `set_default_hash_func` if `cls` is a subclass of another frozen model.
546
+ # In the last case we still need a new hash function to account for new `model_fields`.
547
+ cls.__hash__ = new_hash_func
548
+
549
+
550
+ def make_hash_func(cls: type[BaseModel]) -> Any:
551
+ getter = operator.itemgetter(*cls.__pydantic_fields__.keys()) if cls.__pydantic_fields__ else lambda _: 0
552
+
553
+ def hash_func(self: Any) -> int:
554
+ try:
555
+ return hash(getter(self.__dict__))
556
+ except KeyError:
557
+ # In rare cases (such as when using the deprecated copy method), the __dict__ may not contain
558
+ # all model fields, which is how we can get here.
559
+ # getter(self.__dict__) is much faster than any 'safe' method that accounts for missing keys,
560
+ # and wrapping it in a `try` doesn't slow things down much in the common case.
561
+ return hash(getter(SafeGetItemProxy(self.__dict__)))
562
+
563
+ return hash_func
564
+
565
+
566
+ def set_model_fields(
567
+ cls: type[BaseModel],
568
+ config_wrapper: ConfigWrapper,
569
+ ns_resolver: NsResolver,
570
+ ) -> None:
571
+ """Collect and set `cls.__pydantic_fields__` and `cls.__class_vars__`.
572
+
573
+ Args:
574
+ cls: BaseModel or dataclass.
575
+ config_wrapper: The config wrapper instance.
576
+ ns_resolver: Namespace resolver to use when getting model annotations.
577
+ """
578
+ typevars_map = get_model_typevars_map(cls)
579
+ fields, pydantic_extra_info, class_vars = collect_model_fields(
580
+ cls, config_wrapper, ns_resolver, typevars_map=typevars_map
581
+ )
582
+
583
+ cls.__pydantic_fields__ = fields
584
+ cls.__pydantic_extra_info__ = pydantic_extra_info
585
+ cls.__class_vars__.update(class_vars)
586
+
587
+ for k in class_vars:
588
+ # Class vars should not be private attributes
589
+ # We remove them _here_ and not earlier because we rely on inspecting the class to determine its classvars,
590
+ # but private attributes are determined by inspecting the namespace _prior_ to class creation.
591
+ # In the case that a classvar with a leading-'_' is defined via a ForwardRef (e.g., when using
592
+ # `__future__.annotations`), we want to remove the private attribute which was detected _before_ we knew it
593
+ # evaluated to a classvar
594
+
595
+ value = cls.__private_attributes__.pop(k, None)
596
+ if value is not None and value.default is not PydanticUndefined:
597
+ setattr(cls, k, value.default)
598
+
599
+
600
+ def complete_model_class(
601
+ cls: type[BaseModel],
602
+ config_wrapper: ConfigWrapper,
603
+ ns_resolver: NsResolver,
604
+ *,
605
+ raise_errors: bool = True,
606
+ call_on_complete_hook: bool = True,
607
+ create_model_module: str | None = None,
608
+ is_force_rebuild: bool = False,
609
+ ) -> bool:
610
+ """Finish building a model class.
611
+
612
+ This logic must be called after class has been created since validation functions must be bound
613
+ and `get_type_hints` requires a class object.
614
+
615
+ Args:
616
+ cls: BaseModel or dataclass.
617
+ config_wrapper: The config wrapper instance.
618
+ ns_resolver: The namespace resolver instance to use during schema building.
619
+ raise_errors: Whether to raise errors.
620
+ call_on_complete_hook: Whether to call the `__pydantic_on_complete__` hook.
621
+ create_model_module: The module of the class to be created, if created by `create_model`.
622
+ is_force_rebuild: Whether the model is being force-rebuilt (if True, pre-built serializers and
623
+ validators are not used, to avoid stale references).
624
+
625
+ Returns:
626
+ `True` if the model is successfully completed, else `False`.
627
+
628
+ Raises:
629
+ PydanticUndefinedAnnotation: If PydanticUndefinedAnnotation occurs in __get_pydantic_core_schema__
630
+ and `raise_errors=True`.
631
+ """
632
+ typevars_map = get_model_typevars_map(cls)
633
+
634
+ if not cls.__pydantic_fields_complete__:
635
+ # Note: when coming from `ModelMetaclass.__new__()`, this results in fields being built twice.
636
+ # We do so a second time here so that we can get the ``NameError`` for the specific undefined annotation.
637
+ # Alternatively, we could let `GenerateSchema()` raise the error, but there are cases where incomplete
638
+ # fields are inherited in `collect_model_fields()` and can actually have their annotation resolved in the
639
+ # generate schema process. As we want to avoid having `__pydantic_fields_complete__` set to `False`
640
+ # when `__pydantic_complete__` is `True`, we rebuild here:
641
+ try:
642
+ cls.__pydantic_fields__, cls.__pydantic_extra_info__ = rebuild_model_fields(
643
+ cls,
644
+ config_wrapper=config_wrapper,
645
+ ns_resolver=ns_resolver,
646
+ typevars_map=typevars_map,
647
+ )
648
+ except NameError as e:
649
+ exc = PydanticUndefinedAnnotation.from_name_error(e)
650
+ set_model_mocks(cls, f'`{exc.name}`')
651
+ if raise_errors:
652
+ raise exc from e
653
+
654
+ if not raise_errors and not cls.__pydantic_fields_complete__:
655
+ # No need to continue with schema gen, it is guaranteed to fail
656
+ return False
657
+
658
+ assert cls.__pydantic_fields_complete__
659
+
660
+ gen_schema = GenerateSchema(
661
+ config_wrapper,
662
+ ns_resolver,
663
+ typevars_map,
664
+ )
665
+
666
+ try:
667
+ schema = gen_schema.generate_schema(cls)
668
+ except PydanticUndefinedAnnotation as e:
669
+ if raise_errors:
670
+ raise
671
+ set_model_mocks(cls, f'`{e.name}`')
672
+ return False
673
+
674
+ core_config = config_wrapper.core_config(title=cls.__name__)
675
+
676
+ try:
677
+ schema = gen_schema.clean_schema(schema)
678
+ except InvalidSchemaError:
679
+ set_model_mocks(cls)
680
+ return False
681
+
682
+ # This needs to happen *after* model schema generation, as the return types
683
+ # of the properties are evaluated and the `ComputedFieldInfo` are recreated:
684
+ cls.__pydantic_computed_fields__ = {k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()}
685
+
686
+ set_deprecated_descriptors(cls)
687
+
688
+ cls.__pydantic_core_schema__ = schema
689
+
690
+ cls.__pydantic_validator__ = create_schema_validator(
691
+ schema,
692
+ cls,
693
+ create_model_module or cls.__module__,
694
+ cls.__qualname__,
695
+ 'create_model' if create_model_module else 'BaseModel',
696
+ core_config,
697
+ config_wrapper.plugin_settings,
698
+ _use_prebuilt=not is_force_rebuild,
699
+ )
700
+ cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config, _use_prebuilt=not is_force_rebuild)
701
+
702
+ # set __signature__ attr only for model class, but not for its instances
703
+ # (because instances can define `__call__`, and `inspect.signature` shouldn't
704
+ # use the `__signature__` attribute and instead generate from `__call__`).
705
+ cls.__signature__ = LazyClassAttribute(
706
+ '__signature__',
707
+ partial(
708
+ generate_pydantic_signature,
709
+ init=cls.__init__,
710
+ fields=cls.__pydantic_fields__,
711
+ validate_by_name=config_wrapper.validate_by_name,
712
+ extra=config_wrapper.extra,
713
+ ),
714
+ )
715
+
716
+ cls.__pydantic_complete__ = True
717
+
718
+ if call_on_complete_hook:
719
+ cls.__pydantic_on_complete__()
720
+
721
+ return True
722
+
723
+
724
+ def set_deprecated_descriptors(cls: type[BaseModel]) -> None:
725
+ """Set data descriptors on the class for deprecated fields."""
726
+ for field, field_info in cls.__pydantic_fields__.items():
727
+ if (msg := field_info.deprecation_message) is not None:
728
+ desc = _DeprecatedFieldDescriptor(msg)
729
+ desc.__set_name__(cls, field)
730
+ setattr(cls, field, desc)
731
+
732
+ for field, computed_field_info in cls.__pydantic_computed_fields__.items():
733
+ if (
734
+ (msg := computed_field_info.deprecation_message) is not None
735
+ # Avoid having two warnings emitted:
736
+ and not hasattr(unwrap_wrapped_function(computed_field_info.wrapped_property), '__deprecated__')
737
+ ):
738
+ desc = _DeprecatedFieldDescriptor(msg, computed_field_info.wrapped_property)
739
+ desc.__set_name__(cls, field)
740
+ setattr(cls, field, desc)
741
+
742
+
743
+ class _DeprecatedFieldDescriptor:
744
+ """Read-only data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.
745
+
746
+ Attributes:
747
+ msg: The deprecation message to be emitted.
748
+ wrapped_property: The property instance if the deprecated field is a computed field, or `None`.
749
+ field_name: The name of the field being deprecated.
750
+ """
751
+
752
+ field_name: str
753
+
754
+ def __init__(self, msg: str, wrapped_property: property | None = None) -> None:
755
+ self.msg = msg
756
+ self.wrapped_property = wrapped_property
757
+
758
+ def __set_name__(self, cls: type[BaseModel], name: str) -> None:
759
+ self.field_name = name
760
+
761
+ def __get__(self, obj: BaseModel | None, obj_type: type[BaseModel] | None = None) -> Any:
762
+ if obj is None:
763
+ if self.wrapped_property is not None:
764
+ return self.wrapped_property.__get__(None, obj_type)
765
+ raise AttributeError(self.field_name)
766
+
767
+ warnings.warn(self.msg, DeprecationWarning, stacklevel=2)
768
+
769
+ if self.wrapped_property is not None:
770
+ return self.wrapped_property.__get__(obj, obj_type)
771
+ return obj.__dict__[self.field_name]
772
+
773
+ # Defined to make it a data descriptor and take precedence over the instance's dictionary.
774
+ # Note that it will not be called when setting a value on a model instance
775
+ # as `BaseModel.__setattr__` is defined and takes priority.
776
+ def __set__(self, obj: Any, value: Any) -> NoReturn:
777
+ raise AttributeError(self.field_name)
778
+
779
+
780
+ class _PydanticWeakRef:
781
+ """Wrapper for `weakref.ref` that enables `pickle` serialization.
782
+
783
+ Cloudpickle fails to serialize weakref.ref objects due to an arcane error related to
784
+ to abstract base classes (`abc.ABC`). This class works around the issue by wrapping
785
+ `weakref.ref` instead of subclassing it.
786
+
787
+ See https://github.com/pydantic/pydantic/issues/6763 for context.
788
+
789
+ Semantics:
790
+ - If not pickled, behaves the same as a `weakref.ref`.
791
+ - If pickled along with the referenced object, the same `weakref.ref` behavior
792
+ will be maintained between them after unpickling.
793
+ - If pickled without the referenced object, after unpickling the underlying
794
+ reference will be cleared (`__call__` will always return `None`).
795
+ """
796
+
797
+ def __init__(self, obj: Any):
798
+ if obj is None:
799
+ # The object will be `None` upon deserialization if the serialized weakref
800
+ # had lost its underlying object.
801
+ self._wr = None
802
+ else:
803
+ self._wr = weakref.ref(obj)
804
+
805
+ def __call__(self) -> Any:
806
+ if self._wr is None:
807
+ return None
808
+ else:
809
+ return self._wr()
810
+
811
+ def __reduce__(self) -> tuple[Callable, tuple[weakref.ReferenceType | None]]:
812
+ return _PydanticWeakRef, (self(),)
813
+
814
+
815
+ def build_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None:
816
+ """Takes an input dictionary, and produces a new value that (invertibly) replaces the values with weakrefs.
817
+
818
+ We can't just use a WeakValueDictionary because many types (including int, str, etc.) can't be stored as values
819
+ in a WeakValueDictionary.
820
+
821
+ The `unpack_lenient_weakvaluedict` function can be used to reverse this operation.
822
+ """
823
+ if d is None:
824
+ return None
825
+ result = {}
826
+ for k, v in d.items():
827
+ try:
828
+ proxy = _PydanticWeakRef(v)
829
+ except TypeError:
830
+ proxy = v
831
+ result[k] = proxy
832
+ return result
833
+
834
+
835
+ def unpack_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None:
836
+ """Inverts the transform performed by `build_lenient_weakvaluedict`."""
837
+ if d is None:
838
+ return None
839
+
840
+ result = {}
841
+ for k, v in d.items():
842
+ if isinstance(v, _PydanticWeakRef):
843
+ v = v()
844
+ if v is not None:
845
+ result[k] = v
846
+ else:
847
+ result[k] = v
848
+ return result
849
+
850
+
851
+ @cache
852
+ def default_ignored_types() -> tuple[type[Any], ...]:
853
+ from ..fields import ComputedFieldInfo
854
+
855
+ ignored_types = [
856
+ FunctionType,
857
+ property,
858
+ classmethod,
859
+ staticmethod,
860
+ PydanticDescriptorProxy,
861
+ ComputedFieldInfo,
862
+ TypeAliasType, # from `typing_extensions`
863
+ ]
864
+
865
+ if sys.version_info >= (3, 12):
866
+ ignored_types.append(typing.TypeAliasType)
867
+
868
+ return tuple(ignored_types)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_namespace_utils.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from collections.abc import Generator, Iterator, Mapping
5
+ from contextlib import contextmanager
6
+ from functools import cached_property
7
+ from typing import Any, Callable, NamedTuple, TypeVar
8
+
9
+ from typing_extensions import ParamSpec, TypeAlias, TypeAliasType, TypeVarTuple
10
+
11
+ GlobalsNamespace: TypeAlias = 'dict[str, Any]'
12
+ """A global namespace.
13
+
14
+ In most cases, this is a reference to the `__dict__` attribute of a module.
15
+ This namespace type is expected as the `globals` argument during annotations evaluation.
16
+ """
17
+
18
+ MappingNamespace: TypeAlias = Mapping[str, Any]
19
+ """Any kind of namespace.
20
+
21
+ In most cases, this is a local namespace (e.g. the `__dict__` attribute of a class,
22
+ the [`f_locals`][frame.f_locals] attribute of a frame object, when dealing with types
23
+ defined inside functions).
24
+ This namespace type is expected as the `locals` argument during annotations evaluation.
25
+ """
26
+
27
+ _TypeVarLike: TypeAlias = 'TypeVar | ParamSpec | TypeVarTuple'
28
+
29
+
30
+ class NamespacesTuple(NamedTuple):
31
+ """A tuple of globals and locals to be used during annotations evaluation.
32
+
33
+ This datastructure is defined as a named tuple so that it can easily be unpacked:
34
+
35
+ ```python {lint="skip" test="skip"}
36
+ def eval_type(typ: type[Any], ns: NamespacesTuple) -> None:
37
+ return eval(typ, *ns)
38
+ ```
39
+ """
40
+
41
+ globals: GlobalsNamespace
42
+ """The namespace to be used as the `globals` argument during annotations evaluation."""
43
+
44
+ locals: MappingNamespace
45
+ """The namespace to be used as the `locals` argument during annotations evaluation."""
46
+
47
+
48
+ def get_module_ns_of(obj: Any) -> dict[str, Any]:
49
+ """Get the namespace of the module where the object is defined.
50
+
51
+ Caution: this function does not return a copy of the module namespace, so the result
52
+ should not be mutated. The burden of enforcing this is on the caller.
53
+ """
54
+ module_name = getattr(obj, '__module__', None)
55
+ if module_name:
56
+ try:
57
+ return sys.modules[module_name].__dict__
58
+ except KeyError:
59
+ # happens occasionally, see https://github.com/pydantic/pydantic/issues/2363
60
+ return {}
61
+ return {}
62
+
63
+
64
+ # Note that this class is almost identical to `collections.ChainMap`, but need to enforce
65
+ # immutable mappings here:
66
+ class LazyLocalNamespace(Mapping[str, Any]):
67
+ """A lazily evaluated mapping, to be used as the `locals` argument during annotations evaluation.
68
+
69
+ While the [`eval`][eval] function expects a mapping as the `locals` argument, it only
70
+ performs `__getitem__` calls. The [`Mapping`][collections.abc.Mapping] abstract base class
71
+ is fully implemented only for type checking purposes.
72
+
73
+ Args:
74
+ *namespaces: The namespaces to consider, in ascending order of priority.
75
+
76
+ Example:
77
+ ```python {lint="skip" test="skip"}
78
+ ns = LazyLocalNamespace({'a': 1, 'b': 2}, {'a': 3})
79
+ ns['a']
80
+ #> 3
81
+ ns['b']
82
+ #> 2
83
+ ```
84
+ """
85
+
86
+ def __init__(self, *namespaces: MappingNamespace) -> None:
87
+ self._namespaces = namespaces
88
+
89
+ @cached_property
90
+ def data(self) -> dict[str, Any]:
91
+ return {k: v for ns in self._namespaces for k, v in ns.items()}
92
+
93
+ def __len__(self) -> int:
94
+ return len(self.data)
95
+
96
+ def __getitem__(self, key: str) -> Any:
97
+ return self.data[key]
98
+
99
+ def __contains__(self, key: object) -> bool:
100
+ return key in self.data
101
+
102
+ def __iter__(self) -> Iterator[str]:
103
+ return iter(self.data)
104
+
105
+
106
+ def ns_for_function(obj: Callable[..., Any], parent_namespace: MappingNamespace | None = None) -> NamespacesTuple:
107
+ """Return the global and local namespaces to be used when evaluating annotations for the provided function.
108
+
109
+ The global namespace will be the `__dict__` attribute of the module the function was defined in.
110
+ The local namespace will contain the `__type_params__` introduced by PEP 695.
111
+
112
+ Args:
113
+ obj: The object to use when building namespaces.
114
+ parent_namespace: Optional namespace to be added with the lowest priority in the local namespace.
115
+ If the passed function is a method, the `parent_namespace` will be the namespace of the class
116
+ the method is defined in. Thus, we also fetch type `__type_params__` from there (i.e. the
117
+ class-scoped type variables).
118
+ """
119
+ locals_list: list[MappingNamespace] = []
120
+ if parent_namespace is not None:
121
+ locals_list.append(parent_namespace)
122
+
123
+ # Get the `__type_params__` attribute introduced by PEP 695.
124
+ # Note that the `typing._eval_type` function expects type params to be
125
+ # passed as a separate argument. However, internally, `_eval_type` calls
126
+ # `ForwardRef._evaluate` which will merge type params with the localns,
127
+ # essentially mimicking what we do here.
128
+ type_params: tuple[_TypeVarLike, ...] = getattr(obj, '__type_params__', ())
129
+ if parent_namespace is not None:
130
+ # We also fetch type params from the parent namespace. If present, it probably
131
+ # means the function was defined in a class. This is to support the following:
132
+ # https://github.com/python/cpython/issues/124089.
133
+ type_params += parent_namespace.get('__type_params__', ())
134
+
135
+ locals_list.append({t.__name__: t for t in type_params})
136
+
137
+ # What about short-circuiting to `obj.__globals__`?
138
+ globalns = get_module_ns_of(obj)
139
+
140
+ return NamespacesTuple(globalns, LazyLocalNamespace(*locals_list))
141
+
142
+
143
+ class NsResolver:
144
+ """A class responsible for the namespaces resolving logic for annotations evaluation.
145
+
146
+ This class handles the namespace logic when evaluating annotations mainly for class objects.
147
+
148
+ It holds a stack of classes that are being inspected during the core schema building,
149
+ and the `types_namespace` property exposes the globals and locals to be used for
150
+ type annotation evaluation. Additionally -- if no class is present in the stack -- a
151
+ fallback globals and locals can be provided using the `namespaces_tuple` argument
152
+ (this is useful when generating a schema for a simple annotation, e.g. when using
153
+ `TypeAdapter`).
154
+
155
+ The namespace creation logic is unfortunately flawed in some cases, for backwards
156
+ compatibility reasons and to better support valid edge cases. See the description
157
+ for the `parent_namespace` argument and the example for more details.
158
+
159
+ Args:
160
+ namespaces_tuple: The default globals and locals to use if no class is present
161
+ on the stack. This can be useful when using the `GenerateSchema` class
162
+ with `TypeAdapter`, where the "type" being analyzed is a simple annotation.
163
+ parent_namespace: An optional parent namespace that will be added to the locals
164
+ with the lowest priority. For a given class defined in a function, the locals
165
+ of this function are usually used as the parent namespace:
166
+
167
+ ```python {lint="skip" test="skip"}
168
+ from pydantic import BaseModel
169
+
170
+ def func() -> None:
171
+ SomeType = int
172
+
173
+ class Model(BaseModel):
174
+ f: 'SomeType'
175
+
176
+ # when collecting fields, an namespace resolver instance will be created
177
+ # this way:
178
+ # ns_resolver = NsResolver(parent_namespace={'SomeType': SomeType})
179
+ ```
180
+
181
+ For backwards compatibility reasons and to support valid edge cases, this parent
182
+ namespace will be used for *every* type being pushed to the stack. In the future,
183
+ we might want to be smarter by only doing so when the type being pushed is defined
184
+ in the same module as the parent namespace.
185
+
186
+ Example:
187
+ ```python {lint="skip" test="skip"}
188
+ ns_resolver = NsResolver(
189
+ parent_namespace={'fallback': 1},
190
+ )
191
+
192
+ class Sub:
193
+ m: 'Model'
194
+
195
+ class Model:
196
+ some_local = 1
197
+ sub: Sub
198
+
199
+ ns_resolver = NsResolver()
200
+
201
+ # This is roughly what happens when we build a core schema for `Model`:
202
+ with ns_resolver.push(Model):
203
+ ns_resolver.types_namespace
204
+ #> NamespacesTuple({'Sub': Sub}, {'Model': Model, 'some_local': 1})
205
+ # First thing to notice here, the model being pushed is added to the locals.
206
+ # Because `NsResolver` is being used during the model definition, it is not
207
+ # yet added to the globals. This is useful when resolving self-referencing annotations.
208
+
209
+ with ns_resolver.push(Sub):
210
+ ns_resolver.types_namespace
211
+ #> NamespacesTuple({'Sub': Sub}, {'Sub': Sub, 'Model': Model})
212
+ # Second thing to notice: `Sub` is present in both the globals and locals.
213
+ # This is not an issue, just that as described above, the model being pushed
214
+ # is added to the locals, but it happens to be present in the globals as well
215
+ # because it is already defined.
216
+ # Third thing to notice: `Model` is also added in locals. This is a backwards
217
+ # compatibility workaround that allows for `Sub` to be able to resolve `'Model'`
218
+ # correctly (as otherwise models would have to be rebuilt even though this
219
+ # doesn't look necessary).
220
+ ```
221
+ """
222
+
223
+ def __init__(
224
+ self,
225
+ namespaces_tuple: NamespacesTuple | None = None,
226
+ parent_namespace: MappingNamespace | None = None,
227
+ ) -> None:
228
+ self._base_ns_tuple = namespaces_tuple or NamespacesTuple({}, {})
229
+ self._parent_ns = parent_namespace
230
+ self._types_stack: list[type[Any] | TypeAliasType] = []
231
+
232
+ @cached_property
233
+ def types_namespace(self) -> NamespacesTuple:
234
+ """The current global and local namespaces to be used for annotations evaluation."""
235
+ if not self._types_stack:
236
+ # TODO: should we merge the parent namespace here?
237
+ # This is relevant for TypeAdapter, where there are no types on the stack, and we might
238
+ # need access to the parent_ns. Right now, we sidestep this in `type_adapter.py` by passing
239
+ # locals to both parent_ns and the base_ns_tuple, but this is a bit hacky.
240
+ # we might consider something like:
241
+ # if self._parent_ns is not None:
242
+ # # Hacky workarounds, see class docstring:
243
+ # # An optional parent namespace that will be added to the locals with the lowest priority
244
+ # locals_list: list[MappingNamespace] = [self._parent_ns, self._base_ns_tuple.locals]
245
+ # return NamespacesTuple(self._base_ns_tuple.globals, LazyLocalNamespace(*locals_list))
246
+ return self._base_ns_tuple
247
+
248
+ typ = self._types_stack[-1]
249
+
250
+ globalns = get_module_ns_of(typ)
251
+
252
+ locals_list: list[MappingNamespace] = []
253
+ # Hacky workarounds, see class docstring:
254
+ # An optional parent namespace that will be added to the locals with the lowest priority
255
+ if self._parent_ns is not None:
256
+ locals_list.append(self._parent_ns)
257
+ if len(self._types_stack) > 1:
258
+ first_type = self._types_stack[0]
259
+ locals_list.append({first_type.__name__: first_type})
260
+
261
+ # Adding `__type_params__` *before* `vars(typ)`, as the latter takes priority
262
+ # (see https://github.com/python/cpython/pull/120272).
263
+ # TODO `typ.__type_params__` when we drop support for Python 3.11:
264
+ type_params: tuple[_TypeVarLike, ...] = getattr(typ, '__type_params__', ())
265
+ if type_params:
266
+ # Adding `__type_params__` is mostly useful for generic classes defined using
267
+ # PEP 695 syntax *and* using forward annotations (see the example in
268
+ # https://github.com/python/cpython/issues/114053). For TypeAliasType instances,
269
+ # it is way less common, but still required if using a string annotation in the alias
270
+ # value, e.g. `type A[T] = 'T'` (which is not necessary in most cases).
271
+ locals_list.append({t.__name__: t for t in type_params})
272
+
273
+ # TypeAliasType instances don't have a `__dict__` attribute, so the check
274
+ # is necessary:
275
+ if hasattr(typ, '__dict__'):
276
+ locals_list.append(vars(typ))
277
+
278
+ # The `len(self._types_stack) > 1` check above prevents this from being added twice:
279
+ locals_list.append({typ.__name__: typ})
280
+
281
+ return NamespacesTuple(globalns, LazyLocalNamespace(*locals_list))
282
+
283
+ @contextmanager
284
+ def push(self, typ: type[Any] | TypeAliasType, /) -> Generator[None]:
285
+ """Push a type to the stack."""
286
+ self._types_stack.append(typ)
287
+ # Reset the cached property:
288
+ self.__dict__.pop('types_namespace', None)
289
+ try:
290
+ yield
291
+ finally:
292
+ self._types_stack.pop()
293
+ self.__dict__.pop('types_namespace', None)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_repr.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools to provide pretty/human-readable display of objects."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ import types
6
+ from collections.abc import Callable, Collection, Generator, Iterable
7
+ from typing import TYPE_CHECKING, Any, ForwardRef, cast
8
+
9
+ import typing_extensions
10
+ from typing_extensions import TypeAlias
11
+ from typing_inspection import typing_objects
12
+ from typing_inspection.introspection import is_union_origin
13
+
14
+ from . import _typing_extra
15
+
16
+ if TYPE_CHECKING:
17
+ # TODO remove type error comments when we drop support for Python 3.9
18
+ ReprArgs: TypeAlias = Iterable[tuple[str | None, Any]] # pyright: ignore[reportGeneralTypeIssues]
19
+ RichReprResult: TypeAlias = Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]] # pyright: ignore[reportGeneralTypeIssues]
20
+
21
+
22
+ class PlainRepr(str):
23
+ """String class where repr doesn't include quotes. Useful with Representation when you want to return a string
24
+ representation of something that is valid (or pseudo-valid) python.
25
+ """
26
+
27
+ def __repr__(self) -> str:
28
+ return str(self)
29
+
30
+
31
+ class Representation:
32
+ # Mixin to provide `__str__`, `__repr__`, and `__pretty__` and `__rich_repr__` methods.
33
+ # `__pretty__` is used by [devtools](https://python-devtools.helpmanual.io/).
34
+ # `__rich_repr__` is used by [rich](https://rich.readthedocs.io/en/stable/pretty.html).
35
+ # (this is not a docstring to avoid adding a docstring to classes which inherit from Representation)
36
+
37
+ __slots__ = ()
38
+
39
+ def __repr_args__(self) -> ReprArgs:
40
+ """Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
41
+
42
+ Can either return:
43
+ * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
44
+ * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
45
+ """
46
+ attrs_names = cast(Collection[str], self.__slots__)
47
+ if not attrs_names and hasattr(self, '__dict__'):
48
+ attrs_names = self.__dict__.keys()
49
+ attrs = ((s, getattr(self, s)) for s in attrs_names)
50
+ return [(a, v if v is not self else self.__repr_recursion__(v)) for a, v in attrs if v is not None]
51
+
52
+ def __repr_name__(self) -> str:
53
+ """Name of the instance's class, used in __repr__."""
54
+ return self.__class__.__name__
55
+
56
+ def __repr_recursion__(self, object: Any) -> str:
57
+ """Returns the string representation of a recursive object."""
58
+ # This is copied over from the stdlib `pprint` module:
59
+ return f'<Recursion on {type(object).__name__} with id={id(object)}>'
60
+
61
+ def __repr_str__(self, join_str: str) -> str:
62
+ return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__())
63
+
64
+ def __pretty__(self, fmt: Callable[[Any], Any], **kwargs: Any) -> Generator[Any]:
65
+ """Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects."""
66
+ yield self.__repr_name__() + '('
67
+ yield 1
68
+ for name, value in self.__repr_args__():
69
+ if name is not None:
70
+ yield name + '='
71
+ yield fmt(value)
72
+ yield ','
73
+ yield 0
74
+ yield -1
75
+ yield ')'
76
+
77
+ def __rich_repr__(self) -> RichReprResult:
78
+ """Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects."""
79
+ for name, field_repr in self.__repr_args__():
80
+ if name is None:
81
+ yield field_repr
82
+ else:
83
+ yield name, field_repr
84
+
85
+ def __str__(self) -> str:
86
+ return self.__repr_str__(' ')
87
+
88
+ def __repr__(self) -> str:
89
+ return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
90
+
91
+
92
+ def display_as_type(obj: Any) -> str:
93
+ """Pretty representation of a type, should be as close as possible to the original type definition string.
94
+
95
+ Takes some logic from `typing._type_repr`.
96
+ """
97
+ if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)):
98
+ return obj.__name__
99
+ elif obj is ...:
100
+ return '...'
101
+ elif isinstance(obj, Representation):
102
+ return repr(obj)
103
+ elif isinstance(obj, ForwardRef) or typing_objects.is_typealiastype(obj):
104
+ return str(obj)
105
+
106
+ if not isinstance(obj, (_typing_extra.typing_base, _typing_extra.WithArgsTypes, type)):
107
+ obj = obj.__class__
108
+
109
+ if is_union_origin(typing_extensions.get_origin(obj)):
110
+ args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
111
+ return f'Union[{args}]'
112
+ elif isinstance(obj, _typing_extra.WithArgsTypes):
113
+ if typing_objects.is_literal(typing_extensions.get_origin(obj)):
114
+ args = ', '.join(map(repr, typing_extensions.get_args(obj)))
115
+ else:
116
+ args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
117
+ try:
118
+ return f'{obj.__qualname__}[{args}]'
119
+ except AttributeError:
120
+ return str(obj).replace('typing.', '').replace('typing_extensions.', '') # handles TypeAliasType in 3.12
121
+ elif isinstance(obj, type):
122
+ return obj.__qualname__
123
+ else:
124
+ return repr(obj).replace('typing.', '').replace('typing_extensions.', '')
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_schema_gather.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pyright: reportTypedDictNotRequiredAccess=false, reportGeneralTypeIssues=false, reportArgumentType=false, reportAttributeAccessIssue=false
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import TypedDict
6
+
7
+ from pydantic_core.core_schema import (
8
+ ComputedField,
9
+ CoreSchema,
10
+ DefinitionReferenceSchema,
11
+ SerSchema,
12
+ iter_union_choices,
13
+ )
14
+ from typing_extensions import TypeAlias
15
+
16
+ AllSchemas: TypeAlias = 'CoreSchema | SerSchema | ComputedField'
17
+
18
+
19
+ class GatherResult(TypedDict):
20
+ """Schema traversing result."""
21
+
22
+ collected_references: dict[str, DefinitionReferenceSchema | None]
23
+ """The collected definition references.
24
+
25
+ If a definition reference schema can be inlined, it means that there is
26
+ only one in the whole core schema. As such, it is stored as the value.
27
+ Otherwise, the value is set to `None`.
28
+ """
29
+
30
+ deferred_discriminator_schemas: list[CoreSchema]
31
+ """The list of core schemas having the discriminator application deferred."""
32
+
33
+
34
+ class MissingDefinitionError(LookupError):
35
+ """A reference was pointing to a non-existing core schema."""
36
+
37
+ def __init__(self, schema_reference: str, /) -> None:
38
+ self.schema_reference = schema_reference
39
+
40
+
41
+ @dataclass
42
+ class GatherContext:
43
+ """The current context used during core schema traversing.
44
+
45
+ Context instances should only be used during schema traversing.
46
+ """
47
+
48
+ definitions: dict[str, CoreSchema]
49
+ """The available definitions."""
50
+
51
+ deferred_discriminator_schemas: list[CoreSchema] = field(init=False, default_factory=list)
52
+ """The list of core schemas having the discriminator application deferred.
53
+
54
+ Internally, these core schemas have a specific key set in the core metadata dict.
55
+ """
56
+
57
+ collected_references: dict[str, DefinitionReferenceSchema | None] = field(init=False, default_factory=dict)
58
+ """The collected definition references.
59
+
60
+ If a definition reference schema can be inlined, it means that there is
61
+ only one in the whole core schema. As such, it is stored as the value.
62
+ Otherwise, the value is set to `None`.
63
+
64
+ During schema traversing, definition reference schemas can be added as candidates, or removed
65
+ (by setting the value to `None`).
66
+ """
67
+
68
+
69
+ def traverse_metadata(schema: AllSchemas, ctx: GatherContext) -> None:
70
+ meta = schema.get('metadata')
71
+ if meta is not None and 'pydantic_internal_union_discriminator' in meta:
72
+ ctx.deferred_discriminator_schemas.append(schema) # pyright: ignore[reportArgumentType]
73
+
74
+
75
+ def traverse_definition_ref(def_ref_schema: DefinitionReferenceSchema, ctx: GatherContext) -> None:
76
+ schema_ref = def_ref_schema['schema_ref']
77
+
78
+ if schema_ref not in ctx.collected_references:
79
+ definition = ctx.definitions.get(schema_ref)
80
+ if definition is None:
81
+ raise MissingDefinitionError(schema_ref)
82
+
83
+ # The `'definition-ref'` schema was only encountered once, make it
84
+ # a candidate to be inlined:
85
+ ctx.collected_references[schema_ref] = def_ref_schema
86
+ traverse_schema(definition, ctx)
87
+ if 'serialization' in def_ref_schema:
88
+ traverse_schema(def_ref_schema['serialization'], ctx)
89
+ traverse_metadata(def_ref_schema, ctx)
90
+ else:
91
+ # The `'definition-ref'` schema was already encountered, meaning
92
+ # the previously encountered schema (and this one) can't be inlined:
93
+ ctx.collected_references[schema_ref] = None
94
+
95
+
96
+ def traverse_schema(schema: AllSchemas, context: GatherContext) -> None:
97
+ # TODO When we drop 3.9, use a match statement to get better type checking and remove
98
+ # file-level type ignore.
99
+ # (the `'type'` could also be fetched in every `if/elif` statement, but this alters performance).
100
+ schema_type = schema['type']
101
+
102
+ if schema_type == 'definition-ref':
103
+ traverse_definition_ref(schema, context)
104
+ # `traverse_definition_ref` handles the possible serialization and metadata schemas:
105
+ return
106
+ elif schema_type == 'definitions':
107
+ traverse_schema(schema['schema'], context)
108
+ for definition in schema['definitions']:
109
+ traverse_schema(definition, context)
110
+ elif schema_type in {'list', 'set', 'frozenset', 'generator'}:
111
+ if 'items_schema' in schema:
112
+ traverse_schema(schema['items_schema'], context)
113
+ elif schema_type == 'tuple':
114
+ if 'items_schema' in schema:
115
+ for s in schema['items_schema']:
116
+ traverse_schema(s, context)
117
+ elif schema_type == 'dict':
118
+ if 'keys_schema' in schema:
119
+ traverse_schema(schema['keys_schema'], context)
120
+ if 'values_schema' in schema:
121
+ traverse_schema(schema['values_schema'], context)
122
+ elif schema_type == 'union':
123
+ for choice in iter_union_choices(schema):
124
+ traverse_schema(choice, context)
125
+ elif schema_type == 'tagged-union':
126
+ for v in schema['choices'].values():
127
+ traverse_schema(v, context)
128
+ elif schema_type == 'chain':
129
+ for step in schema['steps']:
130
+ traverse_schema(step, context)
131
+ elif schema_type == 'lax-or-strict':
132
+ traverse_schema(schema['lax_schema'], context)
133
+ traverse_schema(schema['strict_schema'], context)
134
+ elif schema_type == 'json-or-python':
135
+ traverse_schema(schema['json_schema'], context)
136
+ traverse_schema(schema['python_schema'], context)
137
+ elif schema_type in {'model-fields', 'typed-dict'}:
138
+ if 'extras_schema' in schema:
139
+ traverse_schema(schema['extras_schema'], context)
140
+ if 'computed_fields' in schema:
141
+ for s in schema['computed_fields']:
142
+ traverse_schema(s, context)
143
+ for s in schema['fields'].values():
144
+ traverse_schema(s, context)
145
+ elif schema_type == 'dataclass-args':
146
+ if 'computed_fields' in schema:
147
+ for s in schema['computed_fields']:
148
+ traverse_schema(s, context)
149
+ for s in schema['fields']:
150
+ traverse_schema(s, context)
151
+ elif schema_type == 'arguments':
152
+ for s in schema['arguments_schema']:
153
+ traverse_schema(s['schema'], context)
154
+ if 'var_args_schema' in schema:
155
+ traverse_schema(schema['var_args_schema'], context)
156
+ if 'var_kwargs_schema' in schema:
157
+ traverse_schema(schema['var_kwargs_schema'], context)
158
+ elif schema_type == 'arguments-v3':
159
+ for s in schema['arguments_schema']:
160
+ traverse_schema(s['schema'], context)
161
+ elif schema_type == 'call':
162
+ traverse_schema(schema['arguments_schema'], context)
163
+ if 'return_schema' in schema:
164
+ traverse_schema(schema['return_schema'], context)
165
+ elif schema_type == 'computed-field':
166
+ traverse_schema(schema['return_schema'], context)
167
+ elif schema_type == 'function-before':
168
+ if 'schema' in schema:
169
+ traverse_schema(schema['schema'], context)
170
+ if 'json_schema_input_schema' in schema:
171
+ traverse_schema(schema['json_schema_input_schema'], context)
172
+ elif schema_type == 'function-plain':
173
+ # TODO duplicate schema types for serializers and validators, needs to be deduplicated.
174
+ if 'return_schema' in schema:
175
+ traverse_schema(schema['return_schema'], context)
176
+ if 'json_schema_input_schema' in schema:
177
+ traverse_schema(schema['json_schema_input_schema'], context)
178
+ elif schema_type == 'function-wrap':
179
+ # TODO duplicate schema types for serializers and validators, needs to be deduplicated.
180
+ if 'return_schema' in schema:
181
+ traverse_schema(schema['return_schema'], context)
182
+ if 'schema' in schema:
183
+ traverse_schema(schema['schema'], context)
184
+ if 'json_schema_input_schema' in schema:
185
+ traverse_schema(schema['json_schema_input_schema'], context)
186
+ else:
187
+ if 'schema' in schema:
188
+ traverse_schema(schema['schema'], context)
189
+
190
+ if 'serialization' in schema:
191
+ traverse_schema(schema['serialization'], context)
192
+ traverse_metadata(schema, context)
193
+
194
+
195
+ def gather_schemas_for_cleaning(schema: CoreSchema, definitions: dict[str, CoreSchema]) -> GatherResult:
196
+ """Traverse the core schema and definitions and return the necessary information for schema cleaning.
197
+
198
+ During the core schema traversing, any `'definition-ref'` schema is:
199
+
200
+ - Validated: the reference must point to an existing definition. If this is not the case, a
201
+ `MissingDefinitionError` exception is raised.
202
+ - Stored in the context: the actual reference is stored in the context. Depending on whether
203
+ the `'definition-ref'` schema is encountered more that once, the schema itself is also
204
+ saved in the context to be inlined (i.e. replaced by the definition it points to).
205
+ """
206
+ context = GatherContext(definitions)
207
+ traverse_schema(schema, context)
208
+
209
+ return {
210
+ 'collected_references': context.collected_references,
211
+ 'deferred_discriminator_schemas': context.deferred_discriminator_schemas,
212
+ }
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_schema_generation_shared.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Types and utility functions used by various other internal tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Callable, Literal
6
+
7
+ from pydantic_core import core_schema
8
+
9
+ from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
10
+
11
+ if TYPE_CHECKING:
12
+ from ..json_schema import GenerateJsonSchema, JsonSchemaValue
13
+ from ._core_utils import CoreSchemaOrField
14
+ from ._generate_schema import GenerateSchema
15
+ from ._namespace_utils import NamespacesTuple
16
+
17
+ GetJsonSchemaFunction = Callable[[CoreSchemaOrField, GetJsonSchemaHandler], JsonSchemaValue]
18
+ HandlerOverride = Callable[[CoreSchemaOrField], JsonSchemaValue]
19
+
20
+
21
+ class GenerateJsonSchemaHandler(GetJsonSchemaHandler):
22
+ """JsonSchemaHandler implementation that doesn't do ref unwrapping by default.
23
+
24
+ This is used for any Annotated metadata so that we don't end up with conflicting
25
+ modifications to the definition schema.
26
+
27
+ Used internally by Pydantic, please do not rely on this implementation.
28
+ See `GetJsonSchemaHandler` for the handler API.
29
+ """
30
+
31
+ def __init__(self, generate_json_schema: GenerateJsonSchema, handler_override: HandlerOverride | None) -> None:
32
+ self.generate_json_schema = generate_json_schema
33
+ self.handler = handler_override or generate_json_schema.generate_inner
34
+ self.mode = generate_json_schema.mode
35
+
36
+ def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
37
+ return self.handler(core_schema)
38
+
39
+ def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue:
40
+ """Resolves `$ref` in the json schema.
41
+
42
+ This returns the input json schema if there is no `$ref` in json schema.
43
+
44
+ Args:
45
+ maybe_ref_json_schema: The input json schema that may contains `$ref`.
46
+
47
+ Returns:
48
+ Resolved json schema.
49
+
50
+ Raises:
51
+ LookupError: If it can't find the definition for `$ref`.
52
+ """
53
+ if '$ref' not in maybe_ref_json_schema:
54
+ return maybe_ref_json_schema
55
+ ref = maybe_ref_json_schema['$ref']
56
+ json_schema = self.generate_json_schema.get_schema_from_definitions(ref)
57
+ if json_schema is None:
58
+ raise LookupError(
59
+ f'Could not find a ref for {ref}.'
60
+ ' Maybe you tried to call resolve_ref_schema from within a recursive model?'
61
+ )
62
+ return json_schema
63
+
64
+
65
+ class CallbackGetCoreSchemaHandler(GetCoreSchemaHandler):
66
+ """Wrapper to use an arbitrary function as a `GetCoreSchemaHandler`.
67
+
68
+ Used internally by Pydantic, please do not rely on this implementation.
69
+ See `GetCoreSchemaHandler` for the handler API.
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ handler: Callable[[Any], core_schema.CoreSchema],
75
+ generate_schema: GenerateSchema,
76
+ ref_mode: Literal['to-def', 'unpack'] = 'to-def',
77
+ ) -> None:
78
+ self._handler = handler
79
+ self._generate_schema = generate_schema
80
+ self._ref_mode = ref_mode
81
+
82
+ def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
83
+ schema = self._handler(source_type)
84
+ if self._ref_mode == 'to-def':
85
+ ref = schema.get('ref')
86
+ if ref is not None:
87
+ return self._generate_schema.defs.create_definition_reference_schema(schema)
88
+ return schema
89
+ else: # ref_mode = 'unpack'
90
+ return self.resolve_ref_schema(schema)
91
+
92
+ def _get_types_namespace(self) -> NamespacesTuple:
93
+ return self._generate_schema._types_namespace
94
+
95
+ def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
96
+ return self._generate_schema.generate_schema(source_type)
97
+
98
+ @property
99
+ def field_name(self) -> str | None:
100
+ return self._generate_schema.field_name_stack.get()
101
+
102
+ def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
103
+ """Resolves reference in the core schema.
104
+
105
+ Args:
106
+ maybe_ref_schema: The input core schema that may contains reference.
107
+
108
+ Returns:
109
+ Resolved core schema.
110
+
111
+ Raises:
112
+ LookupError: If it can't find the definition for reference.
113
+ """
114
+ if maybe_ref_schema['type'] == 'definition-ref':
115
+ ref = maybe_ref_schema['schema_ref']
116
+ definition = self._generate_schema.defs.get_schema_from_ref(ref)
117
+ if definition is None:
118
+ raise LookupError(
119
+ f'Could not find a ref for {ref}.'
120
+ ' Maybe you tried to call resolve_ref_schema from within a recursive model?'
121
+ )
122
+ return definition
123
+ elif maybe_ref_schema['type'] == 'definitions':
124
+ return self.resolve_ref_schema(maybe_ref_schema['schema'])
125
+ return maybe_ref_schema
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_serializers.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import collections.abc
5
+ import typing
6
+ from typing import Any
7
+
8
+ from pydantic_core import PydanticOmit, core_schema
9
+
10
+ SEQUENCE_ORIGIN_MAP: dict[Any, Any] = {
11
+ typing.Deque: collections.deque, # noqa: UP006
12
+ collections.deque: collections.deque,
13
+ list: list,
14
+ typing.List: list, # noqa: UP006
15
+ tuple: tuple,
16
+ typing.Tuple: tuple, # noqa: UP006
17
+ set: set,
18
+ typing.AbstractSet: set,
19
+ typing.Set: set, # noqa: UP006
20
+ frozenset: frozenset,
21
+ typing.FrozenSet: frozenset, # noqa: UP006
22
+ typing.Sequence: list,
23
+ typing.MutableSequence: list,
24
+ typing.MutableSet: set,
25
+ # this doesn't handle subclasses of these
26
+ # parametrized typing.Set creates one of these
27
+ collections.abc.MutableSet: set,
28
+ collections.abc.Set: frozenset,
29
+ }
30
+
31
+
32
+ def serialize_sequence_via_list(
33
+ v: Any, handler: core_schema.SerializerFunctionWrapHandler, info: core_schema.SerializationInfo
34
+ ) -> Any:
35
+ items: list[Any] = []
36
+
37
+ mapped_origin = SEQUENCE_ORIGIN_MAP.get(type(v), None)
38
+ if mapped_origin is None:
39
+ # we shouldn't hit this branch, should probably add a serialization error or something
40
+ return v
41
+
42
+ for index, item in enumerate(v):
43
+ try:
44
+ v = handler(item, index)
45
+ except PydanticOmit: # noqa: PERF203
46
+ pass
47
+ else:
48
+ items.append(v)
49
+
50
+ if info.mode_is_json():
51
+ return items
52
+ else:
53
+ return mapped_origin(items)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_signature.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ from inspect import Parameter, Signature
5
+ from typing import TYPE_CHECKING, Any, Callable
6
+
7
+ from pydantic_core import PydanticUndefined
8
+
9
+ from ._typing_extra import signature_no_eval
10
+ from ._utils import is_valid_identifier
11
+
12
+ if TYPE_CHECKING:
13
+ from ..config import ExtraValues
14
+ from ..fields import FieldInfo
15
+
16
+
17
+ # Copied over from stdlib dataclasses
18
+ class _HAS_DEFAULT_FACTORY_CLASS:
19
+ def __repr__(self):
20
+ return '<factory>'
21
+
22
+
23
+ _HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
24
+
25
+
26
+ def _field_name_for_signature(field_name: str, field_info: FieldInfo) -> str:
27
+ """Extract the correct name to use for the field when generating a signature.
28
+
29
+ Assuming the field has a valid alias, this will return the alias. Otherwise, it will return the field name.
30
+ First priority is given to the alias, then the validation_alias, then the field name.
31
+
32
+ Args:
33
+ field_name: The name of the field
34
+ field_info: The corresponding FieldInfo object.
35
+
36
+ Returns:
37
+ The correct name to use when generating a signature.
38
+ """
39
+ if isinstance(field_info.alias, str) and is_valid_identifier(field_info.alias):
40
+ return field_info.alias
41
+ if isinstance(field_info.validation_alias, str) and is_valid_identifier(field_info.validation_alias):
42
+ return field_info.validation_alias
43
+
44
+ return field_name
45
+
46
+
47
+ def _process_param_defaults(param: Parameter) -> Parameter:
48
+ """Modify the signature for a parameter in a dataclass where the default value is a FieldInfo instance.
49
+
50
+ Args:
51
+ param (Parameter): The parameter
52
+
53
+ Returns:
54
+ Parameter: The custom processed parameter
55
+ """
56
+ from ..fields import FieldInfo
57
+
58
+ param_default = param.default
59
+ if isinstance(param_default, FieldInfo):
60
+ annotation = param.annotation
61
+ # Replace the annotation if appropriate
62
+ # inspect does "clever" things to show annotations as strings because we have
63
+ # `from __future__ import annotations` in main, we don't want that
64
+ if annotation == 'Any':
65
+ annotation = Any
66
+
67
+ # Replace the field default
68
+ default = param_default.default
69
+ if default is PydanticUndefined:
70
+ if param_default.default_factory is None:
71
+ default = Signature.empty
72
+ else:
73
+ # this is used by dataclasses to indicate a factory exists:
74
+ default = dataclasses._HAS_DEFAULT_FACTORY # type: ignore
75
+ return param.replace(
76
+ annotation=annotation, name=_field_name_for_signature(param.name, param_default), default=default
77
+ )
78
+ return param
79
+
80
+
81
+ def _generate_signature_parameters( # noqa: C901 (ignore complexity, could use a refactor)
82
+ init: Callable[..., None],
83
+ fields: dict[str, FieldInfo],
84
+ validate_by_name: bool,
85
+ extra: ExtraValues | None,
86
+ ) -> dict[str, Parameter]:
87
+ """Generate a mapping of parameter names to Parameter objects for a pydantic BaseModel or dataclass."""
88
+ from itertools import islice
89
+
90
+ present_params = signature_no_eval(init).parameters.values()
91
+ merged_params: dict[str, Parameter] = {}
92
+ var_kw = None
93
+ use_var_kw = False
94
+
95
+ for param in islice(present_params, 1, None): # skip self arg
96
+ # inspect does "clever" things to show annotations as strings because we have
97
+ # `from __future__ import annotations` in main, we don't want that
98
+ if fields.get(param.name):
99
+ # exclude params with init=False
100
+ if getattr(fields[param.name], 'init', True) is False:
101
+ continue
102
+ param = param.replace(name=_field_name_for_signature(param.name, fields[param.name]))
103
+ if param.annotation == 'Any':
104
+ param = param.replace(annotation=Any)
105
+ if param.kind is param.VAR_KEYWORD:
106
+ var_kw = param
107
+ continue
108
+ merged_params[param.name] = param
109
+
110
+ if var_kw: # if custom init has no var_kw, fields which are not declared in it cannot be passed through
111
+ allow_names = validate_by_name
112
+ for field_name, field in fields.items():
113
+ # when alias is a str it should be used for signature generation
114
+ param_name = _field_name_for_signature(field_name, field)
115
+
116
+ if field_name in merged_params or param_name in merged_params:
117
+ continue
118
+
119
+ if not is_valid_identifier(param_name):
120
+ if allow_names:
121
+ param_name = field_name
122
+ else:
123
+ use_var_kw = True
124
+ continue
125
+
126
+ if field.is_required():
127
+ default = Parameter.empty
128
+ elif field.default_factory is not None:
129
+ # Mimics stdlib dataclasses:
130
+ default = _HAS_DEFAULT_FACTORY
131
+ else:
132
+ default = field.default
133
+ merged_params[param_name] = Parameter(
134
+ param_name,
135
+ Parameter.KEYWORD_ONLY,
136
+ annotation=field.rebuild_annotation(),
137
+ default=default,
138
+ )
139
+
140
+ if extra == 'allow':
141
+ use_var_kw = True
142
+
143
+ if var_kw and use_var_kw:
144
+ # Make sure the parameter for extra kwargs
145
+ # does not have the same name as a field
146
+ default_model_signature = [
147
+ ('self', Parameter.POSITIONAL_ONLY),
148
+ ('data', Parameter.VAR_KEYWORD),
149
+ ]
150
+ if [(p.name, p.kind) for p in present_params] == default_model_signature:
151
+ # if this is the standard model signature, use extra_data as the extra args name
152
+ var_kw_name = 'extra_data'
153
+ else:
154
+ # else start from var_kw
155
+ var_kw_name = var_kw.name
156
+
157
+ # generate a name that's definitely unique
158
+ while var_kw_name in fields:
159
+ var_kw_name += '_'
160
+ merged_params[var_kw_name] = var_kw.replace(name=var_kw_name)
161
+
162
+ return merged_params
163
+
164
+
165
+ def generate_pydantic_signature(
166
+ init: Callable[..., None],
167
+ fields: dict[str, FieldInfo],
168
+ validate_by_name: bool,
169
+ extra: ExtraValues | None,
170
+ is_dataclass: bool = False,
171
+ ) -> Signature:
172
+ """Generate signature for a pydantic BaseModel or dataclass.
173
+
174
+ Args:
175
+ init: The class init.
176
+ fields: The model fields.
177
+ validate_by_name: The `validate_by_name` value of the config.
178
+ extra: The `extra` value of the config.
179
+ is_dataclass: Whether the model is a dataclass.
180
+
181
+ Returns:
182
+ The dataclass/BaseModel subclass signature.
183
+ """
184
+ merged_params = _generate_signature_parameters(init, fields, validate_by_name, extra)
185
+
186
+ if is_dataclass:
187
+ merged_params = {k: _process_param_defaults(v) for k, v in merged_params.items()}
188
+
189
+ return Signature(parameters=list(merged_params.values()), return_annotation=None)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_typing_extra.py ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic for interacting with type annotations, mostly extensions, shims and hacks to wrap Python's typing module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections.abc
6
+ import re
7
+ import sys
8
+ import types
9
+ import typing
10
+ from functools import partial
11
+ from inspect import Signature, signature
12
+ from typing import TYPE_CHECKING, Any, Callable, cast
13
+
14
+ import typing_extensions
15
+ from typing_extensions import deprecated, get_args, get_origin
16
+ from typing_inspection import typing_objects
17
+ from typing_inspection.introspection import is_union_origin
18
+
19
+ from pydantic.version import version_short
20
+
21
+ from ._namespace_utils import GlobalsNamespace, MappingNamespace, NsResolver, get_module_ns_of
22
+
23
+ if sys.version_info < (3, 10):
24
+ NoneType = type(None)
25
+ EllipsisType = type(Ellipsis)
26
+ else:
27
+ from types import EllipsisType as EllipsisType
28
+ from types import NoneType as NoneType
29
+
30
+ if sys.version_info >= (3, 14):
31
+ import annotationlib
32
+
33
+ if TYPE_CHECKING:
34
+ from pydantic import BaseModel
35
+ from pydantic.fields import FieldInfo
36
+
37
+ # As per https://typing-extensions.readthedocs.io/en/latest/#runtime-use-of-types,
38
+ # always check for both `typing` and `typing_extensions` variants of a typing construct.
39
+ # (this is implemented differently than the suggested approach in the `typing_extensions`
40
+ # docs for performance).
41
+
42
+
43
+ _t_annotated = typing.Annotated
44
+ _te_annotated = typing_extensions.Annotated
45
+
46
+
47
+ def is_annotated(tp: Any, /) -> bool:
48
+ """Return whether the provided argument is a `Annotated` special form.
49
+
50
+ ```python {test="skip" lint="skip"}
51
+ is_annotated(Annotated[int, ...])
52
+ #> True
53
+ ```
54
+ """
55
+ origin = get_origin(tp)
56
+ return origin is _t_annotated or origin is _te_annotated
57
+
58
+
59
+ def annotated_type(tp: Any, /) -> Any | None:
60
+ """Return the type of the `Annotated` special form, or `None`."""
61
+ return tp.__origin__ if typing_objects.is_annotated(get_origin(tp)) else None
62
+
63
+
64
+ def unpack_type(tp: Any, /) -> Any | None:
65
+ """Return the type wrapped by the `Unpack` special form, or `None`."""
66
+ return get_args(tp)[0] if typing_objects.is_unpack(get_origin(tp)) else None
67
+
68
+
69
+ def is_hashable(tp: Any, /) -> bool:
70
+ """Return whether the provided argument is the `Hashable` class.
71
+
72
+ ```python {test="skip" lint="skip"}
73
+ is_hashable(Hashable)
74
+ #> True
75
+ ```
76
+ """
77
+ # `get_origin` is documented as normalizing any typing-module aliases to `collections` classes,
78
+ # hence the second check:
79
+ return tp is collections.abc.Hashable or get_origin(tp) is collections.abc.Hashable
80
+
81
+
82
+ def is_callable(tp: Any, /) -> bool:
83
+ """Return whether the provided argument is a `Callable`, parametrized or not.
84
+
85
+ ```python {test="skip" lint="skip"}
86
+ is_callable(Callable[[int], str])
87
+ #> True
88
+ is_callable(typing.Callable)
89
+ #> True
90
+ is_callable(collections.abc.Callable)
91
+ #> True
92
+ ```
93
+ """
94
+ # `get_origin` is documented as normalizing any typing-module aliases to `collections` classes,
95
+ # hence the second check:
96
+ return tp is collections.abc.Callable or get_origin(tp) is collections.abc.Callable
97
+
98
+
99
+ _classvar_re = re.compile(r'((\w+\.)?Annotated\[)?(\w+\.)?ClassVar\[')
100
+
101
+
102
+ def is_classvar_annotation(tp: Any, /) -> bool:
103
+ """Return whether the provided argument represents a class variable annotation.
104
+
105
+ Although not explicitly stated by the typing specification, `ClassVar` can be used
106
+ inside `Annotated` and as such, this function checks for this specific scenario.
107
+
108
+ Because this function is used to detect class variables before evaluating forward references
109
+ (or because evaluation failed), we also implement a naive regex match implementation. This is
110
+ required because class variables are inspected before fields are collected, so we try to be
111
+ as accurate as possible.
112
+ """
113
+ if typing_objects.is_classvar(tp):
114
+ return True
115
+
116
+ origin = get_origin(tp)
117
+
118
+ if typing_objects.is_classvar(origin):
119
+ return True
120
+
121
+ if typing_objects.is_annotated(origin):
122
+ annotated_type = tp.__origin__
123
+ if typing_objects.is_classvar(annotated_type) or typing_objects.is_classvar(get_origin(annotated_type)):
124
+ return True
125
+
126
+ str_ann: str | None = None
127
+ if isinstance(tp, typing.ForwardRef):
128
+ str_ann = tp.__forward_arg__
129
+ if isinstance(tp, str):
130
+ str_ann = tp
131
+
132
+ if str_ann is not None and _classvar_re.match(str_ann):
133
+ # stdlib dataclasses do something similar, although a bit more advanced
134
+ # (see `dataclass._is_type`).
135
+ return True
136
+
137
+ return False
138
+
139
+
140
+ _t_final = typing.Final
141
+ _te_final = typing_extensions.Final
142
+
143
+
144
+ # TODO implement `is_finalvar_annotation` as Final can be wrapped with other special forms:
145
+ def is_finalvar(tp: Any, /) -> bool:
146
+ """Return whether the provided argument is a `Final` special form, parametrized or not.
147
+
148
+ ```python {test="skip" lint="skip"}
149
+ is_finalvar(Final[int])
150
+ #> True
151
+ is_finalvar(Final)
152
+ #> True
153
+ """
154
+ # Final is not necessarily parametrized:
155
+ if tp is _t_final or tp is _te_final:
156
+ return True
157
+ origin = get_origin(tp)
158
+ return origin is _t_final or origin is _te_final
159
+
160
+
161
+ _NONE_TYPES: tuple[Any, ...] = (None, NoneType, typing.Literal[None], typing_extensions.Literal[None])
162
+
163
+
164
+ def is_none_type(tp: Any, /) -> bool:
165
+ """Return whether the argument represents the `None` type as part of an annotation.
166
+
167
+ ```python {test="skip" lint="skip"}
168
+ is_none_type(None)
169
+ #> True
170
+ is_none_type(NoneType)
171
+ #> True
172
+ is_none_type(Literal[None])
173
+ #> True
174
+ is_none_type(type[None])
175
+ #> False
176
+ """
177
+ return tp in _NONE_TYPES
178
+
179
+
180
+ def is_namedtuple(tp: Any, /) -> bool:
181
+ """Return whether the provided argument is a named tuple class.
182
+
183
+ The class can be created using `typing.NamedTuple` or `collections.namedtuple`.
184
+ Parametrized generic classes are *not* assumed to be named tuples.
185
+ """
186
+ from ._utils import lenient_issubclass # circ. import
187
+
188
+ return lenient_issubclass(tp, tuple) and hasattr(tp, '_fields')
189
+
190
+
191
+ # TODO In 2.12, delete this export. It is currently defined only to not break
192
+ # pydantic-settings which relies on it:
193
+ origin_is_union = is_union_origin
194
+
195
+
196
+ def is_generic_alias(tp: Any, /) -> bool:
197
+ return isinstance(tp, (types.GenericAlias, typing._GenericAlias)) # pyright: ignore[reportAttributeAccessIssue]
198
+
199
+
200
+ # TODO: Ideally, we should avoid relying on the private `typing` constructs:
201
+
202
+ if sys.version_info < (3, 10):
203
+ WithArgsTypes: tuple[Any, ...] = (typing._GenericAlias, types.GenericAlias) # pyright: ignore[reportAttributeAccessIssue]
204
+ else:
205
+ WithArgsTypes: tuple[Any, ...] = (typing._GenericAlias, types.GenericAlias, types.UnionType) # pyright: ignore[reportAttributeAccessIssue]
206
+
207
+
208
+ # Similarly, we shouldn't rely on this `_Final` class, which is even more private than `_GenericAlias`:
209
+ typing_base: Any = typing._Final # pyright: ignore[reportAttributeAccessIssue]
210
+
211
+
212
+ ### Annotation evaluations functions:
213
+
214
+
215
+ def parent_frame_namespace(*, parent_depth: int = 2, force: bool = False) -> dict[str, Any] | None:
216
+ """Fetch the local namespace of the parent frame where this function is called.
217
+
218
+ Using this function is mostly useful to resolve forward annotations pointing to members defined in a local namespace,
219
+ such as assignments inside a function. Using the standard library tools, it is currently not possible to resolve
220
+ such annotations:
221
+
222
+ ```python {lint="skip" test="skip"}
223
+ from typing import get_type_hints
224
+
225
+ def func() -> None:
226
+ Alias = int
227
+
228
+ class C:
229
+ a: 'Alias'
230
+
231
+ # Raises a `NameError: 'Alias' is not defined`
232
+ get_type_hints(C)
233
+ ```
234
+
235
+ Pydantic uses this function when a Pydantic model is being defined to fetch the parent frame locals. However,
236
+ this only allows us to fetch the parent frame namespace and not other parents (e.g. a model defined in a function,
237
+ itself defined in another function). Inspecting the next outer frames (using `f_back`) is not reliable enough
238
+ (see https://discuss.python.org/t/20659).
239
+
240
+ Because this function is mostly used to better resolve forward annotations, nothing is returned if the parent frame's
241
+ code object is defined at the module level. In this case, the locals of the frame will be the same as the module
242
+ globals where the class is defined (see `_namespace_utils.get_module_ns_of`). However, if you still want to fetch
243
+ the module globals (e.g. when rebuilding a model, where the frame where the rebuild call is performed might contain
244
+ members that you want to use for forward annotations evaluation), you can use the `force` parameter.
245
+
246
+ Args:
247
+ parent_depth: The depth at which to get the frame. Defaults to 2, meaning the parent frame where this function
248
+ is called will be used.
249
+ force: Whether to always return the frame locals, even if the frame's code object is defined at the module level.
250
+
251
+ Returns:
252
+ The locals of the namespace, or `None` if it was skipped as per the described logic.
253
+ """
254
+ frame = sys._getframe(parent_depth)
255
+
256
+ if frame.f_code.co_name.startswith('<generic parameters of'):
257
+ # As `parent_frame_namespace` is mostly called in `ModelMetaclass.__new__`,
258
+ # the parent frame can be the annotation scope if the PEP 695 generic syntax is used.
259
+ # (see https://docs.python.org/3/reference/executionmodel.html#annotation-scopes,
260
+ # https://docs.python.org/3/reference/compound_stmts.html#generic-classes).
261
+ # In this case, the code name is set to `<generic parameters of MyClass>`,
262
+ # and we need to skip this frame as it is irrelevant.
263
+ frame = cast(types.FrameType, frame.f_back) # guaranteed to not be `None`
264
+
265
+ # note, we don't copy frame.f_locals here (or during the last return call), because we don't expect the namespace to be
266
+ # modified down the line if this becomes a problem, we could implement some sort of frozen mapping structure to enforce this.
267
+ if force:
268
+ return frame.f_locals
269
+
270
+ # If either of the following conditions are true, the class is defined at the top module level.
271
+ # To better understand why we need both of these checks, see
272
+ # https://github.com/pydantic/pydantic/pull/10113#discussion_r1714981531.
273
+ if frame.f_back is None or frame.f_code.co_name == '<module>':
274
+ return None
275
+
276
+ return frame.f_locals
277
+
278
+
279
+ def _type_convert(arg: Any) -> Any:
280
+ """Convert `None` to `NoneType` and strings to `ForwardRef` instances.
281
+
282
+ This is a backport of the private `typing._type_convert` function. When
283
+ evaluating a type, `ForwardRef._evaluate` ends up being called, and is
284
+ responsible for making this conversion. However, we still have to apply
285
+ it for the first argument passed to our type evaluation functions, similarly
286
+ to the `typing.get_type_hints` function.
287
+ """
288
+ if arg is None:
289
+ return NoneType
290
+ if isinstance(arg, str):
291
+ # Like `typing.get_type_hints`, assume the arg can be in any context,
292
+ # hence the proper `is_argument` and `is_class` args:
293
+ return _make_forward_ref(arg, is_argument=False, is_class=True)
294
+ return arg
295
+
296
+
297
+ def safe_get_annotations(obj: Any) -> dict[str, Any]:
298
+ """Get the annotations for the provided object, accounting for potential deferred forward references.
299
+
300
+ Starting with Python 3.14, accessing the `__annotations__` attribute might raise a `NameError` if
301
+ a referenced symbol isn't defined yet. In this case, we return the annotation in the *forward ref*
302
+ format.
303
+ """
304
+ if sys.version_info >= (3, 14):
305
+ return annotationlib.get_annotations(obj, format=annotationlib.Format.FORWARDREF)
306
+ else:
307
+ # TODO just do getattr(obj, '__annotations__', {}) when dropping support for Python 3.9:
308
+ if isinstance(obj, type):
309
+ return obj.__dict__.get('__annotations__', {})
310
+ else:
311
+ return getattr(obj, '__annotations__', {})
312
+
313
+
314
+ def get_model_type_hints(
315
+ model_class: type[BaseModel],
316
+ *,
317
+ ns_resolver: NsResolver | None = None,
318
+ ) -> dict[str, tuple[Any, bool]]:
319
+ """Collect annotations from a Pydantic model class, including those from parent classes.
320
+
321
+ Args:
322
+ model_class: The Pydantic model class to inspect.
323
+ ns_resolver: A namespace resolver instance to use. Defaults to an empty instance.
324
+
325
+ Returns:
326
+ A dictionary mapping annotation names to a two-tuple: the first element is the evaluated
327
+ type or the original annotation if a `NameError` occurred, the second element is a boolean
328
+ indicating if whether the evaluation succeeded.
329
+ """
330
+ hints: dict[str, Any] | dict[str, tuple[Any, bool]] = {}
331
+ ns_resolver = ns_resolver or NsResolver()
332
+
333
+ for base in reversed(model_class.__mro__[:-1]):
334
+ # For Python 3.14, we could also use `Format.VALUE` and pass the globals/locals
335
+ # from the ns_resolver, but we want to be able to know which specific field failed
336
+ # to evaluate:
337
+ ann = safe_get_annotations(base)
338
+
339
+ if not ann:
340
+ continue
341
+
342
+ with ns_resolver.push(base):
343
+ base_model_fields: dict[str, FieldInfo] | None = base.__dict__.get('__pydantic_fields__')
344
+
345
+ for name, value in ann.items():
346
+ if name.startswith('_'):
347
+ globalns, localns = ns_resolver.types_namespace
348
+
349
+ # For private attributes, we only need the annotation to detect the `ClassVar` special form.
350
+ # For this reason, we still try to evaluate it, but we also catch any possible exception (on
351
+ # top of the `NameError`s caught in `try_eval_type`) that could happen so that users are free
352
+ # to use any kind of forward annotation for private fields (e.g. circular imports, new typing
353
+ # syntax, etc).
354
+ try:
355
+ hints[name] = try_eval_type(value, globalns, localns)
356
+ except Exception:
357
+ hints[name] = (value, False)
358
+ else:
359
+ if base_model_fields is not None and name in base_model_fields:
360
+ # Avoid unnecessarily evaluating annotations from parent models, as we'll end up
361
+ # copying the `FieldInfo` instance from it anyway if we need to.
362
+ # We use the `annotation` attribute here, but in reality could put anything here,
363
+ # As we are guaranteed to not make use of it:
364
+ hints[name] = (base_model_fields[name].annotation, True)
365
+ else:
366
+ globalns, localns = ns_resolver.types_namespace
367
+
368
+ hints[name] = try_eval_type(value, globalns, localns)
369
+
370
+ return hints
371
+
372
+
373
+ def get_cls_type_hints(
374
+ obj: type[Any],
375
+ *,
376
+ ns_resolver: NsResolver | None = None,
377
+ ) -> dict[str, Any]:
378
+ """Collect annotations from a class, including those from parent classes.
379
+
380
+ Args:
381
+ obj: The class to inspect.
382
+ ns_resolver: A namespace resolver instance to use. Defaults to an empty instance.
383
+ """
384
+ hints: dict[str, Any] = {}
385
+ ns_resolver = ns_resolver or NsResolver()
386
+
387
+ for base in reversed(obj.__mro__):
388
+ # For Python 3.14, we could also use `Format.VALUE` and pass the globals/locals
389
+ # from the ns_resolver, but we want to be able to know which specific field failed
390
+ # to evaluate:
391
+ ann = safe_get_annotations(base)
392
+
393
+ if not ann:
394
+ continue
395
+
396
+ with ns_resolver.push(base):
397
+ globalns, localns = ns_resolver.types_namespace
398
+ for name, value in ann.items():
399
+ hints[name] = eval_type(value, globalns, localns)
400
+ return hints
401
+
402
+
403
+ def try_eval_type(
404
+ value: Any,
405
+ globalns: GlobalsNamespace | None = None,
406
+ localns: MappingNamespace | None = None,
407
+ ) -> tuple[Any, bool]:
408
+ """Try evaluating the annotation using the provided namespaces.
409
+
410
+ Args:
411
+ value: The value to evaluate. If `None`, it will be replaced by `type[None]`. If an instance
412
+ of `str`, it will be converted to a `ForwardRef`.
413
+ localns: The global namespace to use during annotation evaluation.
414
+ globalns: The local namespace to use during annotation evaluation.
415
+
416
+ Returns:
417
+ A two-tuple containing the possibly evaluated type and a boolean indicating
418
+ whether the evaluation succeeded or not.
419
+ """
420
+ value = _type_convert(value)
421
+
422
+ try:
423
+ return eval_type_backport(value, globalns, localns), True
424
+ except NameError:
425
+ return value, False
426
+
427
+
428
+ def eval_type(
429
+ value: Any,
430
+ globalns: GlobalsNamespace | None = None,
431
+ localns: MappingNamespace | None = None,
432
+ ) -> Any:
433
+ """Evaluate the annotation using the provided namespaces.
434
+
435
+ Args:
436
+ value: The value to evaluate. If `None`, it will be replaced by `type[None]`. If an instance
437
+ of `str`, it will be converted to a `ForwardRef`.
438
+ localns: The global namespace to use during annotation evaluation.
439
+ globalns: The local namespace to use during annotation evaluation.
440
+ """
441
+ value = _type_convert(value)
442
+ return eval_type_backport(value, globalns, localns)
443
+
444
+
445
+ @deprecated(
446
+ '`eval_type_lenient` is deprecated, use `try_eval_type` instead.',
447
+ category=None,
448
+ )
449
+ def eval_type_lenient(
450
+ value: Any,
451
+ globalns: GlobalsNamespace | None = None,
452
+ localns: MappingNamespace | None = None,
453
+ ) -> Any:
454
+ ev, _ = try_eval_type(value, globalns, localns)
455
+ return ev
456
+
457
+
458
+ def eval_type_backport(
459
+ value: Any,
460
+ globalns: GlobalsNamespace | None = None,
461
+ localns: MappingNamespace | None = None,
462
+ type_params: tuple[Any, ...] | None = None,
463
+ ) -> Any:
464
+ """An enhanced version of `typing._eval_type` which will fall back to using the `eval_type_backport`
465
+ package if it's installed to let older Python versions use newer typing constructs.
466
+
467
+ Specifically, this transforms `X | Y` into `typing.Union[X, Y]` and `list[X]` into `typing.List[X]`
468
+ (as well as all the types made generic in PEP 585) if the original syntax is not supported in the
469
+ current Python version.
470
+
471
+ This function will also display a helpful error if the value passed fails to evaluate.
472
+ """
473
+ try:
474
+ return _eval_type_backport(value, globalns, localns, type_params)
475
+ except TypeError as e:
476
+ if 'Unable to evaluate type annotation' in str(e):
477
+ raise
478
+
479
+ # If it is a `TypeError` and value isn't a `ForwardRef`, it would have failed during annotation definition.
480
+ # Thus we assert here for type checking purposes:
481
+ assert isinstance(value, typing.ForwardRef)
482
+
483
+ message = f'Unable to evaluate type annotation {value.__forward_arg__!r}.'
484
+ if sys.version_info >= (3, 11):
485
+ e.add_note(message)
486
+ raise
487
+ else:
488
+ raise TypeError(message) from e
489
+ except RecursionError as e:
490
+ # TODO ideally recursion errors should be checked in `eval_type` above, but `eval_type_backport`
491
+ # is used directly in some places.
492
+ message = (
493
+ "If you made use of an implicit recursive type alias (e.g. `MyType = list['MyType']), "
494
+ 'consider using PEP 695 type aliases instead. For more details, refer to the documentation: '
495
+ f'https://docs.pydantic.dev/{version_short()}/concepts/types/#named-recursive-types'
496
+ )
497
+ if sys.version_info >= (3, 11):
498
+ e.add_note(message)
499
+ raise
500
+ else:
501
+ raise RecursionError(f'{e.args[0]}\n{message}')
502
+
503
+
504
+ def _eval_type_backport(
505
+ value: Any,
506
+ globalns: GlobalsNamespace | None = None,
507
+ localns: MappingNamespace | None = None,
508
+ type_params: tuple[Any, ...] | None = None,
509
+ ) -> Any:
510
+ try:
511
+ return _eval_type(value, globalns, localns, type_params)
512
+ except TypeError as e:
513
+ if not (isinstance(value, typing.ForwardRef) and is_backport_fixable_error(e)):
514
+ raise
515
+
516
+ try:
517
+ from eval_type_backport import eval_type_backport
518
+ except ImportError:
519
+ raise TypeError(
520
+ f'Unable to evaluate type annotation {value.__forward_arg__!r}. If you are making use '
521
+ 'of the new typing syntax (unions using `|` since Python 3.10 or builtins subscripting '
522
+ 'since Python 3.9), you should either replace the use of new syntax with the existing '
523
+ '`typing` constructs or install the `eval_type_backport` package.'
524
+ ) from e
525
+
526
+ return eval_type_backport(
527
+ value,
528
+ globalns,
529
+ localns, # pyright: ignore[reportArgumentType], waiting on a new `eval_type_backport` release.
530
+ try_default=False,
531
+ )
532
+
533
+
534
+ def _eval_type(
535
+ value: Any,
536
+ globalns: GlobalsNamespace | None = None,
537
+ localns: MappingNamespace | None = None,
538
+ type_params: tuple[Any, ...] | None = None,
539
+ ) -> Any:
540
+ if sys.version_info >= (3, 14):
541
+ # Starting in 3.14, `_eval_type()` does *not* apply `_type_convert()`
542
+ # anymore. This means the `None` -> `type(None)` conversion does not apply:
543
+ evaluated = typing._eval_type( # type: ignore
544
+ value,
545
+ globalns,
546
+ localns,
547
+ type_params=type_params,
548
+ # This is relevant when evaluating types from `TypedDict` classes, where string annotations
549
+ # are automatically converted to `ForwardRef` instances with a module set. In this case,
550
+ # Our `globalns` is irrelevant and we need to indicate `typing._eval_type()` that it should
551
+ # infer it from the `ForwardRef.__forward_module__` attribute instead (`typing.get_type_hints()`
552
+ # does the same). Note that this would probably be unnecessary if we properly iterated over the
553
+ # `__orig_bases__` for TypedDicts in `get_cls_type_hints()`:
554
+ prefer_fwd_module=True,
555
+ )
556
+ if evaluated is None:
557
+ evaluated = type(None)
558
+ return evaluated
559
+ elif sys.version_info >= (3, 13):
560
+ return typing._eval_type( # type: ignore
561
+ value, globalns, localns, type_params=type_params
562
+ )
563
+ else:
564
+ return typing._eval_type( # type: ignore
565
+ value, globalns, localns
566
+ )
567
+
568
+
569
+ def is_backport_fixable_error(e: TypeError) -> bool:
570
+ msg = str(e)
571
+
572
+ return sys.version_info < (3, 10) and msg.startswith('unsupported operand type(s) for |: ')
573
+
574
+
575
+ def signature_no_eval(f: Callable[..., Any]) -> Signature:
576
+ """Get the signature of a callable without evaluating any annotations."""
577
+ if sys.version_info >= (3, 14):
578
+ from annotationlib import Format
579
+
580
+ return signature(f, annotation_format=Format.FORWARDREF)
581
+ else:
582
+ return signature(f)
583
+
584
+
585
+ def get_function_type_hints(
586
+ function: Callable[..., Any],
587
+ *,
588
+ include_keys: set[str] | None = None,
589
+ globalns: GlobalsNamespace | None = None,
590
+ localns: MappingNamespace | None = None,
591
+ ) -> dict[str, Any]:
592
+ """Return type hints for a function.
593
+
594
+ This is similar to the `typing.get_type_hints` function, with a few differences:
595
+ - Support `functools.partial` by using the underlying `func` attribute.
596
+ - Do not wrap type annotation of a parameter with `Optional` if it has a default value of `None`
597
+ (related bug: https://github.com/python/cpython/issues/90353, only fixed in 3.11+).
598
+ """
599
+ if isinstance(function, partial):
600
+ annotations = safe_get_annotations(function.func)
601
+ else:
602
+ annotations = safe_get_annotations(function)
603
+
604
+ if globalns is None:
605
+ globalns = get_module_ns_of(function)
606
+ type_params: tuple[Any, ...] | None = None
607
+ if localns is None:
608
+ # If localns was specified, it is assumed to already contain type params. This is because
609
+ # Pydantic has more advanced logic to do so (see `_namespace_utils.ns_for_function`).
610
+ type_params = getattr(function, '__type_params__', ())
611
+
612
+ type_hints = {}
613
+ for name, value in annotations.items():
614
+ if include_keys is not None and name not in include_keys:
615
+ continue
616
+ if value is None:
617
+ value = NoneType
618
+ elif isinstance(value, str):
619
+ value = _make_forward_ref(value)
620
+
621
+ type_hints[name] = eval_type_backport(value, globalns, localns, type_params)
622
+
623
+ return type_hints
624
+
625
+
626
+ # TODO use typing.ForwardRef directly when we stop supporting 3.9:
627
+ if sys.version_info < (3, 9, 8) or (3, 10) <= sys.version_info < (3, 10, 1):
628
+
629
+ def _make_forward_ref(
630
+ arg: Any,
631
+ is_argument: bool = True,
632
+ *,
633
+ is_class: bool = False,
634
+ ) -> typing.ForwardRef:
635
+ """Wrapper for ForwardRef that accounts for the `is_class` argument missing in older versions.
636
+ The `module` argument is omitted as it breaks <3.9.8, =3.10.0 and isn't used in the calls below.
637
+
638
+ See https://github.com/python/cpython/pull/28560 for some background.
639
+ The backport happened on 3.9.8, see:
640
+ https://github.com/pydantic/pydantic/discussions/6244#discussioncomment-6275458,
641
+ and on 3.10.1 for the 3.10 branch, see:
642
+ https://github.com/pydantic/pydantic/issues/6912
643
+
644
+ Implemented as EAFP with memory.
645
+ """
646
+ return typing.ForwardRef(arg, is_argument) # pyright: ignore[reportCallIssue]
647
+
648
+ else:
649
+ _make_forward_ref = typing.ForwardRef # pyright: ignore[reportAssignmentType]
650
+
651
+
652
+ if sys.version_info >= (3, 10):
653
+ get_type_hints = typing.get_type_hints
654
+
655
+ else:
656
+ """
657
+ For older versions of python, we have a custom implementation of `get_type_hints` which is a close as possible to
658
+ the implementation in CPython 3.10.8.
659
+ """
660
+
661
+ @typing.no_type_check
662
+ def get_type_hints( # noqa: C901
663
+ obj: Any,
664
+ globalns: dict[str, Any] | None = None,
665
+ localns: dict[str, Any] | None = None,
666
+ include_extras: bool = False,
667
+ ) -> dict[str, Any]: # pragma: no cover
668
+ """Taken verbatim from python 3.10.8 unchanged, except:
669
+ * type annotations of the function definition above.
670
+ * prefixing `typing.` where appropriate
671
+ * Use `_make_forward_ref` instead of `typing.ForwardRef` to handle the `is_class` argument.
672
+
673
+ https://github.com/python/cpython/blob/aaaf5174241496afca7ce4d4584570190ff972fe/Lib/typing.py#L1773-L1875
674
+
675
+ DO NOT CHANGE THIS METHOD UNLESS ABSOLUTELY NECESSARY.
676
+ ======================================================
677
+
678
+ Return type hints for an object.
679
+
680
+ This is often the same as obj.__annotations__, but it handles
681
+ forward references encoded as string literals, adds Optional[t] if a
682
+ default value equal to None is set and recursively replaces all
683
+ 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
684
+
685
+ The argument may be a module, class, method, or function. The annotations
686
+ are returned as a dictionary. For classes, annotations include also
687
+ inherited members.
688
+
689
+ TypeError is raised if the argument is not of a type that can contain
690
+ annotations, and an empty dictionary is returned if no annotations are
691
+ present.
692
+
693
+ BEWARE -- the behavior of globalns and localns is counterintuitive
694
+ (unless you are familiar with how eval() and exec() work). The
695
+ search order is locals first, then globals.
696
+
697
+ - If no dict arguments are passed, an attempt is made to use the
698
+ globals from obj (or the respective module's globals for classes),
699
+ and these are also used as the locals. If the object does not appear
700
+ to have globals, an empty dictionary is used. For classes, the search
701
+ order is globals first then locals.
702
+
703
+ - If one dict argument is passed, it is used for both globals and
704
+ locals.
705
+
706
+ - If two dict arguments are passed, they specify globals and
707
+ locals, respectively.
708
+ """
709
+ if getattr(obj, '__no_type_check__', None):
710
+ return {}
711
+ # Classes require a special treatment.
712
+ if isinstance(obj, type):
713
+ hints = {}
714
+ for base in reversed(obj.__mro__):
715
+ if globalns is None:
716
+ base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {})
717
+ else:
718
+ base_globals = globalns
719
+ ann = base.__dict__.get('__annotations__', {})
720
+ if isinstance(ann, types.GetSetDescriptorType):
721
+ ann = {}
722
+ base_locals = dict(vars(base)) if localns is None else localns
723
+ if localns is None and globalns is None:
724
+ # This is surprising, but required. Before Python 3.10,
725
+ # get_type_hints only evaluated the globalns of
726
+ # a class. To maintain backwards compatibility, we reverse
727
+ # the globalns and localns order so that eval() looks into
728
+ # *base_globals* first rather than *base_locals*.
729
+ # This only affects ForwardRefs.
730
+ base_globals, base_locals = base_locals, base_globals
731
+ for name, value in ann.items():
732
+ if value is None:
733
+ value = type(None)
734
+ if isinstance(value, str):
735
+ value = _make_forward_ref(value, is_argument=False, is_class=True)
736
+
737
+ value = eval_type_backport(value, base_globals, base_locals)
738
+ hints[name] = value
739
+ if not include_extras and hasattr(typing, '_strip_annotations'):
740
+ return {
741
+ k: typing._strip_annotations(t) # type: ignore
742
+ for k, t in hints.items()
743
+ }
744
+ else:
745
+ return hints
746
+
747
+ if globalns is None:
748
+ if isinstance(obj, types.ModuleType):
749
+ globalns = obj.__dict__
750
+ else:
751
+ nsobj = obj
752
+ # Find globalns for the unwrapped object.
753
+ while hasattr(nsobj, '__wrapped__'):
754
+ nsobj = nsobj.__wrapped__
755
+ globalns = getattr(nsobj, '__globals__', {})
756
+ if localns is None:
757
+ localns = globalns
758
+ elif localns is None:
759
+ localns = globalns
760
+ hints = getattr(obj, '__annotations__', None)
761
+ if hints is None:
762
+ # Return empty annotations for something that _could_ have them.
763
+ if isinstance(obj, typing._allowed_types): # type: ignore
764
+ return {}
765
+ else:
766
+ raise TypeError(f'{obj!r} is not a module, class, method, or function.')
767
+ defaults = typing._get_defaults(obj) # type: ignore
768
+ hints = dict(hints)
769
+ for name, value in hints.items():
770
+ if value is None:
771
+ value = type(None)
772
+ if isinstance(value, str):
773
+ # class-level forward refs were handled above, this must be either
774
+ # a module-level annotation or a function argument annotation
775
+
776
+ value = _make_forward_ref(
777
+ value,
778
+ is_argument=not isinstance(obj, types.ModuleType),
779
+ is_class=False,
780
+ )
781
+ value = eval_type_backport(value, globalns, localns)
782
+ if name in defaults and defaults[name] is None:
783
+ value = typing.Optional[value]
784
+ hints[name] = value
785
+ return hints if include_extras else {k: typing._strip_annotations(t) for k, t in hints.items()} # type: ignore
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_utils.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bucket of reusable internal utilities.
2
+
3
+ This should be reduced as much as possible with functions only used in one place, moved to that place.
4
+ """
5
+
6
+ from __future__ import annotations as _annotations
7
+
8
+ import dataclasses
9
+ import keyword
10
+ import sys
11
+ import warnings
12
+ import weakref
13
+ from collections import OrderedDict, defaultdict, deque
14
+ from collections.abc import Callable, Iterable, Mapping
15
+ from collections.abc import Set as AbstractSet
16
+ from copy import deepcopy
17
+ from functools import cached_property
18
+ from inspect import Parameter
19
+ from itertools import zip_longest
20
+ from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType
21
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar, overload
22
+
23
+ from pydantic_core import MISSING, PydanticUndefined
24
+ from typing_extensions import TypeAlias, TypeGuard, deprecated
25
+
26
+ from pydantic import PydanticDeprecatedSince211
27
+
28
+ from . import _repr, _typing_extra
29
+ from ._import_utils import import_cached_base_model
30
+
31
+ if TYPE_CHECKING:
32
+ # TODO remove type error comments when we drop support for Python 3.9
33
+ MappingIntStrAny: TypeAlias = Mapping[int, Any] | Mapping[str, Any] # pyright: ignore[reportGeneralTypeIssues]
34
+ AbstractSetIntStr: TypeAlias = AbstractSet[int] | AbstractSet[str] # pyright: ignore[reportGeneralTypeIssues]
35
+ from ..main import BaseModel
36
+
37
+
38
+ # these are types that are returned unchanged by deepcopy
39
+ IMMUTABLE_NON_COLLECTIONS_TYPES: set[type[Any]] = {
40
+ int,
41
+ float,
42
+ complex,
43
+ str,
44
+ bool,
45
+ bytes,
46
+ type,
47
+ _typing_extra.NoneType,
48
+ FunctionType,
49
+ BuiltinFunctionType,
50
+ LambdaType,
51
+ weakref.ref,
52
+ CodeType,
53
+ # note: including ModuleType will differ from behaviour of deepcopy by not producing error.
54
+ # It might be not a good idea in general, but considering that this function used only internally
55
+ # against default values of fields, this will allow to actually have a field with module as default value
56
+ ModuleType,
57
+ NotImplemented.__class__,
58
+ Ellipsis.__class__,
59
+ }
60
+
61
+ # these are types that if empty, might be copied with simple copy() instead of deepcopy()
62
+ BUILTIN_COLLECTIONS: set[type[Any]] = {
63
+ list,
64
+ set,
65
+ tuple,
66
+ frozenset,
67
+ dict,
68
+ OrderedDict,
69
+ defaultdict,
70
+ deque,
71
+ }
72
+
73
+
74
+ def can_be_positional(param: Parameter) -> bool:
75
+ """Return whether the parameter accepts a positional argument.
76
+
77
+ ```python {test="skip" lint="skip"}
78
+ def func(a, /, b, *, c):
79
+ pass
80
+
81
+ params = inspect.signature(func).parameters
82
+ can_be_positional(params['a'])
83
+ #> True
84
+ can_be_positional(params['b'])
85
+ #> True
86
+ can_be_positional(params['c'])
87
+ #> False
88
+ ```
89
+ """
90
+ return param.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD)
91
+
92
+
93
+ def sequence_like(v: Any) -> bool:
94
+ return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque))
95
+
96
+
97
+ def lenient_isinstance(o: Any, class_or_tuple: type[Any] | tuple[type[Any], ...] | None) -> bool: # pragma: no cover
98
+ try:
99
+ return isinstance(o, class_or_tuple) # type: ignore[arg-type]
100
+ except TypeError:
101
+ return False
102
+
103
+
104
+ def lenient_issubclass(cls: Any, class_or_tuple: Any) -> bool: # pragma: no cover
105
+ try:
106
+ return isinstance(cls, type) and issubclass(cls, class_or_tuple)
107
+ except TypeError:
108
+ if isinstance(cls, _typing_extra.WithArgsTypes):
109
+ return False
110
+ raise # pragma: no cover
111
+
112
+
113
+ def is_model_class(cls: Any) -> TypeGuard[type[BaseModel]]:
114
+ """Returns true if cls is a _proper_ subclass of BaseModel, and provides proper type-checking,
115
+ unlike raw calls to lenient_issubclass.
116
+ """
117
+ BaseModel = import_cached_base_model()
118
+
119
+ return lenient_issubclass(cls, BaseModel) and cls is not BaseModel
120
+
121
+
122
+ def is_valid_identifier(identifier: str) -> bool:
123
+ """Checks that a string is a valid identifier and not a Python keyword.
124
+ :param identifier: The identifier to test.
125
+ :return: True if the identifier is valid.
126
+ """
127
+ return identifier.isidentifier() and not keyword.iskeyword(identifier)
128
+
129
+
130
+ KeyType = TypeVar('KeyType')
131
+
132
+
133
+ def deep_update(mapping: dict[KeyType, Any], *updating_mappings: dict[KeyType, Any]) -> dict[KeyType, Any]:
134
+ updated_mapping = mapping.copy()
135
+ for updating_mapping in updating_mappings:
136
+ for k, v in updating_mapping.items():
137
+ if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict):
138
+ updated_mapping[k] = deep_update(updated_mapping[k], v)
139
+ else:
140
+ updated_mapping[k] = v
141
+ return updated_mapping
142
+
143
+
144
+ def update_not_none(mapping: dict[Any, Any], **update: Any) -> None:
145
+ mapping.update({k: v for k, v in update.items() if v is not None})
146
+
147
+
148
+ T = TypeVar('T')
149
+
150
+
151
+ def unique_list(
152
+ input_list: list[T] | tuple[T, ...],
153
+ *,
154
+ name_factory: Callable[[T], str] = str,
155
+ ) -> list[T]:
156
+ """Make a list unique while maintaining order.
157
+ We update the list if another one with the same name is set
158
+ (e.g. model validator overridden in subclass).
159
+ """
160
+ result: list[T] = []
161
+ result_names: list[str] = []
162
+ for v in input_list:
163
+ v_name = name_factory(v)
164
+ if v_name not in result_names:
165
+ result_names.append(v_name)
166
+ result.append(v)
167
+ else:
168
+ result[result_names.index(v_name)] = v
169
+
170
+ return result
171
+
172
+
173
+ class ValueItems(_repr.Representation):
174
+ """Class for more convenient calculation of excluded or included fields on values."""
175
+
176
+ __slots__ = ('_items', '_type')
177
+
178
+ def __init__(self, value: Any, items: AbstractSetIntStr | MappingIntStrAny) -> None:
179
+ items = self._coerce_items(items)
180
+
181
+ if isinstance(value, (list, tuple)):
182
+ items = self._normalize_indexes(items, len(value)) # type: ignore
183
+
184
+ self._items: MappingIntStrAny = items # type: ignore
185
+
186
+ def is_excluded(self, item: Any) -> bool:
187
+ """Check if item is fully excluded.
188
+
189
+ :param item: key or index of a value
190
+ """
191
+ return self.is_true(self._items.get(item))
192
+
193
+ def is_included(self, item: Any) -> bool:
194
+ """Check if value is contained in self._items.
195
+
196
+ :param item: key or index of value
197
+ """
198
+ return item in self._items
199
+
200
+ def for_element(self, e: int | str) -> AbstractSetIntStr | MappingIntStrAny | None:
201
+ """:param e: key or index of element on value
202
+ :return: raw values for element if self._items is dict and contain needed element
203
+ """
204
+ item = self._items.get(e) # type: ignore
205
+ return item if not self.is_true(item) else None
206
+
207
+ def _normalize_indexes(self, items: MappingIntStrAny, v_length: int) -> dict[int | str, Any]:
208
+ """:param items: dict or set of indexes which will be normalized
209
+ :param v_length: length of sequence indexes of which will be
210
+
211
+ >>> self._normalize_indexes({0: True, -2: True, -1: True}, 4)
212
+ {0: True, 2: True, 3: True}
213
+ >>> self._normalize_indexes({'__all__': True}, 4)
214
+ {0: True, 1: True, 2: True, 3: True}
215
+ """
216
+ normalized_items: dict[int | str, Any] = {}
217
+ all_items = None
218
+ for i, v in items.items():
219
+ if not (isinstance(v, Mapping) or isinstance(v, AbstractSet) or self.is_true(v)):
220
+ raise TypeError(f'Unexpected type of exclude value for index "{i}" {v.__class__}')
221
+ if i == '__all__':
222
+ all_items = self._coerce_value(v)
223
+ continue
224
+ if not isinstance(i, int):
225
+ raise TypeError(
226
+ 'Excluding fields from a sequence of sub-models or dicts must be performed index-wise: '
227
+ 'expected integer keys or keyword "__all__"'
228
+ )
229
+ normalized_i = v_length + i if i < 0 else i
230
+ normalized_items[normalized_i] = self.merge(v, normalized_items.get(normalized_i))
231
+
232
+ if not all_items:
233
+ return normalized_items
234
+ if self.is_true(all_items):
235
+ for i in range(v_length):
236
+ normalized_items.setdefault(i, ...)
237
+ return normalized_items
238
+ for i in range(v_length):
239
+ normalized_item = normalized_items.setdefault(i, {})
240
+ if not self.is_true(normalized_item):
241
+ normalized_items[i] = self.merge(all_items, normalized_item)
242
+ return normalized_items
243
+
244
+ @classmethod
245
+ def merge(cls, base: Any, override: Any, intersect: bool = False) -> Any:
246
+ """Merge a `base` item with an `override` item.
247
+
248
+ Both `base` and `override` are converted to dictionaries if possible.
249
+ Sets are converted to dictionaries with the sets entries as keys and
250
+ Ellipsis as values.
251
+
252
+ Each key-value pair existing in `base` is merged with `override`,
253
+ while the rest of the key-value pairs are updated recursively with this function.
254
+
255
+ Merging takes place based on the "union" of keys if `intersect` is
256
+ set to `False` (default) and on the intersection of keys if
257
+ `intersect` is set to `True`.
258
+ """
259
+ override = cls._coerce_value(override)
260
+ base = cls._coerce_value(base)
261
+ if override is None:
262
+ return base
263
+ if cls.is_true(base) or base is None:
264
+ return override
265
+ if cls.is_true(override):
266
+ return base if intersect else override
267
+
268
+ # intersection or union of keys while preserving ordering:
269
+ if intersect:
270
+ merge_keys = [k for k in base if k in override] + [k for k in override if k in base]
271
+ else:
272
+ merge_keys = list(base) + [k for k in override if k not in base]
273
+
274
+ merged: dict[int | str, Any] = {}
275
+ for k in merge_keys:
276
+ merged_item = cls.merge(base.get(k), override.get(k), intersect=intersect)
277
+ if merged_item is not None:
278
+ merged[k] = merged_item
279
+
280
+ return merged
281
+
282
+ @staticmethod
283
+ def _coerce_items(items: AbstractSetIntStr | MappingIntStrAny) -> MappingIntStrAny:
284
+ if isinstance(items, Mapping):
285
+ pass
286
+ elif isinstance(items, AbstractSet):
287
+ items = dict.fromkeys(items, ...) # type: ignore
288
+ else:
289
+ class_name = getattr(items, '__class__', '???')
290
+ raise TypeError(f'Unexpected type of exclude value {class_name}')
291
+ return items # type: ignore
292
+
293
+ @classmethod
294
+ def _coerce_value(cls, value: Any) -> Any:
295
+ if value is None or cls.is_true(value):
296
+ return value
297
+ return cls._coerce_items(value)
298
+
299
+ @staticmethod
300
+ def is_true(v: Any) -> bool:
301
+ return v is True or v is ...
302
+
303
+ def __repr_args__(self) -> _repr.ReprArgs:
304
+ return [(None, self._items)]
305
+
306
+
307
+ if TYPE_CHECKING:
308
+
309
+ def LazyClassAttribute(name: str, get_value: Callable[[], T]) -> T: ...
310
+
311
+ else:
312
+
313
+ class LazyClassAttribute:
314
+ """A descriptor exposing an attribute only accessible on a class (hidden from instances).
315
+
316
+ The attribute is lazily computed and cached during the first access.
317
+ """
318
+
319
+ def __init__(self, name: str, get_value: Callable[[], Any]) -> None:
320
+ self.name = name
321
+ self.get_value = get_value
322
+
323
+ @cached_property
324
+ def value(self) -> Any:
325
+ return self.get_value()
326
+
327
+ def __get__(self, instance: Any, owner: type[Any]) -> None:
328
+ if instance is None:
329
+ return self.value
330
+ raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only')
331
+
332
+
333
+ Obj = TypeVar('Obj')
334
+
335
+
336
+ def smart_deepcopy(obj: Obj) -> Obj:
337
+ """Return type as is for immutable built-in types
338
+ Use obj.copy() for built-in empty collections
339
+ Use copy.deepcopy() for non-empty collections and unknown objects.
340
+ """
341
+ if obj is MISSING or obj is PydanticUndefined:
342
+ return obj # pyright: ignore[reportReturnType]
343
+ obj_type = obj.__class__
344
+ if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES:
345
+ return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway
346
+ try:
347
+ if not obj and obj_type in BUILTIN_COLLECTIONS:
348
+ # faster way for empty collections, no need to copy its members
349
+ return obj if obj_type is tuple else obj.copy() # tuple doesn't have copy method # type: ignore
350
+ except (TypeError, ValueError, RuntimeError):
351
+ # do we really dare to catch ALL errors? Seems a bit risky
352
+ pass
353
+
354
+ return deepcopy(obj) # slowest way when we actually might need a deepcopy
355
+
356
+
357
+ _SENTINEL = object()
358
+
359
+
360
+ def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool:
361
+ """Check that the items of `left` are the same objects as those in `right`.
362
+
363
+ >>> a, b = object(), object()
364
+ >>> all_identical([a, b, a], [a, b, a])
365
+ True
366
+ >>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical"
367
+ False
368
+ """
369
+ for left_item, right_item in zip_longest(left, right, fillvalue=_SENTINEL):
370
+ if left_item is not right_item:
371
+ return False
372
+ return True
373
+
374
+
375
+ def get_first_not_none(a: Any, b: Any) -> Any:
376
+ """Return the first argument if it is not `None`, otherwise return the second argument."""
377
+ return a if a is not None else b
378
+
379
+
380
+ @dataclasses.dataclass(frozen=True)
381
+ class SafeGetItemProxy:
382
+ """Wrapper redirecting `__getitem__` to `get` with a sentinel value as default
383
+
384
+ This makes is safe to use in `operator.itemgetter` when some keys may be missing
385
+ """
386
+
387
+ # Define __slots__manually for performances
388
+ # @dataclasses.dataclass() only support slots=True in python>=3.10
389
+ __slots__ = ('wrapped',)
390
+
391
+ wrapped: Mapping[str, Any]
392
+
393
+ def __getitem__(self, key: str, /) -> Any:
394
+ return self.wrapped.get(key, _SENTINEL)
395
+
396
+ # required to pass the object to operator.itemgetter() instances due to a quirk of typeshed
397
+ # https://github.com/python/mypy/issues/13713
398
+ # https://github.com/python/typeshed/pull/8785
399
+ # Since this is typing-only, hide it in a typing.TYPE_CHECKING block
400
+ if TYPE_CHECKING:
401
+
402
+ def __contains__(self, key: str, /) -> bool:
403
+ return self.wrapped.__contains__(key)
404
+
405
+
406
+ _ModelT = TypeVar('_ModelT', bound='BaseModel')
407
+ _RT = TypeVar('_RT')
408
+
409
+
410
+ class deprecated_instance_property(Generic[_ModelT, _RT]):
411
+ """A decorator exposing the decorated class method as a property, with a warning on instance access.
412
+
413
+ This decorator takes a class method defined on the `BaseModel` class and transforms it into
414
+ an attribute. The attribute can be accessed on both the class and instances of the class. If accessed
415
+ via an instance, a deprecation warning is emitted stating that instance access will be removed in V3.
416
+ """
417
+
418
+ def __init__(self, fget: Callable[[type[_ModelT]], _RT], /) -> None:
419
+ # Note: fget should be a classmethod:
420
+ self.fget = fget
421
+
422
+ @overload
423
+ def __get__(self, instance: None, objtype: type[_ModelT]) -> _RT: ...
424
+ @overload
425
+ @deprecated(
426
+ 'Accessing this attribute on the instance is deprecated, and will be removed in Pydantic V3. '
427
+ 'Instead, you should access this attribute from the model class.',
428
+ category=None,
429
+ )
430
+ def __get__(self, instance: _ModelT, objtype: type[_ModelT]) -> _RT: ...
431
+ def __get__(self, instance: _ModelT | None, objtype: type[_ModelT]) -> _RT:
432
+ if instance is not None:
433
+ # fmt: off
434
+ attr_name = (
435
+ self.fget.__name__
436
+ if sys.version_info >= (3, 10)
437
+ else self.fget.__func__.__name__ # pyright: ignore[reportFunctionMemberAccess]
438
+ )
439
+ # fmt: on
440
+ warnings.warn(
441
+ f'Accessing the {attr_name!r} attribute on the instance is deprecated. '
442
+ 'Instead, you should access this attribute from the model class.',
443
+ category=PydanticDeprecatedSince211,
444
+ stacklevel=2,
445
+ )
446
+ return self.fget.__get__(instance, objtype)()
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_validate_call.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations as _annotations
2
+
3
+ import functools
4
+ import inspect
5
+ from collections.abc import Awaitable
6
+ from functools import partial
7
+ from typing import Any, Callable
8
+
9
+ import pydantic_core
10
+
11
+ from ..config import ConfigDict
12
+ from ..plugin._schema_validator import create_schema_validator
13
+ from ._config import ConfigWrapper
14
+ from ._generate_schema import GenerateSchema, ValidateCallSupportedTypes
15
+ from ._namespace_utils import MappingNamespace, NsResolver, ns_for_function
16
+ from ._typing_extra import signature_no_eval
17
+
18
+
19
+ def extract_function_name(func: ValidateCallSupportedTypes) -> str:
20
+ """Extract the name of a `ValidateCallSupportedTypes` object."""
21
+ return f'partial({func.func.__name__})' if isinstance(func, functools.partial) else func.__name__
22
+
23
+
24
+ def extract_function_qualname(func: ValidateCallSupportedTypes) -> str:
25
+ """Extract the qualname of a `ValidateCallSupportedTypes` object."""
26
+ return f'partial({func.func.__qualname__})' if isinstance(func, functools.partial) else func.__qualname__
27
+
28
+
29
+ def update_wrapper_attributes(wrapped: ValidateCallSupportedTypes, wrapper: Callable[..., Any]):
30
+ """Update the `wrapper` function with the attributes of the `wrapped` function. Return the updated function."""
31
+ if inspect.iscoroutinefunction(wrapped):
32
+
33
+ @functools.wraps(wrapped)
34
+ async def wrapper_function(*args, **kwargs): # type: ignore
35
+ return await wrapper(*args, **kwargs)
36
+ else:
37
+
38
+ @functools.wraps(wrapped)
39
+ def wrapper_function(*args, **kwargs):
40
+ return wrapper(*args, **kwargs)
41
+
42
+ # We need to manually update this because `partial` object has no `__name__` and `__qualname__`.
43
+ wrapper_function.__name__ = extract_function_name(wrapped)
44
+ wrapper_function.__qualname__ = extract_function_qualname(wrapped)
45
+ wrapper_function.raw_function = wrapped # type: ignore
46
+
47
+ return wrapper_function
48
+
49
+
50
+ class ValidateCallWrapper:
51
+ """This is a wrapper around a function that validates the arguments passed to it, and optionally the return value."""
52
+
53
+ __slots__ = (
54
+ 'function',
55
+ 'validate_return',
56
+ 'schema_type',
57
+ 'module',
58
+ 'qualname',
59
+ 'ns_resolver',
60
+ 'config_wrapper',
61
+ '__pydantic_complete__',
62
+ '__pydantic_validator__',
63
+ '__return_pydantic_validator__',
64
+ )
65
+
66
+ def __init__(
67
+ self,
68
+ function: ValidateCallSupportedTypes,
69
+ config: ConfigDict | None,
70
+ validate_return: bool,
71
+ parent_namespace: MappingNamespace | None,
72
+ ) -> None:
73
+ self.function = function
74
+ self.validate_return = validate_return
75
+ if isinstance(function, partial):
76
+ self.schema_type = function.func
77
+ self.module = function.func.__module__
78
+ else:
79
+ self.schema_type = function
80
+ self.module = function.__module__
81
+ self.qualname = extract_function_qualname(function)
82
+
83
+ self.ns_resolver = NsResolver(
84
+ namespaces_tuple=ns_for_function(self.schema_type, parent_namespace=parent_namespace)
85
+ )
86
+ self.config_wrapper = ConfigWrapper(config)
87
+ if not self.config_wrapper.defer_build:
88
+ self._create_validators()
89
+ else:
90
+ self.__pydantic_complete__ = False
91
+
92
+ def _create_validators(self) -> None:
93
+ gen_schema = GenerateSchema(self.config_wrapper, self.ns_resolver)
94
+ schema = gen_schema.clean_schema(gen_schema.generate_schema(self.function))
95
+ core_config = self.config_wrapper.core_config(title=self.qualname)
96
+
97
+ self.__pydantic_validator__ = create_schema_validator(
98
+ schema,
99
+ self.schema_type,
100
+ self.module,
101
+ self.qualname,
102
+ 'validate_call',
103
+ core_config,
104
+ self.config_wrapper.plugin_settings,
105
+ )
106
+ if self.validate_return:
107
+ signature = signature_no_eval(self.function)
108
+ return_type = signature.return_annotation if signature.return_annotation is not signature.empty else Any
109
+ gen_schema = GenerateSchema(self.config_wrapper, self.ns_resolver)
110
+ schema = gen_schema.clean_schema(gen_schema.generate_schema(return_type))
111
+ validator = create_schema_validator(
112
+ schema,
113
+ self.schema_type,
114
+ self.module,
115
+ self.qualname,
116
+ 'validate_call',
117
+ core_config,
118
+ self.config_wrapper.plugin_settings,
119
+ )
120
+ if inspect.iscoroutinefunction(self.function):
121
+
122
+ async def return_val_wrapper(aw: Awaitable[Any]) -> None:
123
+ return validator.validate_python(await aw)
124
+
125
+ self.__return_pydantic_validator__ = return_val_wrapper
126
+ else:
127
+ self.__return_pydantic_validator__ = validator.validate_python
128
+ else:
129
+ self.__return_pydantic_validator__ = None
130
+
131
+ self.__pydantic_complete__ = True
132
+
133
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
134
+ if not self.__pydantic_complete__:
135
+ self._create_validators()
136
+
137
+ res = self.__pydantic_validator__.validate_python(pydantic_core.ArgsKwargs(args, kwargs))
138
+ if self.__return_pydantic_validator__:
139
+ return self.__return_pydantic_validator__(res)
140
+ else:
141
+ return res
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/_internal/_validators.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validator functions for standard library types.
2
+
3
+ Import of this module is deferred since it contains imports of many standard library modules.
4
+ """
5
+
6
+ from __future__ import annotations as _annotations
7
+
8
+ import collections.abc
9
+ import math
10
+ import re
11
+ import typing
12
+ from collections.abc import Sequence
13
+ from decimal import Decimal
14
+ from fractions import Fraction
15
+ from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
16
+ from typing import Any, Callable, TypeVar, Union, cast
17
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
18
+
19
+ import typing_extensions
20
+ from pydantic_core import PydanticCustomError, PydanticKnownError, core_schema
21
+ from typing_extensions import get_args, get_origin
22
+ from typing_inspection import typing_objects
23
+
24
+ from pydantic._internal._import_utils import import_cached_field_info
25
+ from pydantic.errors import PydanticSchemaGenerationError
26
+
27
+
28
+ def sequence_validator(
29
+ input_value: Sequence[Any],
30
+ /,
31
+ validator: core_schema.ValidatorFunctionWrapHandler,
32
+ ) -> Sequence[Any]:
33
+ """Validator for `Sequence` types, isinstance(v, Sequence) has already been called."""
34
+ value_type = type(input_value)
35
+
36
+ # We don't accept any plain string as a sequence
37
+ # Relevant issue: https://github.com/pydantic/pydantic/issues/5595
38
+ if issubclass(value_type, (str, bytes)):
39
+ raise PydanticCustomError(
40
+ 'sequence_str',
41
+ "'{type_name}' instances are not allowed as a Sequence value",
42
+ {'type_name': value_type.__name__},
43
+ )
44
+
45
+ # TODO: refactor sequence validation to validate with either a list or a tuple
46
+ # schema, depending on the type of the value.
47
+ # Additionally, we should be able to remove one of either this validator or the
48
+ # SequenceValidator in _std_types_schema.py (preferably this one, while porting over some logic).
49
+ # Effectively, a refactor for sequence validation is needed.
50
+ if value_type is tuple:
51
+ input_value = list(input_value)
52
+
53
+ v_list = validator(input_value)
54
+
55
+ # the rest of the logic is just re-creating the original type from `v_list`
56
+ if value_type is list:
57
+ return v_list
58
+ elif issubclass(value_type, range):
59
+ # return the list as we probably can't re-create the range
60
+ return v_list
61
+ elif value_type is tuple:
62
+ return tuple(v_list)
63
+ else:
64
+ # best guess at how to re-create the original type, more custom construction logic might be required
65
+ return value_type(v_list) # type: ignore[call-arg]
66
+
67
+
68
+ def import_string(value: Any) -> Any:
69
+ if isinstance(value, str):
70
+ try:
71
+ return _import_string_logic(value)
72
+ except ImportError as e:
73
+ raise PydanticCustomError('import_error', 'Invalid python path: {error}', {'error': str(e)}) from e
74
+ else:
75
+ # otherwise we just return the value and let the next validator do the rest of the work
76
+ return value
77
+
78
+
79
+ def _import_string_logic(dotted_path: str) -> Any:
80
+ """Inspired by uvicorn — dotted paths should include a colon before the final item if that item is not a module.
81
+ (This is necessary to distinguish between a submodule and an attribute when there is a conflict.).
82
+
83
+ If the dotted path does not include a colon and the final item is not a valid module, importing as an attribute
84
+ rather than a submodule will be attempted automatically.
85
+
86
+ So, for example, the following values of `dotted_path` result in the following returned values:
87
+ * 'collections': <module 'collections'>
88
+ * 'collections.abc': <module 'collections.abc'>
89
+ * 'collections.abc:Mapping': <class 'collections.abc.Mapping'>
90
+ * `collections.abc.Mapping`: <class 'collections.abc.Mapping'> (though this is a bit slower than the previous line)
91
+
92
+ An error will be raised under any of the following scenarios:
93
+ * `dotted_path` contains more than one colon (e.g., 'collections:abc:Mapping')
94
+ * the substring of `dotted_path` before the colon is not a valid module in the environment (e.g., '123:Mapping')
95
+ * the substring of `dotted_path` after the colon is not an attribute of the module (e.g., 'collections:abc123')
96
+ """
97
+ from importlib import import_module
98
+
99
+ components = dotted_path.strip().split(':')
100
+ if len(components) > 2:
101
+ raise ImportError(f"Import strings should have at most one ':'; received {dotted_path!r}")
102
+ attribute = None
103
+ if len(components) == 2:
104
+ attribute = components[1]
105
+ module_path = components[0]
106
+ if not module_path:
107
+ raise ImportError(f'Import strings should have a nonempty module name; received {dotted_path!r}')
108
+
109
+ try:
110
+ module = import_module(module_path)
111
+ except ModuleNotFoundError:
112
+ if attribute is None and '.' in module_path:
113
+ # Try interpreting the final dotted segment as an attribute, not a submodule
114
+ maybe_module_path, maybe_attribute = module_path.rsplit('.', 1)
115
+
116
+ try:
117
+ return _import_string_logic(f'{maybe_module_path}:{maybe_attribute}')
118
+ except ImportError:
119
+ pass
120
+ raise
121
+
122
+ if attribute is not None:
123
+ try:
124
+ return getattr(module, attribute)
125
+ except AttributeError as e:
126
+ raise ImportError(f'cannot import name {attribute!r} from {module_path!r}') from e
127
+ else:
128
+ return module
129
+
130
+
131
+ def pattern_either_validator(input_value: Any, /) -> re.Pattern[Any]:
132
+ if isinstance(input_value, re.Pattern):
133
+ return input_value
134
+ elif isinstance(input_value, (str, bytes)):
135
+ # todo strict mode
136
+ return compile_pattern(input_value) # type: ignore
137
+ else:
138
+ raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')
139
+
140
+
141
+ def pattern_str_validator(input_value: Any, /) -> re.Pattern[str]:
142
+ if isinstance(input_value, re.Pattern):
143
+ if isinstance(input_value.pattern, str):
144
+ return input_value
145
+ else:
146
+ raise PydanticCustomError('pattern_str_type', 'Input should be a string pattern')
147
+ elif isinstance(input_value, str):
148
+ return compile_pattern(input_value)
149
+ elif isinstance(input_value, bytes):
150
+ raise PydanticCustomError('pattern_str_type', 'Input should be a string pattern')
151
+ else:
152
+ raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')
153
+
154
+
155
+ def pattern_bytes_validator(input_value: Any, /) -> re.Pattern[bytes]:
156
+ if isinstance(input_value, re.Pattern):
157
+ if isinstance(input_value.pattern, bytes):
158
+ return input_value
159
+ else:
160
+ raise PydanticCustomError('pattern_bytes_type', 'Input should be a bytes pattern')
161
+ elif isinstance(input_value, bytes):
162
+ return compile_pattern(input_value)
163
+ elif isinstance(input_value, str):
164
+ raise PydanticCustomError('pattern_bytes_type', 'Input should be a bytes pattern')
165
+ else:
166
+ raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')
167
+
168
+
169
+ PatternType = TypeVar('PatternType', str, bytes)
170
+
171
+
172
+ def compile_pattern(pattern: PatternType) -> re.Pattern[PatternType]:
173
+ try:
174
+ return re.compile(pattern)
175
+ except re.error:
176
+ raise PydanticCustomError('pattern_regex', 'Input should be a valid regular expression')
177
+
178
+
179
+ def ip_v4_address_validator(input_value: Any, /) -> IPv4Address:
180
+ if isinstance(input_value, IPv4Address):
181
+ return input_value
182
+
183
+ try:
184
+ return IPv4Address(input_value)
185
+ except ValueError:
186
+ raise PydanticCustomError('ip_v4_address', 'Input is not a valid IPv4 address')
187
+
188
+
189
+ def ip_v6_address_validator(input_value: Any, /) -> IPv6Address:
190
+ if isinstance(input_value, IPv6Address):
191
+ return input_value
192
+
193
+ try:
194
+ return IPv6Address(input_value)
195
+ except ValueError:
196
+ raise PydanticCustomError('ip_v6_address', 'Input is not a valid IPv6 address')
197
+
198
+
199
+ def ip_v4_network_validator(input_value: Any, /) -> IPv4Network:
200
+ """Assume IPv4Network initialised with a default `strict` argument.
201
+
202
+ See more:
203
+ https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network
204
+ """
205
+ if isinstance(input_value, IPv4Network):
206
+ return input_value
207
+
208
+ try:
209
+ return IPv4Network(input_value)
210
+ except ValueError:
211
+ raise PydanticCustomError('ip_v4_network', 'Input is not a valid IPv4 network')
212
+
213
+
214
+ def ip_v6_network_validator(input_value: Any, /) -> IPv6Network:
215
+ """Assume IPv6Network initialised with a default `strict` argument.
216
+
217
+ See more:
218
+ https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network
219
+ """
220
+ if isinstance(input_value, IPv6Network):
221
+ return input_value
222
+
223
+ try:
224
+ return IPv6Network(input_value)
225
+ except ValueError:
226
+ raise PydanticCustomError('ip_v6_network', 'Input is not a valid IPv6 network')
227
+
228
+
229
+ def ip_v4_interface_validator(input_value: Any, /) -> IPv4Interface:
230
+ if isinstance(input_value, IPv4Interface):
231
+ return input_value
232
+
233
+ try:
234
+ return IPv4Interface(input_value)
235
+ except ValueError:
236
+ raise PydanticCustomError('ip_v4_interface', 'Input is not a valid IPv4 interface')
237
+
238
+
239
+ def ip_v6_interface_validator(input_value: Any, /) -> IPv6Interface:
240
+ if isinstance(input_value, IPv6Interface):
241
+ return input_value
242
+
243
+ try:
244
+ return IPv6Interface(input_value)
245
+ except ValueError:
246
+ raise PydanticCustomError('ip_v6_interface', 'Input is not a valid IPv6 interface')
247
+
248
+
249
+ def fraction_validator(input_value: Any, /) -> Fraction:
250
+ if isinstance(input_value, Fraction):
251
+ return input_value
252
+
253
+ try:
254
+ return Fraction(input_value)
255
+ except ValueError:
256
+ raise PydanticCustomError('fraction_parsing', 'Input is not a valid fraction')
257
+
258
+
259
+ def forbid_inf_nan_check(x: Any) -> Any:
260
+ if not math.isfinite(x):
261
+ raise PydanticKnownError('finite_number')
262
+ return x
263
+
264
+
265
+ def _safe_repr(v: Any) -> int | float | str:
266
+ """The context argument for `PydanticKnownError` requires a number or str type, so we do a simple repr() coercion for types like timedelta.
267
+
268
+ See tests/test_types.py::test_annotated_metadata_any_order for some context.
269
+ """
270
+ if isinstance(v, (int, float, str)):
271
+ return v
272
+ return repr(v)
273
+
274
+
275
+ def greater_than_validator(x: Any, gt: Any) -> Any:
276
+ try:
277
+ if not (x > gt):
278
+ raise PydanticKnownError('greater_than', {'gt': _safe_repr(gt)})
279
+ return x
280
+ except TypeError:
281
+ raise TypeError(f"Unable to apply constraint 'gt' to supplied value {x}")
282
+
283
+
284
+ def greater_than_or_equal_validator(x: Any, ge: Any) -> Any:
285
+ try:
286
+ if not (x >= ge):
287
+ raise PydanticKnownError('greater_than_equal', {'ge': _safe_repr(ge)})
288
+ return x
289
+ except TypeError:
290
+ raise TypeError(f"Unable to apply constraint 'ge' to supplied value {x}")
291
+
292
+
293
+ def less_than_validator(x: Any, lt: Any) -> Any:
294
+ try:
295
+ if not (x < lt):
296
+ raise PydanticKnownError('less_than', {'lt': _safe_repr(lt)})
297
+ return x
298
+ except TypeError:
299
+ raise TypeError(f"Unable to apply constraint 'lt' to supplied value {x}")
300
+
301
+
302
+ def less_than_or_equal_validator(x: Any, le: Any) -> Any:
303
+ try:
304
+ if not (x <= le):
305
+ raise PydanticKnownError('less_than_equal', {'le': _safe_repr(le)})
306
+ return x
307
+ except TypeError:
308
+ raise TypeError(f"Unable to apply constraint 'le' to supplied value {x}")
309
+
310
+
311
+ def multiple_of_validator(x: Any, multiple_of: Any) -> Any:
312
+ try:
313
+ if x % multiple_of:
314
+ raise PydanticKnownError('multiple_of', {'multiple_of': _safe_repr(multiple_of)})
315
+ return x
316
+ except TypeError:
317
+ raise TypeError(f"Unable to apply constraint 'multiple_of' to supplied value {x}")
318
+
319
+
320
+ def min_length_validator(x: Any, min_length: Any) -> Any:
321
+ try:
322
+ if not (len(x) >= min_length):
323
+ raise PydanticKnownError(
324
+ 'too_short', {'field_type': 'Value', 'min_length': min_length, 'actual_length': len(x)}
325
+ )
326
+ return x
327
+ except TypeError:
328
+ raise TypeError(f"Unable to apply constraint 'min_length' to supplied value {x}")
329
+
330
+
331
+ def max_length_validator(x: Any, max_length: Any) -> Any:
332
+ try:
333
+ if len(x) > max_length:
334
+ raise PydanticKnownError(
335
+ 'too_long',
336
+ {'field_type': 'Value', 'max_length': max_length, 'actual_length': len(x)},
337
+ )
338
+ return x
339
+ except TypeError:
340
+ raise TypeError(f"Unable to apply constraint 'max_length' to supplied value {x}")
341
+
342
+
343
+ def _extract_decimal_digits_info(decimal: Decimal) -> tuple[int, int]:
344
+ """Compute the total number of digits and decimal places for a given [`Decimal`][decimal.Decimal] instance.
345
+
346
+ This function handles both normalized and non-normalized Decimal instances.
347
+ Example: Decimal('1.230') -> 4 digits, 3 decimal places
348
+
349
+ Args:
350
+ decimal (Decimal): The decimal number to analyze.
351
+
352
+ Returns:
353
+ tuple[int, int]: A tuple containing the number of decimal places and total digits.
354
+
355
+ Though this could be divided into two separate functions, the logic is easier to follow if we couple the computation
356
+ of the number of decimals and digits together.
357
+ """
358
+ try:
359
+ decimal_tuple = decimal.as_tuple()
360
+
361
+ assert isinstance(decimal_tuple.exponent, int)
362
+
363
+ exponent = decimal_tuple.exponent
364
+ num_digits = len(decimal_tuple.digits)
365
+
366
+ if exponent >= 0:
367
+ # A positive exponent adds that many trailing zeros
368
+ # Ex: digit_tuple=(1, 2, 3), exponent=2 -> 12300 -> 0 decimal places, 5 digits
369
+ num_digits += exponent
370
+ decimal_places = 0
371
+ else:
372
+ # If the absolute value of the negative exponent is larger than the
373
+ # number of digits, then it's the same as the number of digits,
374
+ # because it'll consume all the digits in digit_tuple and then
375
+ # add abs(exponent) - len(digit_tuple) leading zeros after the decimal point.
376
+ # Ex: digit_tuple=(1, 2, 3), exponent=-2 -> 1.23 -> 2 decimal places, 3 digits
377
+ # Ex: digit_tuple=(1, 2, 3), exponent=-4 -> 0.0123 -> 4 decimal places, 4 digits
378
+ decimal_places = abs(exponent)
379
+ num_digits = max(num_digits, decimal_places)
380
+
381
+ return decimal_places, num_digits
382
+ except (AssertionError, AttributeError):
383
+ raise TypeError(f'Unable to extract decimal digits info from supplied value {decimal}')
384
+
385
+
386
+ def max_digits_validator(x: Any, max_digits: Any) -> Any:
387
+ try:
388
+ _, num_digits = _extract_decimal_digits_info(x)
389
+ _, normalized_num_digits = _extract_decimal_digits_info(x.normalize())
390
+ if (num_digits > max_digits) and (normalized_num_digits > max_digits):
391
+ raise PydanticKnownError(
392
+ 'decimal_max_digits',
393
+ {'max_digits': max_digits},
394
+ )
395
+ return x
396
+ except TypeError:
397
+ raise TypeError(f"Unable to apply constraint 'max_digits' to supplied value {x}")
398
+
399
+
400
+ def decimal_places_validator(x: Any, decimal_places: Any) -> Any:
401
+ try:
402
+ decimal_places_, _ = _extract_decimal_digits_info(x)
403
+ if decimal_places_ > decimal_places:
404
+ normalized_decimal_places, _ = _extract_decimal_digits_info(x.normalize())
405
+ if normalized_decimal_places > decimal_places:
406
+ raise PydanticKnownError(
407
+ 'decimal_max_places',
408
+ {'decimal_places': decimal_places},
409
+ )
410
+ return x
411
+ except TypeError:
412
+ raise TypeError(f"Unable to apply constraint 'decimal_places' to supplied value {x}")
413
+
414
+
415
+ def deque_validator(input_value: Any, handler: core_schema.ValidatorFunctionWrapHandler) -> collections.deque[Any]:
416
+ return collections.deque(handler(input_value), maxlen=getattr(input_value, 'maxlen', None))
417
+
418
+
419
+ def defaultdict_validator(
420
+ input_value: Any, handler: core_schema.ValidatorFunctionWrapHandler, default_default_factory: Callable[[], Any]
421
+ ) -> collections.defaultdict[Any, Any]:
422
+ if isinstance(input_value, collections.defaultdict):
423
+ default_factory = input_value.default_factory
424
+ return collections.defaultdict(default_factory, handler(input_value))
425
+ else:
426
+ return collections.defaultdict(default_default_factory, handler(input_value))
427
+
428
+
429
+ def get_defaultdict_default_default_factory(values_source_type: Any) -> Callable[[], Any]:
430
+ FieldInfo = import_cached_field_info()
431
+
432
+ values_type_origin = get_origin(values_source_type)
433
+
434
+ def infer_default() -> Callable[[], Any]:
435
+ allowed_default_types: dict[Any, Any] = {
436
+ tuple: tuple,
437
+ collections.abc.Sequence: tuple,
438
+ collections.abc.MutableSequence: list,
439
+ list: list,
440
+ typing.Sequence: list,
441
+ set: set,
442
+ typing.MutableSet: set,
443
+ collections.abc.MutableSet: set,
444
+ collections.abc.Set: frozenset,
445
+ typing.MutableMapping: dict,
446
+ typing.Mapping: dict,
447
+ collections.abc.Mapping: dict,
448
+ collections.abc.MutableMapping: dict,
449
+ float: float,
450
+ int: int,
451
+ str: str,
452
+ bool: bool,
453
+ }
454
+ values_type = values_type_origin or values_source_type
455
+ instructions = 'set using `DefaultDict[..., Annotated[..., Field(default_factory=...)]]`'
456
+ if typing_objects.is_typevar(values_type):
457
+
458
+ def type_var_default_factory() -> None:
459
+ raise RuntimeError(
460
+ 'Generic defaultdict cannot be used without a concrete value type or an'
461
+ ' explicit default factory, ' + instructions
462
+ )
463
+
464
+ return type_var_default_factory
465
+ elif values_type not in allowed_default_types:
466
+ # a somewhat subjective set of types that have reasonable default values
467
+ allowed_msg = ', '.join([t.__name__ for t in set(allowed_default_types.values())])
468
+ raise PydanticSchemaGenerationError(
469
+ f'Unable to infer a default factory for keys of type {values_source_type}.'
470
+ f' Only {allowed_msg} are supported, other types require an explicit default factory'
471
+ ' ' + instructions
472
+ )
473
+ return allowed_default_types[values_type]
474
+
475
+ # Assume Annotated[..., Field(...)]
476
+ if typing_objects.is_annotated(values_type_origin):
477
+ field_info = next((v for v in get_args(values_source_type) if isinstance(v, FieldInfo)), None)
478
+ else:
479
+ field_info = None
480
+ if field_info and field_info.default_factory:
481
+ # Assume the default factory does not take any argument:
482
+ default_default_factory = cast(Callable[[], Any], field_info.default_factory)
483
+ else:
484
+ default_default_factory = infer_default()
485
+ return default_default_factory
486
+
487
+
488
+ def validate_str_is_valid_iana_tz(value: Any, /) -> ZoneInfo:
489
+ if isinstance(value, ZoneInfo):
490
+ return value
491
+ try:
492
+ return ZoneInfo(value)
493
+ except (ZoneInfoNotFoundError, ValueError, TypeError):
494
+ raise PydanticCustomError('zoneinfo_str', 'invalid timezone: {value}', {'value': value})
495
+
496
+
497
+ NUMERIC_VALIDATOR_LOOKUP: dict[str, Callable] = {
498
+ 'gt': greater_than_validator,
499
+ 'ge': greater_than_or_equal_validator,
500
+ 'lt': less_than_validator,
501
+ 'le': less_than_or_equal_validator,
502
+ 'multiple_of': multiple_of_validator,
503
+ 'min_length': min_length_validator,
504
+ 'max_length': max_length_validator,
505
+ 'max_digits': max_digits_validator,
506
+ 'decimal_places': decimal_places_validator,
507
+ }
508
+
509
+ IpType = Union[IPv4Address, IPv6Address, IPv4Network, IPv6Network, IPv4Interface, IPv6Interface]
510
+
511
+ IP_VALIDATOR_LOOKUP: dict[type[IpType], Callable] = {
512
+ IPv4Address: ip_v4_address_validator,
513
+ IPv6Address: ip_v6_address_validator,
514
+ IPv4Network: ip_v4_network_validator,
515
+ IPv6Network: ip_v6_network_validator,
516
+ IPv4Interface: ip_v4_interface_validator,
517
+ IPv6Interface: ip_v6_interface_validator,
518
+ }
519
+
520
+ MAPPING_ORIGIN_MAP: dict[Any, Any] = {
521
+ typing.DefaultDict: collections.defaultdict, # noqa: UP006
522
+ collections.defaultdict: collections.defaultdict,
523
+ typing.OrderedDict: collections.OrderedDict, # noqa: UP006
524
+ collections.OrderedDict: collections.OrderedDict,
525
+ typing_extensions.OrderedDict: collections.OrderedDict,
526
+ typing.Counter: collections.Counter,
527
+ collections.Counter: collections.Counter,
528
+ # this doesn't handle subclasses of these
529
+ typing.Mapping: dict,
530
+ typing.MutableMapping: dict,
531
+ # parametrized typing.{Mutable}Mapping creates one of these
532
+ collections.abc.Mapping: dict,
533
+ collections.abc.MutableMapping: dict,
534
+ }
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/__init__.py ADDED
File without changes
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/class_validators.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Old `@validator` and `@root_validator` function validators from V1."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ from functools import partial, partialmethod
6
+ from types import FunctionType
7
+ from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union, overload
8
+ from warnings import warn
9
+
10
+ from typing_extensions import Protocol, TypeAlias, deprecated
11
+
12
+ from .._internal import _decorators, _decorators_v1
13
+ from ..errors import PydanticUserError
14
+ from ..warnings import PydanticDeprecatedSince20
15
+
16
+ _ALLOW_REUSE_WARNING_MESSAGE = '`allow_reuse` is deprecated and will be ignored; it should no longer be necessary'
17
+
18
+
19
+ if TYPE_CHECKING:
20
+
21
+ class _OnlyValueValidatorClsMethod(Protocol):
22
+ def __call__(self, __cls: Any, __value: Any) -> Any: ...
23
+
24
+ class _V1ValidatorWithValuesClsMethod(Protocol):
25
+ def __call__(self, __cls: Any, __value: Any, values: dict[str, Any]) -> Any: ...
26
+
27
+ class _V1ValidatorWithValuesKwOnlyClsMethod(Protocol):
28
+ def __call__(self, __cls: Any, __value: Any, *, values: dict[str, Any]) -> Any: ...
29
+
30
+ class _V1ValidatorWithKwargsClsMethod(Protocol):
31
+ def __call__(self, __cls: Any, **kwargs: Any) -> Any: ...
32
+
33
+ class _V1ValidatorWithValuesAndKwargsClsMethod(Protocol):
34
+ def __call__(self, __cls: Any, values: dict[str, Any], **kwargs: Any) -> Any: ...
35
+
36
+ class _V1RootValidatorClsMethod(Protocol):
37
+ def __call__(
38
+ self, __cls: Any, __values: _decorators_v1.RootValidatorValues
39
+ ) -> _decorators_v1.RootValidatorValues: ...
40
+
41
+ V1Validator = Union[
42
+ _OnlyValueValidatorClsMethod,
43
+ _V1ValidatorWithValuesClsMethod,
44
+ _V1ValidatorWithValuesKwOnlyClsMethod,
45
+ _V1ValidatorWithKwargsClsMethod,
46
+ _V1ValidatorWithValuesAndKwargsClsMethod,
47
+ _decorators_v1.V1ValidatorWithValues,
48
+ _decorators_v1.V1ValidatorWithValuesKwOnly,
49
+ _decorators_v1.V1ValidatorWithKwargs,
50
+ _decorators_v1.V1ValidatorWithValuesAndKwargs,
51
+ ]
52
+
53
+ V1RootValidator = Union[
54
+ _V1RootValidatorClsMethod,
55
+ _decorators_v1.V1RootValidatorFunction,
56
+ ]
57
+
58
+ _PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]]
59
+
60
+ # Allow both a V1 (assumed pre=False) or V2 (assumed mode='after') validator
61
+ # We lie to type checkers and say we return the same thing we get
62
+ # but in reality we return a proxy object that _mostly_ behaves like the wrapped thing
63
+ _V1ValidatorType = TypeVar('_V1ValidatorType', V1Validator, _PartialClsOrStaticMethod)
64
+ _V1RootValidatorFunctionType = TypeVar(
65
+ '_V1RootValidatorFunctionType',
66
+ _decorators_v1.V1RootValidatorFunction,
67
+ _V1RootValidatorClsMethod,
68
+ _PartialClsOrStaticMethod,
69
+ )
70
+ else:
71
+ # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
72
+ # and https://youtrack.jetbrains.com/issue/PY-51428
73
+ DeprecationWarning = PydanticDeprecatedSince20
74
+
75
+
76
+ @deprecated(
77
+ 'Pydantic V1 style `@validator` validators are deprecated.'
78
+ ' You should migrate to Pydantic V2 style `@field_validator` validators,'
79
+ ' see the migration guide for more details',
80
+ category=None,
81
+ )
82
+ def validator(
83
+ __field: str,
84
+ *fields: str,
85
+ pre: bool = False,
86
+ each_item: bool = False,
87
+ always: bool = False,
88
+ check_fields: bool | None = None,
89
+ allow_reuse: bool = False,
90
+ ) -> Callable[[_V1ValidatorType], _V1ValidatorType]:
91
+ """Decorate methods on the class indicating that they should be used to validate fields.
92
+
93
+ Args:
94
+ __field (str): The first field the validator should be called on; this is separate
95
+ from `fields` to ensure an error is raised if you don't pass at least one.
96
+ *fields (str): Additional field(s) the validator should be called on.
97
+ pre (bool, optional): Whether this validator should be called before the standard
98
+ validators (else after). Defaults to False.
99
+ each_item (bool, optional): For complex objects (sets, lists etc.) whether to validate
100
+ individual elements rather than the whole object. Defaults to False.
101
+ always (bool, optional): Whether this method and other validators should be called even if
102
+ the value is missing. Defaults to False.
103
+ check_fields (bool | None, optional): Whether to check that the fields actually exist on the model.
104
+ Defaults to None.
105
+ allow_reuse (bool, optional): Whether to track and raise an error if another validator refers to
106
+ the decorated function. Defaults to False.
107
+
108
+ Returns:
109
+ Callable: A decorator that can be used to decorate a
110
+ function to be used as a validator.
111
+ """
112
+ warn(
113
+ 'Pydantic V1 style `@validator` validators are deprecated.'
114
+ ' You should migrate to Pydantic V2 style `@field_validator` validators,'
115
+ ' see the migration guide for more details',
116
+ DeprecationWarning,
117
+ stacklevel=2,
118
+ )
119
+
120
+ if allow_reuse is True: # pragma: no cover
121
+ warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning, stacklevel=2)
122
+ fields = __field, *fields
123
+ if isinstance(fields[0], FunctionType):
124
+ raise PydanticUserError(
125
+ '`@validator` should be used with fields and keyword arguments, not bare. '
126
+ "E.g. usage should be `@validator('<field_name>', ...)`",
127
+ code='decorator-missing-arguments',
128
+ )
129
+ elif not all(isinstance(field, str) for field in fields):
130
+ raise PydanticUserError(
131
+ '`@validator` fields should be passed as separate string args. '
132
+ "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`",
133
+ code='decorator-invalid-fields',
134
+ )
135
+
136
+ mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
137
+
138
+ def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
139
+ if _decorators.is_instance_method_from_sig(f):
140
+ raise PydanticUserError(
141
+ '`@validator` cannot be applied to instance methods', code='validator-instance-method'
142
+ )
143
+ # auto apply the @classmethod decorator
144
+ f = _decorators.ensure_classmethod_based_on_signature(f)
145
+ wrap = _decorators_v1.make_generic_v1_field_validator
146
+ validator_wrapper_info = _decorators.ValidatorDecoratorInfo(
147
+ fields=fields,
148
+ mode=mode,
149
+ each_item=each_item,
150
+ always=always,
151
+ check_fields=check_fields,
152
+ )
153
+ return _decorators.PydanticDescriptorProxy(f, validator_wrapper_info, shim=wrap)
154
+
155
+ return dec # type: ignore[return-value]
156
+
157
+
158
+ @overload
159
+ def root_validator(
160
+ *,
161
+ # if you don't specify `pre` the default is `pre=False`
162
+ # which means you need to specify `skip_on_failure=True`
163
+ skip_on_failure: Literal[True],
164
+ allow_reuse: bool = ...,
165
+ ) -> Callable[
166
+ [_V1RootValidatorFunctionType],
167
+ _V1RootValidatorFunctionType,
168
+ ]: ...
169
+
170
+
171
+ @overload
172
+ def root_validator(
173
+ *,
174
+ # if you specify `pre=True` then you don't need to specify
175
+ # `skip_on_failure`, in fact it is not allowed as an argument!
176
+ pre: Literal[True],
177
+ allow_reuse: bool = ...,
178
+ ) -> Callable[
179
+ [_V1RootValidatorFunctionType],
180
+ _V1RootValidatorFunctionType,
181
+ ]: ...
182
+
183
+
184
+ @overload
185
+ def root_validator(
186
+ *,
187
+ # if you explicitly specify `pre=False` then you
188
+ # MUST specify `skip_on_failure=True`
189
+ pre: Literal[False],
190
+ skip_on_failure: Literal[True],
191
+ allow_reuse: bool = ...,
192
+ ) -> Callable[
193
+ [_V1RootValidatorFunctionType],
194
+ _V1RootValidatorFunctionType,
195
+ ]: ...
196
+
197
+
198
+ @deprecated(
199
+ 'Pydantic V1 style `@root_validator` validators are deprecated.'
200
+ ' You should migrate to Pydantic V2 style `@model_validator` validators,'
201
+ ' see the migration guide for more details',
202
+ category=None,
203
+ )
204
+ def root_validator(
205
+ *__args,
206
+ pre: bool = False,
207
+ skip_on_failure: bool = False,
208
+ allow_reuse: bool = False,
209
+ ) -> Any:
210
+ """Decorate methods on a model indicating that they should be used to validate (and perhaps
211
+ modify) data either before or after standard model parsing/validation is performed.
212
+
213
+ Args:
214
+ pre (bool, optional): Whether this validator should be called before the standard
215
+ validators (else after). Defaults to False.
216
+ skip_on_failure (bool, optional): Whether to stop validation and return as soon as a
217
+ failure is encountered. Defaults to False.
218
+ allow_reuse (bool, optional): Whether to track and raise an error if another validator
219
+ refers to the decorated function. Defaults to False.
220
+
221
+ Returns:
222
+ Any: A decorator that can be used to decorate a function to be used as a root_validator.
223
+ """
224
+ warn(
225
+ 'Pydantic V1 style `@root_validator` validators are deprecated.'
226
+ ' You should migrate to Pydantic V2 style `@model_validator` validators,'
227
+ ' see the migration guide for more details',
228
+ DeprecationWarning,
229
+ stacklevel=2,
230
+ )
231
+
232
+ if __args:
233
+ # Ensure a nice error is raised if someone attempts to use the bare decorator
234
+ return root_validator()(*__args) # type: ignore
235
+
236
+ if allow_reuse is True: # pragma: no cover
237
+ warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning, stacklevel=2)
238
+ mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
239
+ if pre is False and skip_on_failure is not True:
240
+ raise PydanticUserError(
241
+ 'If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`.'
242
+ ' Note that `@root_validator` is deprecated and should be replaced with `@model_validator`.',
243
+ code='root-validator-pre-skip',
244
+ )
245
+
246
+ wrap = partial(_decorators_v1.make_v1_generic_root_validator, pre=pre)
247
+
248
+ def dec(f: Callable[..., Any] | classmethod[Any, Any, Any] | staticmethod[Any, Any]) -> Any:
249
+ if _decorators.is_instance_method_from_sig(f):
250
+ raise TypeError('`@root_validator` cannot be applied to instance methods')
251
+ # auto apply the @classmethod decorator
252
+ res = _decorators.ensure_classmethod_based_on_signature(f)
253
+ dec_info = _decorators.RootValidatorDecoratorInfo(mode=mode)
254
+ return _decorators.PydanticDescriptorProxy(res, dec_info, shim=wrap)
255
+
256
+ return dec
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/config.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations as _annotations
2
+
3
+ import warnings
4
+ from typing import TYPE_CHECKING, Any, Literal
5
+
6
+ from typing_extensions import deprecated
7
+
8
+ from .._internal import _config
9
+ from ..warnings import PydanticDeprecatedSince20
10
+
11
+ if not TYPE_CHECKING:
12
+ # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
13
+ # and https://youtrack.jetbrains.com/issue/PY-51428
14
+ DeprecationWarning = PydanticDeprecatedSince20
15
+
16
+ __all__ = 'BaseConfig', 'Extra'
17
+
18
+
19
+ class _ConfigMetaclass(type):
20
+ def __getattr__(self, item: str) -> Any:
21
+ try:
22
+ obj = _config.config_defaults[item]
23
+ warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
24
+ return obj
25
+ except KeyError as exc:
26
+ raise AttributeError(f"type object '{self.__name__}' has no attribute {exc}") from exc
27
+
28
+
29
+ @deprecated('BaseConfig is deprecated. Use the `pydantic.ConfigDict` instead.', category=PydanticDeprecatedSince20)
30
+ class BaseConfig(metaclass=_ConfigMetaclass):
31
+ """This class is only retained for backwards compatibility.
32
+
33
+ !!! Warning "Deprecated"
34
+ BaseConfig is deprecated. Use the [`pydantic.ConfigDict`][pydantic.ConfigDict] instead.
35
+ """
36
+
37
+ def __getattr__(self, item: str) -> Any:
38
+ try:
39
+ obj = super().__getattribute__(item)
40
+ warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
41
+ return obj
42
+ except AttributeError as exc:
43
+ try:
44
+ return getattr(type(self), item)
45
+ except AttributeError:
46
+ # re-raising changes the displayed text to reflect that `self` is not a type
47
+ raise AttributeError(str(exc)) from exc
48
+
49
+ def __init_subclass__(cls, **kwargs: Any) -> None:
50
+ warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
51
+ return super().__init_subclass__(**kwargs)
52
+
53
+
54
+ class _ExtraMeta(type):
55
+ def __getattribute__(self, __name: str) -> Any:
56
+ # The @deprecated decorator accesses other attributes, so we only emit a warning for the expected ones
57
+ if __name in {'allow', 'ignore', 'forbid'}:
58
+ warnings.warn(
59
+ "`pydantic.config.Extra` is deprecated, use literal values instead (e.g. `extra='allow'`)",
60
+ DeprecationWarning,
61
+ stacklevel=2,
62
+ )
63
+ return super().__getattribute__(__name)
64
+
65
+
66
+ @deprecated(
67
+ "Extra is deprecated. Use literal values instead (e.g. `extra='allow'`)", category=PydanticDeprecatedSince20
68
+ )
69
+ class Extra(metaclass=_ExtraMeta):
70
+ allow: Literal['allow'] = 'allow'
71
+ ignore: Literal['ignore'] = 'ignore'
72
+ forbid: Literal['forbid'] = 'forbid'
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/copy_internals.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations as _annotations
2
+
3
+ import typing
4
+ from copy import deepcopy
5
+ from enum import Enum
6
+ from typing import Any
7
+
8
+ import typing_extensions
9
+
10
+ from .._internal import (
11
+ _model_construction,
12
+ _typing_extra,
13
+ _utils,
14
+ )
15
+
16
+ if typing.TYPE_CHECKING:
17
+ from .. import BaseModel
18
+ from .._internal._utils import AbstractSetIntStr, MappingIntStrAny
19
+
20
+ AnyClassMethod = classmethod[Any, Any, Any]
21
+ TupleGenerator = typing.Generator[tuple[str, Any], None, None]
22
+ Model = typing.TypeVar('Model', bound='BaseModel')
23
+ # should be `set[int] | set[str] | dict[int, IncEx] | dict[str, IncEx] | None`, but mypy can't cope
24
+ IncEx: typing_extensions.TypeAlias = 'set[int] | set[str] | dict[int, Any] | dict[str, Any] | None'
25
+
26
+ _object_setattr = _model_construction.object_setattr
27
+
28
+
29
+ def _iter(
30
+ self: BaseModel,
31
+ to_dict: bool = False,
32
+ by_alias: bool = False,
33
+ include: AbstractSetIntStr | MappingIntStrAny | None = None,
34
+ exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
35
+ exclude_unset: bool = False,
36
+ exclude_defaults: bool = False,
37
+ exclude_none: bool = False,
38
+ ) -> TupleGenerator:
39
+ # Merge field set excludes with explicit exclude parameter with explicit overriding field set options.
40
+ # The extra "is not None" guards are not logically necessary but optimizes performance for the simple case.
41
+ if exclude is not None:
42
+ exclude = _utils.ValueItems.merge(
43
+ {k: v.exclude for k, v in self.__pydantic_fields__.items() if v.exclude is not None}, exclude
44
+ )
45
+
46
+ if include is not None:
47
+ include = _utils.ValueItems.merge(dict.fromkeys(self.__pydantic_fields__, True), include, intersect=True)
48
+
49
+ allowed_keys = _calculate_keys(self, include=include, exclude=exclude, exclude_unset=exclude_unset) # type: ignore
50
+ if allowed_keys is None and not (to_dict or by_alias or exclude_unset or exclude_defaults or exclude_none):
51
+ # huge boost for plain _iter()
52
+ yield from self.__dict__.items()
53
+ if self.__pydantic_extra__:
54
+ yield from self.__pydantic_extra__.items()
55
+ return
56
+
57
+ value_exclude = _utils.ValueItems(self, exclude) if exclude is not None else None
58
+ value_include = _utils.ValueItems(self, include) if include is not None else None
59
+
60
+ if self.__pydantic_extra__ is None:
61
+ items = self.__dict__.items()
62
+ else:
63
+ items = list(self.__dict__.items()) + list(self.__pydantic_extra__.items())
64
+
65
+ for field_key, v in items:
66
+ if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None):
67
+ continue
68
+
69
+ if exclude_defaults:
70
+ try:
71
+ field = self.__pydantic_fields__[field_key]
72
+ except KeyError:
73
+ pass
74
+ else:
75
+ if not field.is_required() and field.default == v:
76
+ continue
77
+
78
+ if by_alias and field_key in self.__pydantic_fields__:
79
+ dict_key = self.__pydantic_fields__[field_key].alias or field_key
80
+ else:
81
+ dict_key = field_key
82
+
83
+ if to_dict or value_include or value_exclude:
84
+ v = _get_value(
85
+ type(self),
86
+ v,
87
+ to_dict=to_dict,
88
+ by_alias=by_alias,
89
+ include=value_include and value_include.for_element(field_key),
90
+ exclude=value_exclude and value_exclude.for_element(field_key),
91
+ exclude_unset=exclude_unset,
92
+ exclude_defaults=exclude_defaults,
93
+ exclude_none=exclude_none,
94
+ )
95
+ yield dict_key, v
96
+
97
+
98
+ def _copy_and_set_values(
99
+ self: Model,
100
+ values: dict[str, Any],
101
+ fields_set: set[str],
102
+ extra: dict[str, Any] | None = None,
103
+ private: dict[str, Any] | None = None,
104
+ *,
105
+ deep: bool, # UP006
106
+ ) -> Model:
107
+ if deep:
108
+ # chances of having empty dict here are quite low for using smart_deepcopy
109
+ values = deepcopy(values)
110
+ extra = deepcopy(extra)
111
+ private = deepcopy(private)
112
+
113
+ cls = self.__class__
114
+ m = cls.__new__(cls)
115
+ _object_setattr(m, '__dict__', values)
116
+ _object_setattr(m, '__pydantic_extra__', extra)
117
+ _object_setattr(m, '__pydantic_fields_set__', fields_set)
118
+ _object_setattr(m, '__pydantic_private__', private)
119
+
120
+ return m
121
+
122
+
123
+ @typing.no_type_check
124
+ def _get_value(
125
+ cls: type[BaseModel],
126
+ v: Any,
127
+ to_dict: bool,
128
+ by_alias: bool,
129
+ include: AbstractSetIntStr | MappingIntStrAny | None,
130
+ exclude: AbstractSetIntStr | MappingIntStrAny | None,
131
+ exclude_unset: bool,
132
+ exclude_defaults: bool,
133
+ exclude_none: bool,
134
+ ) -> Any:
135
+ from .. import BaseModel
136
+
137
+ if isinstance(v, BaseModel):
138
+ if to_dict:
139
+ return v.model_dump(
140
+ by_alias=by_alias,
141
+ exclude_unset=exclude_unset,
142
+ exclude_defaults=exclude_defaults,
143
+ include=include, # type: ignore
144
+ exclude=exclude, # type: ignore
145
+ exclude_none=exclude_none,
146
+ )
147
+ else:
148
+ return v.copy(include=include, exclude=exclude)
149
+
150
+ value_exclude = _utils.ValueItems(v, exclude) if exclude else None
151
+ value_include = _utils.ValueItems(v, include) if include else None
152
+
153
+ if isinstance(v, dict):
154
+ return {
155
+ k_: _get_value(
156
+ cls,
157
+ v_,
158
+ to_dict=to_dict,
159
+ by_alias=by_alias,
160
+ exclude_unset=exclude_unset,
161
+ exclude_defaults=exclude_defaults,
162
+ include=value_include and value_include.for_element(k_),
163
+ exclude=value_exclude and value_exclude.for_element(k_),
164
+ exclude_none=exclude_none,
165
+ )
166
+ for k_, v_ in v.items()
167
+ if (not value_exclude or not value_exclude.is_excluded(k_))
168
+ and (not value_include or value_include.is_included(k_))
169
+ }
170
+
171
+ elif _utils.sequence_like(v):
172
+ seq_args = (
173
+ _get_value(
174
+ cls,
175
+ v_,
176
+ to_dict=to_dict,
177
+ by_alias=by_alias,
178
+ exclude_unset=exclude_unset,
179
+ exclude_defaults=exclude_defaults,
180
+ include=value_include and value_include.for_element(i),
181
+ exclude=value_exclude and value_exclude.for_element(i),
182
+ exclude_none=exclude_none,
183
+ )
184
+ for i, v_ in enumerate(v)
185
+ if (not value_exclude or not value_exclude.is_excluded(i))
186
+ and (not value_include or value_include.is_included(i))
187
+ )
188
+
189
+ return v.__class__(*seq_args) if _typing_extra.is_namedtuple(v.__class__) else v.__class__(seq_args)
190
+
191
+ elif isinstance(v, Enum) and getattr(cls.model_config, 'use_enum_values', False):
192
+ return v.value
193
+
194
+ else:
195
+ return v
196
+
197
+
198
+ def _calculate_keys(
199
+ self: BaseModel,
200
+ include: MappingIntStrAny | None,
201
+ exclude: MappingIntStrAny | None,
202
+ exclude_unset: bool,
203
+ update: dict[str, Any] | None = None, # noqa UP006
204
+ ) -> typing.AbstractSet[str] | None:
205
+ if include is None and exclude is None and exclude_unset is False:
206
+ return None
207
+
208
+ keys: typing.AbstractSet[str]
209
+ if exclude_unset:
210
+ keys = self.__pydantic_fields_set__.copy()
211
+ else:
212
+ keys = set(self.__dict__.keys())
213
+ keys = keys | (self.__pydantic_extra__ or {}).keys()
214
+
215
+ if include is not None:
216
+ keys &= include.keys()
217
+
218
+ if update:
219
+ keys -= update.keys()
220
+
221
+ if exclude:
222
+ keys -= {k for k, v in exclude.items() if _utils.ValueItems.is_true(v)}
223
+
224
+ return keys
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/decorator.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from collections.abc import Mapping
3
+ from functools import wraps
4
+ from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union, overload
5
+
6
+ from typing_extensions import deprecated
7
+
8
+ from .._internal import _config, _typing_extra
9
+ from ..alias_generators import to_pascal
10
+ from ..errors import PydanticUserError
11
+ from ..functional_validators import field_validator
12
+ from ..main import BaseModel, create_model
13
+ from ..warnings import PydanticDeprecatedSince20
14
+
15
+ if not TYPE_CHECKING:
16
+ # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
17
+ # and https://youtrack.jetbrains.com/issue/PY-51428
18
+ DeprecationWarning = PydanticDeprecatedSince20
19
+
20
+ __all__ = ('validate_arguments',)
21
+
22
+ if TYPE_CHECKING:
23
+ AnyCallable = Callable[..., Any]
24
+
25
+ AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable)
26
+ ConfigType = Union[None, type[Any], dict[str, Any]]
27
+
28
+
29
+ @overload
30
+ def validate_arguments(
31
+ func: None = None, *, config: 'ConfigType' = None
32
+ ) -> Callable[['AnyCallableT'], 'AnyCallableT']: ...
33
+
34
+
35
+ @overload
36
+ def validate_arguments(func: 'AnyCallableT') -> 'AnyCallableT': ...
37
+
38
+
39
+ @deprecated(
40
+ 'The `validate_arguments` method is deprecated; use `validate_call` instead.',
41
+ category=None,
42
+ )
43
+ def validate_arguments(func: Optional['AnyCallableT'] = None, *, config: 'ConfigType' = None) -> Any:
44
+ """Decorator to validate the arguments passed to a function."""
45
+ warnings.warn(
46
+ 'The `validate_arguments` method is deprecated; use `validate_call` instead.',
47
+ PydanticDeprecatedSince20,
48
+ stacklevel=2,
49
+ )
50
+
51
+ def validate(_func: 'AnyCallable') -> 'AnyCallable':
52
+ vd = ValidatedFunction(_func, config)
53
+
54
+ @wraps(_func)
55
+ def wrapper_function(*args: Any, **kwargs: Any) -> Any:
56
+ return vd.call(*args, **kwargs)
57
+
58
+ wrapper_function.vd = vd # type: ignore
59
+ wrapper_function.validate = vd.init_model_instance # type: ignore
60
+ wrapper_function.raw_function = vd.raw_function # type: ignore
61
+ wrapper_function.model = vd.model # type: ignore
62
+ return wrapper_function
63
+
64
+ if func:
65
+ return validate(func)
66
+ else:
67
+ return validate
68
+
69
+
70
+ ALT_V_ARGS = 'v__args'
71
+ ALT_V_KWARGS = 'v__kwargs'
72
+ V_POSITIONAL_ONLY_NAME = 'v__positional_only'
73
+ V_DUPLICATE_KWARGS = 'v__duplicate_kwargs'
74
+
75
+
76
+ class ValidatedFunction:
77
+ def __init__(self, function: 'AnyCallable', config: 'ConfigType'):
78
+ from inspect import Parameter, signature
79
+
80
+ parameters: Mapping[str, Parameter] = signature(function).parameters
81
+
82
+ if parameters.keys() & {ALT_V_ARGS, ALT_V_KWARGS, V_POSITIONAL_ONLY_NAME, V_DUPLICATE_KWARGS}:
83
+ raise PydanticUserError(
84
+ f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" '
85
+ f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator',
86
+ code=None,
87
+ )
88
+
89
+ self.raw_function = function
90
+ self.arg_mapping: dict[int, str] = {}
91
+ self.positional_only_args: set[str] = set()
92
+ self.v_args_name = 'args'
93
+ self.v_kwargs_name = 'kwargs'
94
+
95
+ type_hints = _typing_extra.get_type_hints(function, include_extras=True)
96
+ takes_args = False
97
+ takes_kwargs = False
98
+ fields: dict[str, tuple[Any, Any]] = {}
99
+ for i, (name, p) in enumerate(parameters.items()):
100
+ if p.annotation is p.empty:
101
+ annotation = Any
102
+ else:
103
+ annotation = type_hints[name]
104
+
105
+ default = ... if p.default is p.empty else p.default
106
+ if p.kind == Parameter.POSITIONAL_ONLY:
107
+ self.arg_mapping[i] = name
108
+ fields[name] = annotation, default
109
+ fields[V_POSITIONAL_ONLY_NAME] = list[str], None
110
+ self.positional_only_args.add(name)
111
+ elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
112
+ self.arg_mapping[i] = name
113
+ fields[name] = annotation, default
114
+ fields[V_DUPLICATE_KWARGS] = list[str], None
115
+ elif p.kind == Parameter.KEYWORD_ONLY:
116
+ fields[name] = annotation, default
117
+ elif p.kind == Parameter.VAR_POSITIONAL:
118
+ self.v_args_name = name
119
+ fields[name] = tuple[annotation, ...], None
120
+ takes_args = True
121
+ else:
122
+ assert p.kind == Parameter.VAR_KEYWORD, p.kind
123
+ self.v_kwargs_name = name
124
+ fields[name] = dict[str, annotation], None
125
+ takes_kwargs = True
126
+
127
+ # these checks avoid a clash between "args" and a field with that name
128
+ if not takes_args and self.v_args_name in fields:
129
+ self.v_args_name = ALT_V_ARGS
130
+
131
+ # same with "kwargs"
132
+ if not takes_kwargs and self.v_kwargs_name in fields:
133
+ self.v_kwargs_name = ALT_V_KWARGS
134
+
135
+ if not takes_args:
136
+ # we add the field so validation below can raise the correct exception
137
+ fields[self.v_args_name] = list[Any], None
138
+
139
+ if not takes_kwargs:
140
+ # same with kwargs
141
+ fields[self.v_kwargs_name] = dict[Any, Any], None
142
+
143
+ self.create_model(fields, takes_args, takes_kwargs, config)
144
+
145
+ def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel:
146
+ values = self.build_values(args, kwargs)
147
+ return self.model(**values)
148
+
149
+ def call(self, *args: Any, **kwargs: Any) -> Any:
150
+ m = self.init_model_instance(*args, **kwargs)
151
+ return self.execute(m)
152
+
153
+ def build_values(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> dict[str, Any]:
154
+ values: dict[str, Any] = {}
155
+ if args:
156
+ arg_iter = enumerate(args)
157
+ while True:
158
+ try:
159
+ i, a = next(arg_iter)
160
+ except StopIteration:
161
+ break
162
+ arg_name = self.arg_mapping.get(i)
163
+ if arg_name is not None:
164
+ values[arg_name] = a
165
+ else:
166
+ values[self.v_args_name] = [a] + [a for _, a in arg_iter]
167
+ break
168
+
169
+ var_kwargs: dict[str, Any] = {}
170
+ wrong_positional_args = []
171
+ duplicate_kwargs = []
172
+ fields_alias = [
173
+ field.alias
174
+ for name, field in self.model.__pydantic_fields__.items()
175
+ if name not in (self.v_args_name, self.v_kwargs_name)
176
+ ]
177
+ non_var_fields = set(self.model.__pydantic_fields__) - {self.v_args_name, self.v_kwargs_name}
178
+ for k, v in kwargs.items():
179
+ if k in non_var_fields or k in fields_alias:
180
+ if k in self.positional_only_args:
181
+ wrong_positional_args.append(k)
182
+ if k in values:
183
+ duplicate_kwargs.append(k)
184
+ values[k] = v
185
+ else:
186
+ var_kwargs[k] = v
187
+
188
+ if var_kwargs:
189
+ values[self.v_kwargs_name] = var_kwargs
190
+ if wrong_positional_args:
191
+ values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args
192
+ if duplicate_kwargs:
193
+ values[V_DUPLICATE_KWARGS] = duplicate_kwargs
194
+ return values
195
+
196
+ def execute(self, m: BaseModel) -> Any:
197
+ d = {
198
+ k: v
199
+ for k, v in m.__dict__.items()
200
+ if k in m.__pydantic_fields_set__ or m.__pydantic_fields__[k].default_factory
201
+ }
202
+ var_kwargs = d.pop(self.v_kwargs_name, {})
203
+
204
+ if self.v_args_name in d:
205
+ args_: list[Any] = []
206
+ in_kwargs = False
207
+ kwargs = {}
208
+ for name, value in d.items():
209
+ if in_kwargs:
210
+ kwargs[name] = value
211
+ elif name == self.v_args_name:
212
+ args_ += value
213
+ in_kwargs = True
214
+ else:
215
+ args_.append(value)
216
+ return self.raw_function(*args_, **kwargs, **var_kwargs)
217
+ elif self.positional_only_args:
218
+ args_ = []
219
+ kwargs = {}
220
+ for name, value in d.items():
221
+ if name in self.positional_only_args:
222
+ args_.append(value)
223
+ else:
224
+ kwargs[name] = value
225
+ return self.raw_function(*args_, **kwargs, **var_kwargs)
226
+ else:
227
+ return self.raw_function(**d, **var_kwargs)
228
+
229
+ def create_model(self, fields: dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None:
230
+ pos_args = len(self.arg_mapping)
231
+
232
+ config_wrapper = _config.ConfigWrapper(config)
233
+
234
+ if config_wrapper.alias_generator:
235
+ raise PydanticUserError(
236
+ 'Setting the "alias_generator" property on custom Config for '
237
+ '@validate_arguments is not yet supported, please remove.',
238
+ code=None,
239
+ )
240
+ if config_wrapper.extra is None:
241
+ config_wrapper.config_dict['extra'] = 'forbid'
242
+
243
+ class DecoratorBaseModel(BaseModel):
244
+ @field_validator(self.v_args_name, check_fields=False)
245
+ @classmethod
246
+ def check_args(cls, v: Optional[list[Any]]) -> Optional[list[Any]]:
247
+ if takes_args or v is None:
248
+ return v
249
+
250
+ raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given')
251
+
252
+ @field_validator(self.v_kwargs_name, check_fields=False)
253
+ @classmethod
254
+ def check_kwargs(cls, v: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
255
+ if takes_kwargs or v is None:
256
+ return v
257
+
258
+ plural = '' if len(v) == 1 else 's'
259
+ keys = ', '.join(map(repr, v.keys()))
260
+ raise TypeError(f'unexpected keyword argument{plural}: {keys}')
261
+
262
+ @field_validator(V_POSITIONAL_ONLY_NAME, check_fields=False)
263
+ @classmethod
264
+ def check_positional_only(cls, v: Optional[list[str]]) -> None:
265
+ if v is None:
266
+ return
267
+
268
+ plural = '' if len(v) == 1 else 's'
269
+ keys = ', '.join(map(repr, v))
270
+ raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}')
271
+
272
+ @field_validator(V_DUPLICATE_KWARGS, check_fields=False)
273
+ @classmethod
274
+ def check_duplicate_kwargs(cls, v: Optional[list[str]]) -> None:
275
+ if v is None:
276
+ return
277
+
278
+ plural = '' if len(v) == 1 else 's'
279
+ keys = ', '.join(map(repr, v))
280
+ raise TypeError(f'multiple values for argument{plural}: {keys}')
281
+
282
+ model_config = config_wrapper.config_dict
283
+
284
+ self.model = create_model(to_pascal(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/json.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import warnings
3
+ from collections import deque
4
+ from decimal import Decimal
5
+ from enum import Enum
6
+ from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
7
+ from pathlib import Path
8
+ from re import Pattern
9
+ from types import GeneratorType
10
+ from typing import TYPE_CHECKING, Any, Callable, Union
11
+ from uuid import UUID
12
+
13
+ from typing_extensions import deprecated
14
+
15
+ from .._internal._import_utils import import_cached_base_model
16
+ from ..color import Color
17
+ from ..networks import NameEmail
18
+ from ..types import SecretBytes, SecretStr
19
+ from ..warnings import PydanticDeprecatedSince20
20
+
21
+ if not TYPE_CHECKING:
22
+ # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
23
+ # and https://youtrack.jetbrains.com/issue/PY-51428
24
+ DeprecationWarning = PydanticDeprecatedSince20
25
+
26
+ __all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
27
+
28
+
29
+ def isoformat(o: Union[datetime.date, datetime.time]) -> str:
30
+ return o.isoformat()
31
+
32
+
33
+ def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
34
+ """Encodes a Decimal as int of there's no exponent, otherwise float.
35
+
36
+ This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
37
+ where a integer (but not int typed) is used. Encoding this as a float
38
+ results in failed round-tripping between encode and parse.
39
+ Our Id type is a prime example of this.
40
+
41
+ >>> decimal_encoder(Decimal("1.0"))
42
+ 1.0
43
+
44
+ >>> decimal_encoder(Decimal("1"))
45
+ 1
46
+ """
47
+ exponent = dec_value.as_tuple().exponent
48
+ if isinstance(exponent, int) and exponent >= 0:
49
+ return int(dec_value)
50
+ else:
51
+ return float(dec_value)
52
+
53
+
54
+ ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = {
55
+ bytes: lambda o: o.decode(),
56
+ Color: str,
57
+ datetime.date: isoformat,
58
+ datetime.datetime: isoformat,
59
+ datetime.time: isoformat,
60
+ datetime.timedelta: lambda td: td.total_seconds(),
61
+ Decimal: decimal_encoder,
62
+ Enum: lambda o: o.value,
63
+ frozenset: list,
64
+ deque: list,
65
+ GeneratorType: list,
66
+ IPv4Address: str,
67
+ IPv4Interface: str,
68
+ IPv4Network: str,
69
+ IPv6Address: str,
70
+ IPv6Interface: str,
71
+ IPv6Network: str,
72
+ NameEmail: str,
73
+ Path: str,
74
+ Pattern: lambda o: o.pattern,
75
+ SecretBytes: str,
76
+ SecretStr: str,
77
+ set: list,
78
+ UUID: str,
79
+ }
80
+
81
+
82
+ @deprecated(
83
+ '`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
84
+ category=None,
85
+ )
86
+ def pydantic_encoder(obj: Any) -> Any:
87
+ warnings.warn(
88
+ '`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.',
89
+ category=PydanticDeprecatedSince20,
90
+ stacklevel=2,
91
+ )
92
+ from dataclasses import asdict, is_dataclass
93
+
94
+ BaseModel = import_cached_base_model()
95
+
96
+ if isinstance(obj, BaseModel):
97
+ return obj.model_dump()
98
+ elif is_dataclass(obj):
99
+ return asdict(obj) # type: ignore
100
+
101
+ # Check the class type and its superclasses for a matching encoder
102
+ for base in obj.__class__.__mro__[:-1]:
103
+ try:
104
+ encoder = ENCODERS_BY_TYPE[base]
105
+ except KeyError:
106
+ continue
107
+ return encoder(obj)
108
+ else: # We have exited the for loop without finding a suitable encoder
109
+ raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
110
+
111
+
112
+ # TODO: Add a suggested migration path once there is a way to use custom encoders
113
+ @deprecated(
114
+ '`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
115
+ category=None,
116
+ )
117
+ def custom_pydantic_encoder(type_encoders: dict[Any, Callable[[type[Any]], Any]], obj: Any) -> Any:
118
+ warnings.warn(
119
+ '`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.',
120
+ category=PydanticDeprecatedSince20,
121
+ stacklevel=2,
122
+ )
123
+ # Check the class type and its superclasses for a matching encoder
124
+ for base in obj.__class__.__mro__[:-1]:
125
+ try:
126
+ encoder = type_encoders[base]
127
+ except KeyError:
128
+ continue
129
+
130
+ return encoder(obj)
131
+ else: # We have exited the for loop without finding a suitable encoder
132
+ return pydantic_encoder(obj)
133
+
134
+
135
+ @deprecated('`timedelta_isoformat` is deprecated.', category=None)
136
+ def timedelta_isoformat(td: datetime.timedelta) -> str:
137
+ """ISO 8601 encoding for Python timedelta object."""
138
+ warnings.warn('`timedelta_isoformat` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
139
+ minutes, seconds = divmod(td.seconds, 60)
140
+ hours, minutes = divmod(minutes, 60)
141
+ return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/parse.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import pickle
5
+ import warnings
6
+ from enum import Enum
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Any, Callable
9
+
10
+ from typing_extensions import deprecated
11
+
12
+ from ..warnings import PydanticDeprecatedSince20
13
+
14
+ if not TYPE_CHECKING:
15
+ # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
16
+ # and https://youtrack.jetbrains.com/issue/PY-51428
17
+ DeprecationWarning = PydanticDeprecatedSince20
18
+
19
+
20
+ class Protocol(str, Enum):
21
+ json = 'json'
22
+ pickle = 'pickle'
23
+
24
+
25
+ @deprecated('`load_str_bytes` is deprecated.', category=None)
26
+ def load_str_bytes(
27
+ b: str | bytes,
28
+ *,
29
+ content_type: str | None = None,
30
+ encoding: str = 'utf8',
31
+ proto: Protocol | None = None,
32
+ allow_pickle: bool = False,
33
+ json_loads: Callable[[str], Any] = json.loads,
34
+ ) -> Any:
35
+ warnings.warn('`load_str_bytes` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
36
+ if proto is None and content_type:
37
+ if content_type.endswith(('json', 'javascript')):
38
+ pass
39
+ elif allow_pickle and content_type.endswith('pickle'):
40
+ proto = Protocol.pickle
41
+ else:
42
+ raise TypeError(f'Unknown content-type: {content_type}')
43
+
44
+ proto = proto or Protocol.json
45
+
46
+ if proto == Protocol.json:
47
+ if isinstance(b, bytes):
48
+ b = b.decode(encoding)
49
+ return json_loads(b) # type: ignore
50
+ elif proto == Protocol.pickle:
51
+ if not allow_pickle:
52
+ raise RuntimeError('Trying to decode with pickle with allow_pickle=False')
53
+ bb = b if isinstance(b, bytes) else b.encode() # type: ignore
54
+ return pickle.loads(bb)
55
+ else:
56
+ raise TypeError(f'Unknown protocol: {proto}')
57
+
58
+
59
+ @deprecated('`load_file` is deprecated.', category=None)
60
+ def load_file(
61
+ path: str | Path,
62
+ *,
63
+ content_type: str | None = None,
64
+ encoding: str = 'utf8',
65
+ proto: Protocol | None = None,
66
+ allow_pickle: bool = False,
67
+ json_loads: Callable[[str], Any] = json.loads,
68
+ ) -> Any:
69
+ warnings.warn('`load_file` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2)
70
+ path = Path(path)
71
+ b = path.read_bytes()
72
+ if content_type is None:
73
+ if path.suffix in ('.js', '.json'):
74
+ proto = Protocol.json
75
+ elif path.suffix == '.pkl':
76
+ proto = Protocol.pickle
77
+
78
+ return load_str_bytes(
79
+ b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads
80
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/deprecated/tools.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import warnings
5
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union
6
+
7
+ from typing_extensions import deprecated
8
+
9
+ from ..json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema
10
+ from ..type_adapter import TypeAdapter
11
+ from ..warnings import PydanticDeprecatedSince20
12
+
13
+ if not TYPE_CHECKING:
14
+ # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915
15
+ # and https://youtrack.jetbrains.com/issue/PY-51428
16
+ DeprecationWarning = PydanticDeprecatedSince20
17
+
18
+ __all__ = 'parse_obj_as', 'schema_of', 'schema_json_of'
19
+
20
+ NameFactory = Union[str, Callable[[type[Any]], str]]
21
+
22
+
23
+ T = TypeVar('T')
24
+
25
+
26
+ @deprecated(
27
+ '`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.',
28
+ category=None,
29
+ )
30
+ def parse_obj_as(type_: type[T], obj: Any, type_name: NameFactory | None = None) -> T:
31
+ warnings.warn(
32
+ '`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.',
33
+ category=PydanticDeprecatedSince20,
34
+ stacklevel=2,
35
+ )
36
+ if type_name is not None: # pragma: no cover
37
+ warnings.warn(
38
+ 'The type_name parameter is deprecated. parse_obj_as no longer creates temporary models',
39
+ DeprecationWarning,
40
+ stacklevel=2,
41
+ )
42
+ return TypeAdapter(type_).validate_python(obj)
43
+
44
+
45
+ @deprecated(
46
+ '`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
47
+ category=None,
48
+ )
49
+ def schema_of(
50
+ type_: Any,
51
+ *,
52
+ title: NameFactory | None = None,
53
+ by_alias: bool = True,
54
+ ref_template: str = DEFAULT_REF_TEMPLATE,
55
+ schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
56
+ ) -> dict[str, Any]:
57
+ """Generate a JSON schema (as dict) for the passed model or dynamically generated one."""
58
+ warnings.warn(
59
+ '`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
60
+ category=PydanticDeprecatedSince20,
61
+ stacklevel=2,
62
+ )
63
+ res = TypeAdapter(type_).json_schema(
64
+ by_alias=by_alias,
65
+ schema_generator=schema_generator,
66
+ ref_template=ref_template,
67
+ )
68
+ if title is not None:
69
+ if isinstance(title, str):
70
+ res['title'] = title
71
+ else:
72
+ warnings.warn(
73
+ 'Passing a callable for the `title` parameter is deprecated and no longer supported',
74
+ DeprecationWarning,
75
+ stacklevel=2,
76
+ )
77
+ res['title'] = title(type_)
78
+ return res
79
+
80
+
81
+ @deprecated(
82
+ '`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
83
+ category=None,
84
+ )
85
+ def schema_json_of(
86
+ type_: Any,
87
+ *,
88
+ title: NameFactory | None = None,
89
+ by_alias: bool = True,
90
+ ref_template: str = DEFAULT_REF_TEMPLATE,
91
+ schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
92
+ **dumps_kwargs: Any,
93
+ ) -> str:
94
+ """Generate a JSON schema (as JSON) for the passed model or dynamically generated one."""
95
+ warnings.warn(
96
+ '`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.',
97
+ category=PydanticDeprecatedSince20,
98
+ stacklevel=2,
99
+ )
100
+ return json.dumps(
101
+ schema_of(type_, title=title, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator),
102
+ **dumps_kwargs,
103
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/experimental/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """The "experimental" module of pydantic contains potential new features that are subject to change."""
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/experimental/arguments_schema.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Experimental module exposing a function to generate a core schema that validates callable arguments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any, Literal
7
+
8
+ from pydantic_core import CoreSchema
9
+
10
+ from pydantic import ConfigDict
11
+ from pydantic._internal import _config, _generate_schema, _namespace_utils
12
+
13
+
14
+ def generate_arguments_schema(
15
+ func: Callable[..., Any],
16
+ schema_type: Literal['arguments', 'arguments-v3'] = 'arguments-v3',
17
+ parameters_callback: Callable[[int, str, Any], Literal['skip'] | None] | None = None,
18
+ config: ConfigDict | None = None,
19
+ ) -> CoreSchema:
20
+ """Generate the schema for the arguments of a function.
21
+
22
+ Args:
23
+ func: The function to generate the schema for.
24
+ schema_type: The type of schema to generate.
25
+ parameters_callback: A callable that will be invoked for each parameter. The callback
26
+ should take three required arguments: the index, the name and the type annotation
27
+ (or [`Parameter.empty`][inspect.Parameter.empty] if not annotated) of the parameter.
28
+ The callback can optionally return `'skip'`, so that the parameter gets excluded
29
+ from the resulting schema.
30
+ config: The configuration to use.
31
+
32
+ Returns:
33
+ The generated schema.
34
+ """
35
+ generate_schema = _generate_schema.GenerateSchema(
36
+ _config.ConfigWrapper(config),
37
+ ns_resolver=_namespace_utils.NsResolver(namespaces_tuple=_namespace_utils.ns_for_function(func)),
38
+ )
39
+
40
+ if schema_type == 'arguments':
41
+ schema = generate_schema._arguments_schema(func, parameters_callback) # pyright: ignore[reportArgumentType]
42
+ else:
43
+ schema = generate_schema._arguments_v3_schema(func, parameters_callback) # pyright: ignore[reportArgumentType]
44
+ return generate_schema.clean_schema(schema)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/experimental/missing_sentinel.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Experimental module exposing a function a `MISSING` sentinel."""
2
+
3
+ from pydantic_core import MISSING
4
+
5
+ __all__ = ('MISSING',)
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/experimental/pipeline.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Experimental pipeline API functionality. Be careful with this API, it's subject to change."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import operator
7
+ import re
8
+ import sys
9
+ from collections import deque
10
+ from collections.abc import Container
11
+ from dataclasses import dataclass
12
+ from decimal import Decimal
13
+ from functools import cached_property, partial
14
+ from re import Pattern
15
+ from typing import TYPE_CHECKING, Annotated, Any, Callable, Generic, Protocol, TypeVar, Union, overload
16
+
17
+ import annotated_types
18
+
19
+ if TYPE_CHECKING:
20
+ from pydantic import GetCoreSchemaHandler
21
+
22
+ from pydantic_core import PydanticCustomError
23
+ from pydantic_core import core_schema as cs
24
+
25
+ from pydantic import Strict
26
+ from pydantic._internal._internal_dataclass import slots_true as _slots_true
27
+
28
+ if sys.version_info < (3, 10):
29
+ EllipsisType = type(Ellipsis)
30
+ else:
31
+ from types import EllipsisType
32
+
33
+ __all__ = ['validate_as', 'validate_as_deferred', 'transform']
34
+
35
+ _slots_frozen = {**_slots_true, 'frozen': True}
36
+
37
+
38
+ @dataclass(**_slots_frozen)
39
+ class _ValidateAs:
40
+ tp: type[Any]
41
+ strict: bool = False
42
+
43
+
44
+ @dataclass
45
+ class _ValidateAsDefer:
46
+ func: Callable[[], type[Any]]
47
+
48
+ @cached_property
49
+ def tp(self) -> type[Any]:
50
+ return self.func()
51
+
52
+
53
+ @dataclass(**_slots_frozen)
54
+ class _Transform:
55
+ func: Callable[[Any], Any]
56
+
57
+
58
+ @dataclass(**_slots_frozen)
59
+ class _PipelineOr:
60
+ left: _Pipeline[Any, Any]
61
+ right: _Pipeline[Any, Any]
62
+
63
+
64
+ @dataclass(**_slots_frozen)
65
+ class _PipelineAnd:
66
+ left: _Pipeline[Any, Any]
67
+ right: _Pipeline[Any, Any]
68
+
69
+
70
+ @dataclass(**_slots_frozen)
71
+ class _Eq:
72
+ value: Any
73
+
74
+
75
+ @dataclass(**_slots_frozen)
76
+ class _NotEq:
77
+ value: Any
78
+
79
+
80
+ @dataclass(**_slots_frozen)
81
+ class _In:
82
+ values: Container[Any]
83
+
84
+
85
+ @dataclass(**_slots_frozen)
86
+ class _NotIn:
87
+ values: Container[Any]
88
+
89
+
90
+ _ConstraintAnnotation = Union[
91
+ annotated_types.Le,
92
+ annotated_types.Ge,
93
+ annotated_types.Lt,
94
+ annotated_types.Gt,
95
+ annotated_types.Len,
96
+ annotated_types.MultipleOf,
97
+ annotated_types.Timezone,
98
+ annotated_types.Interval,
99
+ annotated_types.Predicate,
100
+ # common predicates not included in annotated_types
101
+ _Eq,
102
+ _NotEq,
103
+ _In,
104
+ _NotIn,
105
+ # regular expressions
106
+ Pattern[str],
107
+ ]
108
+
109
+
110
+ @dataclass(**_slots_frozen)
111
+ class _Constraint:
112
+ constraint: _ConstraintAnnotation
113
+
114
+
115
+ _Step = Union[_ValidateAs, _ValidateAsDefer, _Transform, _PipelineOr, _PipelineAnd, _Constraint]
116
+
117
+ _InT = TypeVar('_InT')
118
+ _OutT = TypeVar('_OutT')
119
+ _NewOutT = TypeVar('_NewOutT')
120
+
121
+
122
+ class _FieldTypeMarker:
123
+ pass
124
+
125
+
126
+ # TODO: ultimately, make this public, see https://github.com/pydantic/pydantic/pull/9459#discussion_r1628197626
127
+ # Also, make this frozen eventually, but that doesn't work right now because of the generic base
128
+ # Which attempts to modify __orig_base__ and such.
129
+ # We could go with a manual freeze, but that seems overkill for now.
130
+ @dataclass(**_slots_true)
131
+ class _Pipeline(Generic[_InT, _OutT]):
132
+ """Abstract representation of a chain of validation, transformation, and parsing steps."""
133
+
134
+ _steps: tuple[_Step, ...]
135
+
136
+ def transform(
137
+ self,
138
+ func: Callable[[_OutT], _NewOutT],
139
+ ) -> _Pipeline[_InT, _NewOutT]:
140
+ """Transform the output of the previous step.
141
+
142
+ If used as the first step in a pipeline, the type of the field is used.
143
+ That is, the transformation is applied to after the value is parsed to the field's type.
144
+ """
145
+ return _Pipeline[_InT, _NewOutT](self._steps + (_Transform(func),))
146
+
147
+ @overload
148
+ def validate_as(self, tp: type[_NewOutT], *, strict: bool = False) -> _Pipeline[_InT, _NewOutT]: ...
149
+
150
+ @overload
151
+ def validate_as(
152
+ self,
153
+ tp: ellipsis, # noqa: F821 # TODO: use `_typing_extra.EllipsisType` when we drop Py3.9
154
+ *,
155
+ strict: bool = False,
156
+ ) -> _Pipeline[_InT, Any]: ...
157
+
158
+ # TODO PEP 747: use TypeForm to properly type Annotated aliases (e.g. NewPath, FilePath).
159
+ # This fallback accepts any type expression but loses generic type inference.
160
+ @overload
161
+ def validate_as(self, tp: Any, *, strict: bool = ...) -> _Pipeline[_InT, Any]: ...
162
+
163
+ def validate_as(self, tp: type[_NewOutT] | EllipsisType | Any, *, strict: bool = False) -> _Pipeline[_InT, Any]: # type: ignore
164
+ """Validate / parse the input into a new type.
165
+
166
+ If no type is provided, the type of the field is used.
167
+
168
+ Types are parsed in Pydantic's `lax` mode by default,
169
+ but you can enable `strict` mode by passing `strict=True`.
170
+ """
171
+ if isinstance(tp, EllipsisType):
172
+ return _Pipeline[_InT, Any](self._steps + (_ValidateAs(_FieldTypeMarker, strict=strict),))
173
+ return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAs(tp, strict=strict),))
174
+
175
+ def validate_as_deferred(self, func: Callable[[], type[_NewOutT]]) -> _Pipeline[_InT, _NewOutT]:
176
+ """Parse the input into a new type, deferring resolution of the type until the current class
177
+ is fully defined.
178
+
179
+ This is useful when you need to reference the class in it's own type annotations.
180
+ """
181
+ return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAsDefer(func),))
182
+
183
+ # constraints
184
+ @overload
185
+ def constrain(self: _Pipeline[_InT, _NewOutGe], constraint: annotated_types.Ge) -> _Pipeline[_InT, _NewOutGe]: ...
186
+
187
+ @overload
188
+ def constrain(self: _Pipeline[_InT, _NewOutGt], constraint: annotated_types.Gt) -> _Pipeline[_InT, _NewOutGt]: ...
189
+
190
+ @overload
191
+ def constrain(self: _Pipeline[_InT, _NewOutLe], constraint: annotated_types.Le) -> _Pipeline[_InT, _NewOutLe]: ...
192
+
193
+ @overload
194
+ def constrain(self: _Pipeline[_InT, _NewOutLt], constraint: annotated_types.Lt) -> _Pipeline[_InT, _NewOutLt]: ...
195
+
196
+ @overload
197
+ def constrain(
198
+ self: _Pipeline[_InT, _NewOutLen], constraint: annotated_types.Len
199
+ ) -> _Pipeline[_InT, _NewOutLen]: ...
200
+
201
+ @overload
202
+ def constrain(
203
+ self: _Pipeline[_InT, _NewOutT], constraint: annotated_types.MultipleOf
204
+ ) -> _Pipeline[_InT, _NewOutT]: ...
205
+
206
+ @overload
207
+ def constrain(
208
+ self: _Pipeline[_InT, _NewOutDatetime], constraint: annotated_types.Timezone
209
+ ) -> _Pipeline[_InT, _NewOutDatetime]: ...
210
+
211
+ @overload
212
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: annotated_types.Predicate) -> _Pipeline[_InT, _OutT]: ...
213
+
214
+ @overload
215
+ def constrain(
216
+ self: _Pipeline[_InT, _NewOutInterval], constraint: annotated_types.Interval
217
+ ) -> _Pipeline[_InT, _NewOutInterval]: ...
218
+
219
+ @overload
220
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: _Eq) -> _Pipeline[_InT, _OutT]: ...
221
+
222
+ @overload
223
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotEq) -> _Pipeline[_InT, _OutT]: ...
224
+
225
+ @overload
226
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: _In) -> _Pipeline[_InT, _OutT]: ...
227
+
228
+ @overload
229
+ def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotIn) -> _Pipeline[_InT, _OutT]: ...
230
+
231
+ @overload
232
+ def constrain(self: _Pipeline[_InT, _NewOutT], constraint: Pattern[str]) -> _Pipeline[_InT, _NewOutT]: ...
233
+
234
+ def constrain(self, constraint: _ConstraintAnnotation) -> Any:
235
+ """Constrain a value to meet a certain condition.
236
+
237
+ We support most conditions from `annotated_types`, as well as regular expressions.
238
+
239
+ Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc
240
+ so you don't need to call this directly.
241
+ """
242
+ return _Pipeline[_InT, _OutT](self._steps + (_Constraint(constraint),))
243
+
244
+ def predicate(self: _Pipeline[_InT, _NewOutT], func: Callable[[_NewOutT], bool]) -> _Pipeline[_InT, _NewOutT]:
245
+ """Constrain a value to meet a certain predicate."""
246
+ return self.constrain(annotated_types.Predicate(func))
247
+
248
+ def gt(self: _Pipeline[_InT, _NewOutGt], gt: _NewOutGt) -> _Pipeline[_InT, _NewOutGt]:
249
+ """Constrain a value to be greater than a certain value."""
250
+ return self.constrain(annotated_types.Gt(gt))
251
+
252
+ def lt(self: _Pipeline[_InT, _NewOutLt], lt: _NewOutLt) -> _Pipeline[_InT, _NewOutLt]:
253
+ """Constrain a value to be less than a certain value."""
254
+ return self.constrain(annotated_types.Lt(lt))
255
+
256
+ def ge(self: _Pipeline[_InT, _NewOutGe], ge: _NewOutGe) -> _Pipeline[_InT, _NewOutGe]:
257
+ """Constrain a value to be greater than or equal to a certain value."""
258
+ return self.constrain(annotated_types.Ge(ge))
259
+
260
+ def le(self: _Pipeline[_InT, _NewOutLe], le: _NewOutLe) -> _Pipeline[_InT, _NewOutLe]:
261
+ """Constrain a value to be less than or equal to a certain value."""
262
+ return self.constrain(annotated_types.Le(le))
263
+
264
+ def len(self: _Pipeline[_InT, _NewOutLen], min_len: int, max_len: int | None = None) -> _Pipeline[_InT, _NewOutLen]:
265
+ """Constrain a value to have a certain length."""
266
+ return self.constrain(annotated_types.Len(min_len, max_len))
267
+
268
+ @overload
269
+ def multiple_of(self: _Pipeline[_InT, _NewOutDiv], multiple_of: _NewOutDiv) -> _Pipeline[_InT, _NewOutDiv]: ...
270
+
271
+ @overload
272
+ def multiple_of(self: _Pipeline[_InT, _NewOutMod], multiple_of: _NewOutMod) -> _Pipeline[_InT, _NewOutMod]: ...
273
+
274
+ def multiple_of(self: _Pipeline[_InT, Any], multiple_of: Any) -> _Pipeline[_InT, Any]:
275
+ """Constrain a value to be a multiple of a certain number."""
276
+ return self.constrain(annotated_types.MultipleOf(multiple_of))
277
+
278
+ def eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
279
+ """Constrain a value to be equal to a certain value."""
280
+ return self.constrain(_Eq(value))
281
+
282
+ def not_eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]:
283
+ """Constrain a value to not be equal to a certain value."""
284
+ return self.constrain(_NotEq(value))
285
+
286
+ def in_(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
287
+ """Constrain a value to be in a certain set."""
288
+ return self.constrain(_In(values))
289
+
290
+ def not_in(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]:
291
+ """Constrain a value to not be in a certain set."""
292
+ return self.constrain(_NotIn(values))
293
+
294
+ # timezone methods
295
+ def datetime_tz_naive(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
296
+ return self.constrain(annotated_types.Timezone(None))
297
+
298
+ def datetime_tz_aware(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]:
299
+ return self.constrain(annotated_types.Timezone(...))
300
+
301
+ def datetime_tz(
302
+ self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo
303
+ ) -> _Pipeline[_InT, datetime.datetime]:
304
+ return self.constrain(annotated_types.Timezone(tz)) # type: ignore
305
+
306
+ def datetime_with_tz(
307
+ self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo | None
308
+ ) -> _Pipeline[_InT, datetime.datetime]:
309
+ return self.transform(partial(datetime.datetime.replace, tzinfo=tz))
310
+
311
+ # string methods
312
+ def str_lower(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
313
+ return self.transform(str.lower)
314
+
315
+ def str_upper(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
316
+ return self.transform(str.upper)
317
+
318
+ def str_title(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
319
+ return self.transform(str.title)
320
+
321
+ def str_strip(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]:
322
+ return self.transform(str.strip)
323
+
324
+ def str_pattern(self: _Pipeline[_InT, str], pattern: str) -> _Pipeline[_InT, str]:
325
+ return self.constrain(re.compile(pattern))
326
+
327
+ def str_contains(self: _Pipeline[_InT, str], substring: str) -> _Pipeline[_InT, str]:
328
+ return self.predicate(lambda v: substring in v)
329
+
330
+ def str_starts_with(self: _Pipeline[_InT, str], prefix: str) -> _Pipeline[_InT, str]:
331
+ return self.predicate(lambda v: v.startswith(prefix))
332
+
333
+ def str_ends_with(self: _Pipeline[_InT, str], suffix: str) -> _Pipeline[_InT, str]:
334
+ return self.predicate(lambda v: v.endswith(suffix))
335
+
336
+ # operators
337
+ def otherwise(self, other: _Pipeline[_OtherIn, _OtherOut]) -> _Pipeline[_InT | _OtherIn, _OutT | _OtherOut]:
338
+ """Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails."""
339
+ return _Pipeline((_PipelineOr(self, other),))
340
+
341
+ __or__ = otherwise
342
+
343
+ def then(self, other: _Pipeline[_OutT, _OtherOut]) -> _Pipeline[_InT, _OtherOut]:
344
+ """Pipe the result of one validation chain into another."""
345
+ return _Pipeline((_PipelineAnd(self, other),))
346
+
347
+ __and__ = then
348
+
349
+ def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> cs.CoreSchema:
350
+ queue = deque(self._steps)
351
+
352
+ s = None
353
+
354
+ while queue:
355
+ step = queue.popleft()
356
+ s = _apply_step(step, s, handler, source_type)
357
+
358
+ s = s or cs.any_schema()
359
+ return s
360
+
361
+ def __supports_type__(self, _: _OutT) -> bool:
362
+ raise NotImplementedError
363
+
364
+
365
+ validate_as = _Pipeline[Any, Any](()).validate_as
366
+ validate_as_deferred = _Pipeline[Any, Any](()).validate_as_deferred
367
+ transform = _Pipeline[Any, Any]((_ValidateAs(_FieldTypeMarker),)).transform
368
+
369
+
370
+ def _check_func(
371
+ func: Callable[[Any], bool], predicate_err: str | Callable[[], str], s: cs.CoreSchema | None
372
+ ) -> cs.CoreSchema:
373
+ def handler(v: Any) -> Any:
374
+ if func(v):
375
+ return v
376
+ raise ValueError(f'Expected {predicate_err if isinstance(predicate_err, str) else predicate_err()}')
377
+
378
+ if s is None:
379
+ return cs.no_info_plain_validator_function(handler)
380
+ else:
381
+ return cs.no_info_after_validator_function(handler, s)
382
+
383
+
384
+ def _apply_step(step: _Step, s: cs.CoreSchema | None, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema:
385
+ if isinstance(step, _ValidateAs):
386
+ s = _apply_parse(s, step.tp, step.strict, handler, source_type)
387
+ elif isinstance(step, _ValidateAsDefer):
388
+ s = _apply_parse(s, step.tp, False, handler, source_type)
389
+ elif isinstance(step, _Transform):
390
+ s = _apply_transform(s, step.func, handler)
391
+ elif isinstance(step, _Constraint):
392
+ s = _apply_constraint(s, step.constraint)
393
+ elif isinstance(step, _PipelineOr):
394
+ s = cs.union_schema([handler(step.left), handler(step.right)])
395
+ else:
396
+ assert isinstance(step, _PipelineAnd)
397
+ s = cs.chain_schema([handler(step.left), handler(step.right)])
398
+ return s
399
+
400
+
401
+ def _apply_parse(
402
+ s: cs.CoreSchema | None,
403
+ tp: type[Any],
404
+ strict: bool,
405
+ handler: GetCoreSchemaHandler,
406
+ source_type: Any,
407
+ ) -> cs.CoreSchema:
408
+ if tp is _FieldTypeMarker:
409
+ return cs.chain_schema([s, handler(source_type)]) if s else handler(source_type)
410
+
411
+ if strict:
412
+ tp = Annotated[tp, Strict()] # type: ignore
413
+
414
+ if s and s['type'] == 'any':
415
+ return handler(tp)
416
+ else:
417
+ return cs.chain_schema([s, handler(tp)]) if s else handler(tp)
418
+
419
+
420
+ def _apply_transform(
421
+ s: cs.CoreSchema | None, func: Callable[[Any], Any], handler: GetCoreSchemaHandler
422
+ ) -> cs.CoreSchema:
423
+ if s is None:
424
+ return cs.no_info_plain_validator_function(func)
425
+
426
+ if s['type'] == 'str':
427
+ if func is str.strip:
428
+ s = s.copy()
429
+ s['strip_whitespace'] = True
430
+ return s
431
+ elif func is str.lower:
432
+ s = s.copy()
433
+ s['to_lower'] = True
434
+ return s
435
+ elif func is str.upper:
436
+ s = s.copy()
437
+ s['to_upper'] = True
438
+ return s
439
+
440
+ return cs.no_info_after_validator_function(func, s)
441
+
442
+
443
+ def _apply_constraint( # noqa: C901
444
+ s: cs.CoreSchema | None, constraint: _ConstraintAnnotation
445
+ ) -> cs.CoreSchema:
446
+ """Apply a single constraint to a schema."""
447
+ if isinstance(constraint, annotated_types.Gt):
448
+ gt = constraint.gt
449
+ if s and s['type'] in {'int', 'float', 'decimal'}:
450
+ s = s.copy()
451
+ if s['type'] == 'int' and isinstance(gt, int):
452
+ s['gt'] = gt
453
+ elif s['type'] == 'float' and isinstance(gt, float):
454
+ s['gt'] = gt
455
+ elif s['type'] == 'decimal' and isinstance(gt, Decimal):
456
+ s['gt'] = gt
457
+ else:
458
+
459
+ def check_gt(v: Any) -> bool:
460
+ return v > gt
461
+
462
+ s = _check_func(check_gt, f'> {gt}', s)
463
+ elif isinstance(constraint, annotated_types.Ge):
464
+ ge = constraint.ge
465
+ if s and s['type'] in {'int', 'float', 'decimal'}:
466
+ s = s.copy()
467
+ if s['type'] == 'int' and isinstance(ge, int):
468
+ s['ge'] = ge
469
+ elif s['type'] == 'float' and isinstance(ge, float):
470
+ s['ge'] = ge
471
+ elif s['type'] == 'decimal' and isinstance(ge, Decimal):
472
+ s['ge'] = ge
473
+
474
+ def check_ge(v: Any) -> bool:
475
+ return v >= ge
476
+
477
+ s = _check_func(check_ge, f'>= {ge}', s)
478
+ elif isinstance(constraint, annotated_types.Lt):
479
+ lt = constraint.lt
480
+ if s and s['type'] in {'int', 'float', 'decimal'}:
481
+ s = s.copy()
482
+ if s['type'] == 'int' and isinstance(lt, int):
483
+ s['lt'] = lt
484
+ elif s['type'] == 'float' and isinstance(lt, float):
485
+ s['lt'] = lt
486
+ elif s['type'] == 'decimal' and isinstance(lt, Decimal):
487
+ s['lt'] = lt
488
+
489
+ def check_lt(v: Any) -> bool:
490
+ return v < lt
491
+
492
+ s = _check_func(check_lt, f'< {lt}', s)
493
+ elif isinstance(constraint, annotated_types.Le):
494
+ le = constraint.le
495
+ if s and s['type'] in {'int', 'float', 'decimal'}:
496
+ s = s.copy()
497
+ if s['type'] == 'int' and isinstance(le, int):
498
+ s['le'] = le
499
+ elif s['type'] == 'float' and isinstance(le, float):
500
+ s['le'] = le
501
+ elif s['type'] == 'decimal' and isinstance(le, Decimal):
502
+ s['le'] = le
503
+
504
+ def check_le(v: Any) -> bool:
505
+ return v <= le
506
+
507
+ s = _check_func(check_le, f'<= {le}', s)
508
+ elif isinstance(constraint, annotated_types.Len):
509
+ min_len = constraint.min_length
510
+ max_len = constraint.max_length
511
+
512
+ if s and s['type'] in {'str', 'list', 'tuple', 'set', 'frozenset', 'dict'}:
513
+ assert (
514
+ s['type'] == 'str'
515
+ or s['type'] == 'list'
516
+ or s['type'] == 'tuple'
517
+ or s['type'] == 'set'
518
+ or s['type'] == 'dict'
519
+ or s['type'] == 'frozenset'
520
+ )
521
+ s = s.copy()
522
+ if min_len != 0:
523
+ s['min_length'] = min_len
524
+ if max_len is not None:
525
+ s['max_length'] = max_len
526
+
527
+ def check_len(v: Any) -> bool:
528
+ if max_len is not None:
529
+ return (min_len <= len(v)) and (len(v) <= max_len)
530
+ return min_len <= len(v)
531
+
532
+ s = _check_func(check_len, f'length >= {min_len} and length <= {max_len}', s)
533
+ elif isinstance(constraint, annotated_types.MultipleOf):
534
+ multiple_of = constraint.multiple_of
535
+ if s and s['type'] in {'int', 'float', 'decimal'}:
536
+ s = s.copy()
537
+ if s['type'] == 'int' and isinstance(multiple_of, int):
538
+ s['multiple_of'] = multiple_of
539
+ elif s['type'] == 'float' and isinstance(multiple_of, float):
540
+ s['multiple_of'] = multiple_of
541
+ elif s['type'] == 'decimal' and isinstance(multiple_of, Decimal):
542
+ s['multiple_of'] = multiple_of
543
+
544
+ def check_multiple_of(v: Any) -> bool:
545
+ return v % multiple_of == 0
546
+
547
+ s = _check_func(check_multiple_of, f'% {multiple_of} == 0', s)
548
+ elif isinstance(constraint, annotated_types.Timezone):
549
+ tz = constraint.tz
550
+
551
+ if tz is ...:
552
+ if s and s['type'] == 'datetime':
553
+ s = s.copy()
554
+ s['tz_constraint'] = 'aware'
555
+ else:
556
+
557
+ def check_tz_aware(v: object) -> bool:
558
+ assert isinstance(v, datetime.datetime)
559
+ return v.tzinfo is not None
560
+
561
+ s = _check_func(check_tz_aware, 'timezone aware', s)
562
+ elif tz is None:
563
+ if s and s['type'] == 'datetime':
564
+ s = s.copy()
565
+ s['tz_constraint'] = 'naive'
566
+ else:
567
+
568
+ def check_tz_naive(v: object) -> bool:
569
+ assert isinstance(v, datetime.datetime)
570
+ return v.tzinfo is None
571
+
572
+ s = _check_func(check_tz_naive, 'timezone naive', s)
573
+ else:
574
+ raise NotImplementedError('Constraining to a specific timezone is not yet supported')
575
+ elif isinstance(constraint, annotated_types.Interval):
576
+ if constraint.ge:
577
+ s = _apply_constraint(s, annotated_types.Ge(constraint.ge))
578
+ if constraint.gt:
579
+ s = _apply_constraint(s, annotated_types.Gt(constraint.gt))
580
+ if constraint.le:
581
+ s = _apply_constraint(s, annotated_types.Le(constraint.le))
582
+ if constraint.lt:
583
+ s = _apply_constraint(s, annotated_types.Lt(constraint.lt))
584
+ assert s is not None
585
+ elif isinstance(constraint, annotated_types.Predicate):
586
+ func = constraint.func
587
+ # Same logic as in `_known_annotated_metadata.apply_known_metadata()`:
588
+ predicate_name = f'{func.__qualname__!r} ' if hasattr(func, '__qualname__') else ''
589
+
590
+ def predicate_func(v: Any) -> Any:
591
+ if not func(v):
592
+ raise PydanticCustomError(
593
+ 'predicate_failed',
594
+ f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType]
595
+ )
596
+ return v
597
+
598
+ if s is None:
599
+ s = cs.no_info_plain_validator_function(predicate_func)
600
+ else:
601
+ s = cs.no_info_after_validator_function(predicate_func, s)
602
+ elif isinstance(constraint, _NotEq):
603
+ value = constraint.value
604
+
605
+ def check_not_eq(v: Any) -> bool:
606
+ return operator.__ne__(v, value)
607
+
608
+ s = _check_func(check_not_eq, f'!= {value}', s)
609
+ elif isinstance(constraint, _Eq):
610
+ value = constraint.value
611
+
612
+ def check_eq(v: Any) -> bool:
613
+ return operator.__eq__(v, value)
614
+
615
+ s = _check_func(check_eq, f'== {value}', s)
616
+ elif isinstance(constraint, _In):
617
+ values = constraint.values
618
+
619
+ def check_in(v: Any) -> bool:
620
+ return operator.__contains__(values, v)
621
+
622
+ s = _check_func(check_in, f'in {values}', s)
623
+ elif isinstance(constraint, _NotIn):
624
+ values = constraint.values
625
+
626
+ def check_not_in(v: Any) -> bool:
627
+ return operator.__not__(operator.__contains__(values, v))
628
+
629
+ s = _check_func(check_not_in, f'not in {values}', s)
630
+ else:
631
+ assert isinstance(constraint, Pattern)
632
+ if s and s['type'] == 'str':
633
+ s = s.copy()
634
+ s['pattern'] = constraint.pattern
635
+ else:
636
+
637
+ def check_pattern(v: object) -> bool:
638
+ assert isinstance(v, str)
639
+ return constraint.match(v) is not None
640
+
641
+ s = _check_func(check_pattern, f'~ {constraint.pattern}', s)
642
+ return s
643
+
644
+
645
+ class _SupportsRange(annotated_types.SupportsLe, annotated_types.SupportsGe, Protocol):
646
+ pass
647
+
648
+
649
+ class _SupportsLen(Protocol):
650
+ def __len__(self) -> int: ...
651
+
652
+
653
+ _NewOutGt = TypeVar('_NewOutGt', bound=annotated_types.SupportsGt)
654
+ _NewOutGe = TypeVar('_NewOutGe', bound=annotated_types.SupportsGe)
655
+ _NewOutLt = TypeVar('_NewOutLt', bound=annotated_types.SupportsLt)
656
+ _NewOutLe = TypeVar('_NewOutLe', bound=annotated_types.SupportsLe)
657
+ _NewOutLen = TypeVar('_NewOutLen', bound=_SupportsLen)
658
+ _NewOutDiv = TypeVar('_NewOutDiv', bound=annotated_types.SupportsDiv)
659
+ _NewOutMod = TypeVar('_NewOutMod', bound=annotated_types.SupportsMod)
660
+ _NewOutDatetime = TypeVar('_NewOutDatetime', bound=datetime.datetime)
661
+ _NewOutInterval = TypeVar('_NewOutInterval', bound=_SupportsRange)
662
+ _OtherIn = TypeVar('_OtherIn')
663
+ _OtherOut = TypeVar('_OtherOut')
micromamba_root/envs/pytorch_env/Lib/site-packages/pydantic/plugin/__init__.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """!!! abstract "Usage Documentation"
2
+ [Build a Plugin](../concepts/plugins.md#build-a-plugin)
3
+
4
+ Plugin interface for Pydantic plugins, and related types.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Callable, Literal, NamedTuple
10
+
11
+ from pydantic_core import CoreConfig, CoreSchema, ValidationError
12
+ from typing_extensions import Protocol, TypeAlias
13
+
14
+ from pydantic.config import ExtraValues
15
+
16
+ __all__ = (
17
+ 'PydanticPluginProtocol',
18
+ 'BaseValidateHandlerProtocol',
19
+ 'ValidatePythonHandlerProtocol',
20
+ 'ValidateJsonHandlerProtocol',
21
+ 'ValidateStringsHandlerProtocol',
22
+ 'NewSchemaReturns',
23
+ 'SchemaTypePath',
24
+ 'SchemaKind',
25
+ )
26
+
27
+ NewSchemaReturns: TypeAlias = 'tuple[ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None]'
28
+
29
+
30
+ class SchemaTypePath(NamedTuple):
31
+ """Path defining where `schema_type` was defined, or where `TypeAdapter` was called."""
32
+
33
+ module: str
34
+ name: str
35
+
36
+
37
+ SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call']
38
+
39
+
40
+ class PydanticPluginProtocol(Protocol):
41
+ """Protocol defining the interface for Pydantic plugins."""
42
+
43
+ def new_schema_validator(
44
+ self,
45
+ schema: CoreSchema,
46
+ schema_type: Any,
47
+ schema_type_path: SchemaTypePath,
48
+ schema_kind: SchemaKind,
49
+ config: CoreConfig | None,
50
+ plugin_settings: dict[str, object],
51
+ ) -> tuple[
52
+ ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None
53
+ ]:
54
+ """This method is called for each plugin every time a new [`SchemaValidator`][pydantic_core.SchemaValidator]
55
+ is created.
56
+
57
+ It should return an event handler for each of the three validation methods, or `None` if the plugin does not
58
+ implement that method.
59
+
60
+ Args:
61
+ schema: The schema to validate against.
62
+ schema_type: The original type which the schema was created from, e.g. the model class.
63
+ schema_type_path: Path defining where `schema_type` was defined, or where `TypeAdapter` was called.
64
+ schema_kind: The kind of schema to validate against.
65
+ config: The config to use for validation.
66
+ plugin_settings: Any plugin settings.
67
+
68
+ Returns:
69
+ A tuple of optional event handlers for each of the three validation methods -
70
+ `validate_python`, `validate_json`, `validate_strings`.
71
+ """
72
+ raise NotImplementedError('Pydantic plugins should implement `new_schema_validator`.')
73
+
74
+
75
+ class BaseValidateHandlerProtocol(Protocol):
76
+ """Base class for plugin callbacks protocols.
77
+
78
+ You shouldn't implement this protocol directly, instead use one of the subclasses with adds the correctly
79
+ typed `on_error` method.
80
+ """
81
+
82
+ on_enter: Callable[..., None]
83
+ """`on_enter` is changed to be more specific on all subclasses"""
84
+
85
+ def on_success(self, result: Any) -> None:
86
+ """Callback to be notified of successful validation.
87
+
88
+ Args:
89
+ result: The result of the validation.
90
+ """
91
+ return
92
+
93
+ def on_error(self, error: ValidationError) -> None:
94
+ """Callback to be notified of validation errors.
95
+
96
+ Args:
97
+ error: The validation error.
98
+ """
99
+ return
100
+
101
+ def on_exception(self, exception: Exception) -> None:
102
+ """Callback to be notified of validation exceptions.
103
+
104
+ Args:
105
+ exception: The exception raised during validation.
106
+ """
107
+ return
108
+
109
+
110
+ class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
111
+ """Event handler for `SchemaValidator.validate_python`."""
112
+
113
+ def on_enter(
114
+ self,
115
+ input: Any,
116
+ *,
117
+ strict: bool | None = None,
118
+ extra: ExtraValues | None = None,
119
+ from_attributes: bool | None = None,
120
+ context: Any | None = None,
121
+ self_instance: Any | None = None,
122
+ by_alias: bool | None = None,
123
+ by_name: bool | None = None,
124
+ ) -> None:
125
+ """Callback to be notified of validation start, and create an instance of the event handler.
126
+
127
+ Args:
128
+ input: The input to be validated.
129
+ strict: Whether to validate the object in strict mode.
130
+ extra: Whether to ignore, allow, or forbid extra data during model validation.
131
+ from_attributes: Whether to validate objects as inputs by extracting attributes.
132
+ context: The context to use for validation, this is passed to functional validators.
133
+ self_instance: An instance of a model to set attributes on from validation, this is used when running
134
+ validation from the `__init__` method of a model.
135
+ by_alias: Whether to use the field's alias to match the input data to an attribute.
136
+ by_name: Whether to use the field's name to match the input data to an attribute.
137
+ """
138
+
139
+
140
+ class ValidateJsonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
141
+ """Event handler for `SchemaValidator.validate_json`."""
142
+
143
+ def on_enter(
144
+ self,
145
+ input: str | bytes | bytearray,
146
+ *,
147
+ strict: bool | None = None,
148
+ extra: ExtraValues | None = None,
149
+ context: Any | None = None,
150
+ self_instance: Any | None = None,
151
+ by_alias: bool | None = None,
152
+ by_name: bool | None = None,
153
+ ) -> None:
154
+ """Callback to be notified of validation start, and create an instance of the event handler.
155
+
156
+ Args:
157
+ input: The JSON data to be validated.
158
+ strict: Whether to validate the object in strict mode.
159
+ extra: Whether to ignore, allow, or forbid extra data during model validation.
160
+ context: The context to use for validation, this is passed to functional validators.
161
+ self_instance: An instance of a model to set attributes on from validation, this is used when running
162
+ validation from the `__init__` method of a model.
163
+ by_alias: Whether to use the field's alias to match the input data to an attribute.
164
+ by_name: Whether to use the field's name to match the input data to an attribute.
165
+ """
166
+
167
+
168
+ StringInput: TypeAlias = 'dict[str, StringInput]'
169
+
170
+
171
+ class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
172
+ """Event handler for `SchemaValidator.validate_strings`."""
173
+
174
+ def on_enter(
175
+ self,
176
+ input: StringInput,
177
+ *,
178
+ strict: bool | None = None,
179
+ extra: ExtraValues | None = None,
180
+ context: Any | None = None,
181
+ by_alias: bool | None = None,
182
+ by_name: bool | None = None,
183
+ ) -> None:
184
+ """Callback to be notified of validation start, and create an instance of the event handler.
185
+
186
+ Args:
187
+ input: The string data to be validated.
188
+ strict: Whether to validate the object in strict mode.
189
+ extra: Whether to ignore, allow, or forbid extra data during model validation.
190
+ context: The context to use for validation, this is passed to functional validators.
191
+ by_alias: Whether to use the field's alias to match the input data to an attribute.
192
+ by_name: Whether to use the field's name to match the input data to an attribute.
193
+ """