assassinlike commited on
Commit
09152ac
·
verified ·
1 Parent(s): cc3d24b

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. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/__init__.cpython-311.pyc +0 -0
  2. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/_migration.cpython-311.pyc +0 -0
  3. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/alias_generators.cpython-311.pyc +0 -0
  4. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/annotated_handlers.cpython-311.pyc +0 -0
  5. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/class_validators.cpython-311.pyc +0 -0
  6. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/config.cpython-311.pyc +0 -0
  7. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/dataclasses.cpython-311.pyc +0 -0
  8. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/datetime_parse.cpython-311.pyc +0 -0
  9. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/decorator.cpython-311.pyc +0 -0
  10. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/env_settings.cpython-311.pyc +0 -0
  11. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/errors.cpython-311.pyc +0 -0
  12. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/fields.cpython-311.pyc +0 -0
  13. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/main.cpython-311.pyc +0 -0
  14. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/mypy.cpython-311.pyc +0 -0
  15. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/networks.cpython-311.pyc +0 -0
  16. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/parse.cpython-311.pyc +0 -0
  17. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/root_model.cpython-311.pyc +0 -0
  18. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/schema.cpython-311.pyc +0 -0
  19. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/type_adapter.cpython-311.pyc +0 -0
  20. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/typing.cpython-311.pyc +0 -0
  21. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/validate_call_decorator.cpython-311.pyc +0 -0
  22. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/validators.cpython-311.pyc +0 -0
  23. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__init__.py +0 -0
  24. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_config.cpython-311.pyc +0 -0
  25. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_dataclasses.cpython-311.pyc +0 -0
  26. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_fields.cpython-311.pyc +0 -0
  27. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-311.pyc +0 -0
  28. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-311.pyc +0 -0
  29. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-311.pyc +0 -0
  30. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_utils.cpython-311.pyc +0 -0
  31. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_validate_call.cpython-311.pyc +0 -0
  32. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_config.py +383 -0
  33. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_core_metadata.py +97 -0
  34. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_core_utils.py +174 -0
  35. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_dataclasses.py +315 -0
  36. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_decorators.py +858 -0
  37. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_decorators_v1.py +174 -0
  38. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_discriminated_union.py +479 -0
  39. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_docs_extraction.py +113 -0
  40. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_fields.py +635 -0
  41. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_forward_ref.py +23 -0
  42. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py +0 -0
  43. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_generics.py +543 -0
  44. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_git.py +27 -0
  45. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_import_utils.py +20 -0
  46. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_internal_dataclass.py +7 -0
  47. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_known_annotated_metadata.py +401 -0
  48. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_mock_val_ser.py +228 -0
  49. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_model_construction.py +848 -0
  50. data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_namespace_utils.py +293 -0
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (13.7 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/_migration.cpython-311.pyc ADDED
Binary file (11.6 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/alias_generators.cpython-311.pyc ADDED
Binary file (3.54 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/annotated_handlers.cpython-311.pyc ADDED
Binary file (5.86 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/class_validators.cpython-311.pyc ADDED
Binary file (408 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/config.cpython-311.pyc ADDED
Binary file (8.48 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/dataclasses.cpython-311.pyc ADDED
Binary file (18.1 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/datetime_parse.cpython-311.pyc ADDED
Binary file (408 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/decorator.cpython-311.pyc ADDED
Binary file (398 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/env_settings.cpython-311.pyc ADDED
Binary file (404 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/errors.cpython-311.pyc ADDED
Binary file (8.85 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/fields.cpython-311.pyc ADDED
Binary file (73.4 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/main.cpython-311.pyc ADDED
Binary file (81.8 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/mypy.cpython-311.pyc ADDED
Binary file (65.6 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/networks.cpython-311.pyc ADDED
Binary file (54.3 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/parse.cpython-311.pyc ADDED
Binary file (390 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/root_model.cpython-311.pyc ADDED
Binary file (8.63 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/schema.cpython-311.pyc ADDED
Binary file (392 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/type_adapter.cpython-311.pyc ADDED
Binary file (35.9 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/typing.cpython-311.pyc ADDED
Binary file (388 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/validate_call_decorator.cpython-311.pyc ADDED
Binary file (6.05 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/__pycache__/validators.cpython-311.pyc ADDED
Binary file (400 Bytes). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__init__.py ADDED
File without changes
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_config.cpython-311.pyc ADDED
Binary file (18.4 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_dataclasses.cpython-311.pyc ADDED
Binary file (14.3 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_fields.cpython-311.pyc ADDED
Binary file (26.2 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-311.pyc ADDED
Binary file (12.4 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-311.pyc ADDED
Binary file (39.5 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-311.pyc ADDED
Binary file (29.7 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_utils.cpython-311.pyc ADDED
Binary file (22.7 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/__pycache__/_validate_call.cpython-311.pyc ADDED
Binary file (7.22 kB). View file
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_config.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
92
+ def __init__(self, config: ConfigDict | dict[str, Any] | type[Any] | None, *, check: bool = True):
93
+ if check:
94
+ self.config_dict = prepare_config(config)
95
+ else:
96
+ self.config_dict = cast(ConfigDict, config)
97
+
98
+ @classmethod
99
+ def for_model(
100
+ cls,
101
+ bases: tuple[type[Any], ...],
102
+ namespace: dict[str, Any],
103
+ raw_annotations: dict[str, Any],
104
+ kwargs: dict[str, Any],
105
+ ) -> Self:
106
+ """Build a new `ConfigWrapper` instance for a `BaseModel`.
107
+
108
+ The config wrapper built based on (in descending order of priority):
109
+ - options from `kwargs`
110
+ - options from the `namespace`
111
+ - options from the base classes (`bases`)
112
+
113
+ Args:
114
+ bases: A tuple of base classes.
115
+ namespace: The namespace of the class being created.
116
+ raw_annotations: The (non-evaluated) annotations of the model.
117
+ kwargs: The kwargs passed to the class being created.
118
+
119
+ Returns:
120
+ A `ConfigWrapper` instance for `BaseModel`.
121
+ """
122
+ config_new = ConfigDict()
123
+ for base in bases:
124
+ config = getattr(base, 'model_config', None)
125
+ if config:
126
+ config_new.update(config.copy())
127
+
128
+ config_class_from_namespace = namespace.get('Config')
129
+ config_dict_from_namespace = namespace.get('model_config')
130
+
131
+ if raw_annotations.get('model_config') and config_dict_from_namespace is None:
132
+ raise PydanticUserError(
133
+ '`model_config` cannot be used as a model field name. Use `model_config` for model configuration.',
134
+ code='model-config-invalid-field-name',
135
+ )
136
+
137
+ if config_class_from_namespace and config_dict_from_namespace:
138
+ raise PydanticUserError('"Config" and "model_config" cannot be used together', code='config-both')
139
+
140
+ config_from_namespace = config_dict_from_namespace or prepare_config(config_class_from_namespace)
141
+
142
+ config_new.update(config_from_namespace)
143
+
144
+ for k in list(kwargs.keys()):
145
+ if k in config_keys:
146
+ config_new[k] = kwargs.pop(k)
147
+
148
+ return cls(config_new)
149
+
150
+ # we don't show `__getattr__` to type checkers so missing attributes cause errors
151
+ if not TYPE_CHECKING: # pragma: no branch
152
+
153
+ def __getattr__(self, name: str) -> Any:
154
+ try:
155
+ return self.config_dict[name]
156
+ except KeyError:
157
+ try:
158
+ return config_defaults[name]
159
+ except KeyError:
160
+ raise AttributeError(f'Config has no attribute {name!r}') from None
161
+
162
+ def core_config(self, title: str | None) -> core_schema.CoreConfig:
163
+ """Create a pydantic-core config.
164
+
165
+ We don't use getattr here since we don't want to populate with defaults.
166
+
167
+ Args:
168
+ title: The title to use if not set in config.
169
+
170
+ Returns:
171
+ A `CoreConfig` object created from config.
172
+ """
173
+ config = self.config_dict
174
+
175
+ if config.get('schema_generator') is not None:
176
+ warnings.warn(
177
+ 'The `schema_generator` setting has been deprecated since v2.10. This setting no longer has any effect.',
178
+ PydanticDeprecatedSince210,
179
+ stacklevel=2,
180
+ )
181
+
182
+ if (populate_by_name := config.get('populate_by_name')) is not None:
183
+ # We include this patch for backwards compatibility purposes, but this config setting will be deprecated in v3.0, and likely removed in v4.0.
184
+ # Thus, the above warning and this patch can be removed then as well.
185
+ if config.get('validate_by_name') is None:
186
+ config['validate_by_alias'] = True
187
+ config['validate_by_name'] = populate_by_name
188
+
189
+ # We dynamically patch validate_by_name to be True if validate_by_alias is set to False
190
+ # and validate_by_name is not explicitly set.
191
+ if config.get('validate_by_alias') is False and config.get('validate_by_name') is None:
192
+ config['validate_by_name'] = True
193
+
194
+ if (not config.get('validate_by_alias', True)) and (not config.get('validate_by_name', False)):
195
+ raise PydanticUserError(
196
+ 'At least one of `validate_by_alias` or `validate_by_name` must be set to True.',
197
+ code='validate-by-alias-and-name-false',
198
+ )
199
+
200
+ return core_schema.CoreConfig(
201
+ **{ # pyright: ignore[reportArgumentType]
202
+ k: v
203
+ for k, v in (
204
+ ('title', config.get('title') or title or None),
205
+ ('extra_fields_behavior', config.get('extra')),
206
+ ('allow_inf_nan', config.get('allow_inf_nan')),
207
+ ('str_strip_whitespace', config.get('str_strip_whitespace')),
208
+ ('str_to_lower', config.get('str_to_lower')),
209
+ ('str_to_upper', config.get('str_to_upper')),
210
+ ('strict', config.get('strict')),
211
+ ('ser_json_timedelta', config.get('ser_json_timedelta')),
212
+ ('ser_json_temporal', config.get('ser_json_temporal')),
213
+ ('val_temporal_unit', config.get('val_temporal_unit')),
214
+ ('ser_json_bytes', config.get('ser_json_bytes')),
215
+ ('val_json_bytes', config.get('val_json_bytes')),
216
+ ('ser_json_inf_nan', config.get('ser_json_inf_nan')),
217
+ ('from_attributes', config.get('from_attributes')),
218
+ ('loc_by_alias', config.get('loc_by_alias')),
219
+ ('revalidate_instances', config.get('revalidate_instances')),
220
+ ('validate_default', config.get('validate_default')),
221
+ ('str_max_length', config.get('str_max_length')),
222
+ ('str_min_length', config.get('str_min_length')),
223
+ ('hide_input_in_errors', config.get('hide_input_in_errors')),
224
+ ('coerce_numbers_to_str', config.get('coerce_numbers_to_str')),
225
+ ('regex_engine', config.get('regex_engine')),
226
+ ('validation_error_cause', config.get('validation_error_cause')),
227
+ ('cache_strings', config.get('cache_strings')),
228
+ ('validate_by_alias', config.get('validate_by_alias')),
229
+ ('validate_by_name', config.get('validate_by_name')),
230
+ ('serialize_by_alias', config.get('serialize_by_alias')),
231
+ ('url_preserve_empty_path', config.get('url_preserve_empty_path')),
232
+ )
233
+ if v is not None
234
+ }
235
+ )
236
+
237
+ def __repr__(self):
238
+ c = ', '.join(f'{k}={v!r}' for k, v in self.config_dict.items())
239
+ return f'ConfigWrapper({c})'
240
+
241
+
242
+ class ConfigWrapperStack:
243
+ """A stack of `ConfigWrapper` instances."""
244
+
245
+ def __init__(self, config_wrapper: ConfigWrapper):
246
+ self._config_wrapper_stack: list[ConfigWrapper] = [config_wrapper]
247
+
248
+ @property
249
+ def tail(self) -> ConfigWrapper:
250
+ return self._config_wrapper_stack[-1]
251
+
252
+ @contextmanager
253
+ def push(self, config_wrapper: ConfigWrapper | ConfigDict | None):
254
+ if config_wrapper is None:
255
+ yield
256
+ return
257
+
258
+ if not isinstance(config_wrapper, ConfigWrapper):
259
+ config_wrapper = ConfigWrapper(config_wrapper, check=False)
260
+
261
+ self._config_wrapper_stack.append(config_wrapper)
262
+ try:
263
+ yield
264
+ finally:
265
+ self._config_wrapper_stack.pop()
266
+
267
+
268
+ config_defaults = ConfigDict(
269
+ title=None,
270
+ str_to_lower=False,
271
+ str_to_upper=False,
272
+ str_strip_whitespace=False,
273
+ str_min_length=0,
274
+ str_max_length=None,
275
+ # let the model / dataclass decide how to handle it
276
+ extra=None,
277
+ frozen=False,
278
+ populate_by_name=False,
279
+ use_enum_values=False,
280
+ validate_assignment=False,
281
+ arbitrary_types_allowed=False,
282
+ from_attributes=False,
283
+ loc_by_alias=True,
284
+ alias_generator=None,
285
+ model_title_generator=None,
286
+ field_title_generator=None,
287
+ ignored_types=(),
288
+ allow_inf_nan=True,
289
+ json_schema_extra=None,
290
+ strict=False,
291
+ revalidate_instances='never',
292
+ ser_json_timedelta='iso8601',
293
+ ser_json_temporal='iso8601',
294
+ val_temporal_unit='infer',
295
+ ser_json_bytes='utf8',
296
+ val_json_bytes='utf8',
297
+ ser_json_inf_nan='null',
298
+ validate_default=False,
299
+ validate_return=False,
300
+ protected_namespaces=('model_validate', 'model_dump'),
301
+ hide_input_in_errors=False,
302
+ json_encoders=None,
303
+ defer_build=False,
304
+ schema_generator=None,
305
+ plugin_settings=None,
306
+ json_schema_serialization_defaults_required=False,
307
+ json_schema_mode_override=None,
308
+ coerce_numbers_to_str=False,
309
+ regex_engine='rust-regex',
310
+ validation_error_cause=False,
311
+ use_attribute_docstrings=False,
312
+ cache_strings=True,
313
+ validate_by_alias=True,
314
+ validate_by_name=False,
315
+ serialize_by_alias=False,
316
+ url_preserve_empty_path=False,
317
+ )
318
+
319
+
320
+ def prepare_config(config: ConfigDict | dict[str, Any] | type[Any] | None) -> ConfigDict:
321
+ """Create a `ConfigDict` instance from an existing dict, a class (e.g. old class-based config) or None.
322
+
323
+ Args:
324
+ config: The input config.
325
+
326
+ Returns:
327
+ A ConfigDict object created from config.
328
+ """
329
+ if config is None:
330
+ return ConfigDict()
331
+
332
+ if not isinstance(config, dict):
333
+ warnings.warn(DEPRECATION_MESSAGE, PydanticDeprecatedSince20, stacklevel=4)
334
+ config = {k: getattr(config, k) for k in dir(config) if not k.startswith('__')}
335
+
336
+ config_dict = cast(ConfigDict, config)
337
+ check_deprecated(config_dict)
338
+ return config_dict
339
+
340
+
341
+ config_keys = set(ConfigDict.__annotations__.keys())
342
+
343
+
344
+ V2_REMOVED_KEYS = {
345
+ 'allow_mutation',
346
+ 'error_msg_templates',
347
+ 'fields',
348
+ 'getter_dict',
349
+ 'smart_union',
350
+ 'underscore_attrs_are_private',
351
+ 'json_loads',
352
+ 'json_dumps',
353
+ 'copy_on_model_validation',
354
+ 'post_init_call',
355
+ }
356
+ V2_RENAMED_KEYS = {
357
+ 'allow_population_by_field_name': 'validate_by_name',
358
+ 'anystr_lower': 'str_to_lower',
359
+ 'anystr_strip_whitespace': 'str_strip_whitespace',
360
+ 'anystr_upper': 'str_to_upper',
361
+ 'keep_untouched': 'ignored_types',
362
+ 'max_anystr_length': 'str_max_length',
363
+ 'min_anystr_length': 'str_min_length',
364
+ 'orm_mode': 'from_attributes',
365
+ 'schema_extra': 'json_schema_extra',
366
+ 'validate_all': 'validate_default',
367
+ }
368
+
369
+
370
+ def check_deprecated(config_dict: ConfigDict) -> None:
371
+ """Check for deprecated config keys and warn the user.
372
+
373
+ Args:
374
+ config_dict: The input config.
375
+ """
376
+ deprecated_removed_keys = V2_REMOVED_KEYS & config_dict.keys()
377
+ deprecated_renamed_keys = V2_RENAMED_KEYS.keys() & config_dict.keys()
378
+ if deprecated_removed_keys or deprecated_renamed_keys:
379
+ renamings = {k: V2_RENAMED_KEYS[k] for k in sorted(deprecated_renamed_keys)}
380
+ renamed_bullets = [f'* {k!r} has been renamed to {v!r}' for k, v in renamings.items()]
381
+ removed_bullets = [f'* {k!r} has been removed' for k in sorted(deprecated_removed_keys)]
382
+ message = '\n'.join(['Valid config keys have changed in V2:'] + renamed_bullets + removed_bullets)
383
+ warnings.warn(message, UserWarning)
data/miniconda3/envs/catiagent/lib/python3.11/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
data/miniconda3/envs/catiagent/lib/python3.11/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
data/miniconda3/envs/catiagent/lib/python3.11/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:
217
+ field_args['kw_only'] = True
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
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_decorators.py ADDED
@@ -0,0 +1,858 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sys
6
+ import types
7
+ from collections import deque
8
+ from collections.abc import Iterable
9
+ from dataclasses import dataclass, field
10
+ from functools import cached_property, partial, partialmethod
11
+ from inspect import Parameter, Signature, isdatadescriptor, ismethoddescriptor, signature
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 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
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
+ # This branch will get hit for classmethod properties
264
+ attribute = get_attribute_from_base_dicts(cls_, cls_var_name) # prevents the binding call to `__get__`
265
+ if isinstance(attribute, PydanticDescriptorProxy):
266
+ func = unwrap_wrapped_function(attribute.wrapped)
267
+ return Decorator(
268
+ cls_ref=get_type_ref(cls_),
269
+ cls_var_name=cls_var_name,
270
+ func=func,
271
+ shim=shim,
272
+ info=info,
273
+ )
274
+
275
+ def bind_to_cls(self, cls: Any) -> Decorator[DecoratorInfoType]:
276
+ """Bind the decorator to a class.
277
+
278
+ Args:
279
+ cls: the class.
280
+
281
+ Returns:
282
+ The new decorator instance.
283
+ """
284
+ return self.build(
285
+ cls,
286
+ cls_var_name=self.cls_var_name,
287
+ shim=self.shim,
288
+ info=self.info,
289
+ )
290
+
291
+
292
+ def get_bases(tp: type[Any]) -> tuple[type[Any], ...]:
293
+ """Get the base classes of a class or typeddict.
294
+
295
+ Args:
296
+ tp: The type or class to get the bases.
297
+
298
+ Returns:
299
+ The base classes.
300
+ """
301
+ if is_typeddict(tp):
302
+ return tp.__orig_bases__ # type: ignore
303
+ try:
304
+ return tp.__bases__
305
+ except AttributeError:
306
+ return ()
307
+
308
+
309
+ def mro(tp: type[Any]) -> tuple[type[Any], ...]:
310
+ """Calculate the Method Resolution Order of bases using the C3 algorithm.
311
+
312
+ See https://www.python.org/download/releases/2.3/mro/
313
+ """
314
+ # try to use the existing mro, for performance mainly
315
+ # but also because it helps verify the implementation below
316
+ if not is_typeddict(tp):
317
+ try:
318
+ return tp.__mro__
319
+ except AttributeError:
320
+ # GenericAlias and some other cases
321
+ pass
322
+
323
+ bases = get_bases(tp)
324
+ return (tp,) + mro_for_bases(bases)
325
+
326
+
327
+ def mro_for_bases(bases: tuple[type[Any], ...]) -> tuple[type[Any], ...]:
328
+ def merge_seqs(seqs: list[deque[type[Any]]]) -> Iterable[type[Any]]:
329
+ while True:
330
+ non_empty = [seq for seq in seqs if seq]
331
+ if not non_empty:
332
+ # Nothing left to process, we're done.
333
+ return
334
+ candidate: type[Any] | None = None
335
+ for seq in non_empty: # Find merge candidates among seq heads.
336
+ candidate = seq[0]
337
+ not_head = [s for s in non_empty if candidate in islice(s, 1, None)]
338
+ if not_head:
339
+ # Reject the candidate.
340
+ candidate = None
341
+ else:
342
+ break
343
+ if not candidate:
344
+ raise TypeError('Inconsistent hierarchy, no C3 MRO is possible')
345
+ yield candidate
346
+ for seq in non_empty:
347
+ # Remove candidate.
348
+ if seq[0] == candidate:
349
+ seq.popleft()
350
+
351
+ seqs = [deque(mro(base)) for base in bases] + [deque(bases)]
352
+ return tuple(merge_seqs(seqs))
353
+
354
+
355
+ _sentinel = object()
356
+
357
+
358
+ def get_attribute_from_bases(tp: type[Any] | tuple[type[Any], ...], name: str) -> Any:
359
+ """Get the attribute from the next class in the MRO that has it,
360
+ aiming to simulate calling the method on the actual class.
361
+
362
+ The reason for iterating over the mro instead of just getting
363
+ the attribute (which would do that for us) is to support TypedDict,
364
+ which lacks a real __mro__, but can have a virtual one constructed
365
+ from its bases (as done here).
366
+
367
+ Args:
368
+ tp: The type or class to search for the attribute. If a tuple, this is treated as a set of base classes.
369
+ name: The name of the attribute to retrieve.
370
+
371
+ Returns:
372
+ Any: The attribute value, if found.
373
+
374
+ Raises:
375
+ AttributeError: If the attribute is not found in any class in the MRO.
376
+ """
377
+ if isinstance(tp, tuple):
378
+ for base in mro_for_bases(tp):
379
+ attribute = base.__dict__.get(name, _sentinel)
380
+ if attribute is not _sentinel:
381
+ attribute_get = getattr(attribute, '__get__', None)
382
+ if attribute_get is not None:
383
+ return attribute_get(None, tp)
384
+ return attribute
385
+ raise AttributeError(f'{name} not found in {tp}')
386
+ else:
387
+ try:
388
+ return getattr(tp, name)
389
+ except AttributeError:
390
+ return get_attribute_from_bases(mro(tp), name)
391
+
392
+
393
+ def get_attribute_from_base_dicts(tp: type[Any], name: str) -> Any:
394
+ """Get an attribute out of the `__dict__` following the MRO.
395
+ This prevents the call to `__get__` on the descriptor, and allows
396
+ us to get the original function for classmethod properties.
397
+
398
+ Args:
399
+ tp: The type or class to search for the attribute.
400
+ name: The name of the attribute to retrieve.
401
+
402
+ Returns:
403
+ Any: The attribute value, if found.
404
+
405
+ Raises:
406
+ KeyError: If the attribute is not found in any class's `__dict__` in the MRO.
407
+ """
408
+ for base in reversed(mro(tp)):
409
+ if name in base.__dict__:
410
+ return base.__dict__[name]
411
+ return tp.__dict__[name] # raise the error
412
+
413
+
414
+ @dataclass(**slots_true)
415
+ class DecoratorInfos:
416
+ """Mapping of name in the class namespace to decorator info.
417
+
418
+ note that the name in the class namespace is the function or attribute name
419
+ not the field name!
420
+ """
421
+
422
+ validators: dict[str, Decorator[ValidatorDecoratorInfo]] = field(default_factory=dict)
423
+ field_validators: dict[str, Decorator[FieldValidatorDecoratorInfo]] = field(default_factory=dict)
424
+ root_validators: dict[str, Decorator[RootValidatorDecoratorInfo]] = field(default_factory=dict)
425
+ field_serializers: dict[str, Decorator[FieldSerializerDecoratorInfo]] = field(default_factory=dict)
426
+ model_serializers: dict[str, Decorator[ModelSerializerDecoratorInfo]] = field(default_factory=dict)
427
+ model_validators: dict[str, Decorator[ModelValidatorDecoratorInfo]] = field(default_factory=dict)
428
+ computed_fields: dict[str, Decorator[ComputedFieldInfo]] = field(default_factory=dict)
429
+
430
+ @staticmethod
431
+ def build(model_dc: type[Any]) -> DecoratorInfos: # noqa: C901 (ignore complexity)
432
+ """We want to collect all DecFunc instances that exist as
433
+ attributes in the namespace of the class (a BaseModel or dataclass)
434
+ that called us
435
+ But we want to collect these in the order of the bases
436
+ So instead of getting them all from the leaf class (the class that called us),
437
+ we traverse the bases from root (the oldest ancestor class) to leaf
438
+ and collect all of the instances as we go, taking care to replace
439
+ any duplicate ones with the last one we see to mimic how function overriding
440
+ works with inheritance.
441
+ If we do replace any functions we put the replacement into the position
442
+ the replaced function was in; that is, we maintain the order.
443
+ """
444
+ # reminder: dicts are ordered and replacement does not alter the order
445
+ res = DecoratorInfos()
446
+ for base in reversed(mro(model_dc)[1:]):
447
+ existing: DecoratorInfos | None = base.__dict__.get('__pydantic_decorators__')
448
+ if existing is None:
449
+ existing = DecoratorInfos.build(base)
450
+ res.validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.validators.items()})
451
+ res.field_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.field_validators.items()})
452
+ res.root_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.root_validators.items()})
453
+ res.field_serializers.update({k: v.bind_to_cls(model_dc) for k, v in existing.field_serializers.items()})
454
+ res.model_serializers.update({k: v.bind_to_cls(model_dc) for k, v in existing.model_serializers.items()})
455
+ res.model_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.model_validators.items()})
456
+ res.computed_fields.update({k: v.bind_to_cls(model_dc) for k, v in existing.computed_fields.items()})
457
+
458
+ to_replace: list[tuple[str, Any]] = []
459
+
460
+ for var_name, var_value in vars(model_dc).items():
461
+ if isinstance(var_value, PydanticDescriptorProxy):
462
+ info = var_value.decorator_info
463
+ if isinstance(info, ValidatorDecoratorInfo):
464
+ res.validators[var_name] = Decorator.build(
465
+ model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
466
+ )
467
+ elif isinstance(info, FieldValidatorDecoratorInfo):
468
+ res.field_validators[var_name] = Decorator.build(
469
+ model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
470
+ )
471
+ elif isinstance(info, RootValidatorDecoratorInfo):
472
+ res.root_validators[var_name] = Decorator.build(
473
+ model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
474
+ )
475
+ elif isinstance(info, FieldSerializerDecoratorInfo):
476
+ # check whether a serializer function is already registered for fields
477
+ for field_serializer_decorator in res.field_serializers.values():
478
+ # check that each field has at most one serializer function.
479
+ # serializer functions for the same field in subclasses are allowed,
480
+ # and are treated as overrides
481
+ if field_serializer_decorator.cls_var_name == var_name:
482
+ continue
483
+ for f in info.fields:
484
+ if f in field_serializer_decorator.info.fields:
485
+ raise PydanticUserError(
486
+ 'Multiple field serializer functions were defined '
487
+ f'for field {f!r}, this is not allowed.',
488
+ code='multiple-field-serializers',
489
+ )
490
+ res.field_serializers[var_name] = Decorator.build(
491
+ model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
492
+ )
493
+ elif isinstance(info, ModelValidatorDecoratorInfo):
494
+ res.model_validators[var_name] = Decorator.build(
495
+ model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
496
+ )
497
+ elif isinstance(info, ModelSerializerDecoratorInfo):
498
+ res.model_serializers[var_name] = Decorator.build(
499
+ model_dc, cls_var_name=var_name, shim=var_value.shim, info=info
500
+ )
501
+ else:
502
+ from ..fields import ComputedFieldInfo
503
+
504
+ isinstance(var_value, ComputedFieldInfo)
505
+ res.computed_fields[var_name] = Decorator.build(
506
+ model_dc, cls_var_name=var_name, shim=None, info=info
507
+ )
508
+ to_replace.append((var_name, var_value.wrapped))
509
+ if to_replace:
510
+ # If we can save `__pydantic_decorators__` on the class we'll be able to check for it above
511
+ # so then we don't need to re-process the type, which means we can discard our descriptor wrappers
512
+ # and replace them with the thing they are wrapping (see the other setattr call below)
513
+ # which allows validator class methods to also function as regular class methods
514
+ model_dc.__pydantic_decorators__ = res
515
+ for name, value in to_replace:
516
+ setattr(model_dc, name, value)
517
+ return res
518
+
519
+ def update_from_config(self, config_wrapper: ConfigWrapper) -> None:
520
+ """Update the decorator infos from the configuration of the class they are attached to."""
521
+ for name, computed_field_dec in self.computed_fields.items():
522
+ computed_field_dec.info._update_from_config(config_wrapper, name)
523
+
524
+
525
+ def inspect_validator(
526
+ validator: Callable[..., Any], *, mode: FieldValidatorModes, type: Literal['field', 'model']
527
+ ) -> bool:
528
+ """Look at a field or model validator function and determine whether it takes an info argument.
529
+
530
+ An error is raised if the function has an invalid signature.
531
+
532
+ Args:
533
+ validator: The validator function to inspect.
534
+ mode: The proposed validator mode.
535
+ type: The type of validator, either 'field' or 'model'.
536
+
537
+ Returns:
538
+ Whether the validator takes an info argument.
539
+ """
540
+ try:
541
+ sig = _signature_no_eval(validator)
542
+ except (ValueError, TypeError):
543
+ # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
544
+ # In this case, we assume no info argument is present:
545
+ return False
546
+ n_positional = count_positional_required_params(sig)
547
+ if mode == 'wrap':
548
+ if n_positional == 3:
549
+ return True
550
+ elif n_positional == 2:
551
+ return False
552
+ else:
553
+ assert mode in {'before', 'after', 'plain'}, f"invalid mode: {mode!r}, expected 'before', 'after' or 'plain"
554
+ if n_positional == 2:
555
+ return True
556
+ elif n_positional == 1:
557
+ return False
558
+
559
+ raise PydanticUserError(
560
+ f'Unrecognized {type} validator function signature for {validator} with `mode={mode}`: {sig}',
561
+ code='validator-signature',
562
+ )
563
+
564
+
565
+ def inspect_field_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> tuple[bool, bool]:
566
+ """Look at a field serializer function and determine if it is a field serializer,
567
+ and whether it takes an info argument.
568
+
569
+ An error is raised if the function has an invalid signature.
570
+
571
+ Args:
572
+ serializer: The serializer function to inspect.
573
+ mode: The serializer mode, either 'plain' or 'wrap'.
574
+
575
+ Returns:
576
+ Tuple of (is_field_serializer, info_arg).
577
+ """
578
+ try:
579
+ sig = _signature_no_eval(serializer)
580
+ except (ValueError, TypeError):
581
+ # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
582
+ # In this case, we assume no info argument is present and this is not a method:
583
+ return (False, False)
584
+
585
+ first = next(iter(sig.parameters.values()), None)
586
+ is_field_serializer = first is not None and first.name == 'self'
587
+
588
+ n_positional = count_positional_required_params(sig)
589
+ if is_field_serializer:
590
+ # -1 to correct for self parameter
591
+ info_arg = _serializer_info_arg(mode, n_positional - 1)
592
+ else:
593
+ info_arg = _serializer_info_arg(mode, n_positional)
594
+
595
+ if info_arg is None:
596
+ raise PydanticUserError(
597
+ f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}',
598
+ code='field-serializer-signature',
599
+ )
600
+
601
+ return is_field_serializer, info_arg
602
+
603
+
604
+ def inspect_annotated_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool:
605
+ """Look at a serializer function used via `Annotated` and determine whether it takes an info argument.
606
+
607
+ An error is raised if the function has an invalid signature.
608
+
609
+ Args:
610
+ serializer: The serializer function to check.
611
+ mode: The serializer mode, either 'plain' or 'wrap'.
612
+
613
+ Returns:
614
+ info_arg
615
+ """
616
+ try:
617
+ sig = _signature_no_eval(serializer)
618
+ except (ValueError, TypeError):
619
+ # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
620
+ # In this case, we assume no info argument is present:
621
+ return False
622
+ info_arg = _serializer_info_arg(mode, count_positional_required_params(sig))
623
+ if info_arg is None:
624
+ raise PydanticUserError(
625
+ f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}',
626
+ code='field-serializer-signature',
627
+ )
628
+ else:
629
+ return info_arg
630
+
631
+
632
+ def inspect_model_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool:
633
+ """Look at a model serializer function and determine whether it takes an info argument.
634
+
635
+ An error is raised if the function has an invalid signature.
636
+
637
+ Args:
638
+ serializer: The serializer function to check.
639
+ mode: The serializer mode, either 'plain' or 'wrap'.
640
+
641
+ Returns:
642
+ `info_arg` - whether the function expects an info argument.
643
+ """
644
+ if isinstance(serializer, (staticmethod, classmethod)) or not is_instance_method_from_sig(serializer):
645
+ raise PydanticUserError(
646
+ '`@model_serializer` must be applied to instance methods', code='model-serializer-instance-method'
647
+ )
648
+
649
+ sig = _signature_no_eval(serializer)
650
+ info_arg = _serializer_info_arg(mode, count_positional_required_params(sig))
651
+ if info_arg is None:
652
+ raise PydanticUserError(
653
+ f'Unrecognized model_serializer function signature for {serializer} with `mode={mode}`:{sig}',
654
+ code='model-serializer-signature',
655
+ )
656
+ else:
657
+ return info_arg
658
+
659
+
660
+ def _serializer_info_arg(mode: Literal['plain', 'wrap'], n_positional: int) -> bool | None:
661
+ if mode == 'plain':
662
+ if n_positional == 1:
663
+ # (input_value: Any, /) -> Any
664
+ return False
665
+ elif n_positional == 2:
666
+ # (model: Any, input_value: Any, /) -> Any
667
+ return True
668
+ else:
669
+ assert mode == 'wrap', f"invalid mode: {mode!r}, expected 'plain' or 'wrap'"
670
+ if n_positional == 2:
671
+ # (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
672
+ return False
673
+ elif n_positional == 3:
674
+ # (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any
675
+ return True
676
+
677
+ return None
678
+
679
+
680
+ AnyDecoratorCallable: TypeAlias = (
681
+ 'Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any], Callable[..., Any]]'
682
+ )
683
+
684
+
685
+ def is_instance_method_from_sig(function: AnyDecoratorCallable) -> bool:
686
+ """Whether the function is an instance method.
687
+
688
+ It will consider a function as instance method if the first parameter of
689
+ function is `self`.
690
+
691
+ Args:
692
+ function: The function to check.
693
+
694
+ Returns:
695
+ `True` if the function is an instance method, `False` otherwise.
696
+ """
697
+ sig = _signature_no_eval(unwrap_wrapped_function(function))
698
+ first = next(iter(sig.parameters.values()), None)
699
+ if first and first.name == 'self':
700
+ return True
701
+ return False
702
+
703
+
704
+ def ensure_classmethod_based_on_signature(function: AnyDecoratorCallable) -> Any:
705
+ """Apply the `@classmethod` decorator on the function.
706
+
707
+ Args:
708
+ function: The function to apply the decorator on.
709
+
710
+ Return:
711
+ The `@classmethod` decorator applied function.
712
+ """
713
+ if not isinstance(
714
+ unwrap_wrapped_function(function, unwrap_class_static_method=False), classmethod
715
+ ) and _is_classmethod_from_sig(function):
716
+ return classmethod(function) # type: ignore[arg-type]
717
+ return function
718
+
719
+
720
+ def _is_classmethod_from_sig(function: AnyDecoratorCallable) -> bool:
721
+ sig = _signature_no_eval(unwrap_wrapped_function(function))
722
+ first = next(iter(sig.parameters.values()), None)
723
+ if first and first.name == 'cls':
724
+ return True
725
+ return False
726
+
727
+
728
+ def unwrap_wrapped_function(
729
+ func: Any,
730
+ *,
731
+ unwrap_partial: bool = True,
732
+ unwrap_class_static_method: bool = True,
733
+ ) -> Any:
734
+ """Recursively unwraps a wrapped function until the underlying function is reached.
735
+ This handles property, functools.partial, functools.partialmethod, staticmethod, and classmethod.
736
+
737
+ Args:
738
+ func: The function to unwrap.
739
+ unwrap_partial: If True (default), unwrap partial and partialmethod decorators.
740
+ unwrap_class_static_method: If True (default), also unwrap classmethod and staticmethod
741
+ decorators. If False, only unwrap partial and partialmethod decorators.
742
+
743
+ Returns:
744
+ The underlying function of the wrapped function.
745
+ """
746
+ # Define the types we want to check against as a single tuple.
747
+ unwrap_types = (
748
+ (property, cached_property)
749
+ + ((partial, partialmethod) if unwrap_partial else ())
750
+ + ((staticmethod, classmethod) if unwrap_class_static_method else ())
751
+ )
752
+
753
+ while isinstance(func, unwrap_types):
754
+ if unwrap_class_static_method and isinstance(func, (classmethod, staticmethod)):
755
+ func = func.__func__
756
+ elif isinstance(func, (partial, partialmethod)):
757
+ func = func.func
758
+ elif isinstance(func, property):
759
+ func = func.fget # arbitrary choice, convenient for computed fields
760
+ else:
761
+ # Make coverage happy as it can only get here in the last possible case
762
+ assert isinstance(func, cached_property)
763
+ func = func.func # type: ignore
764
+
765
+ return func
766
+
767
+
768
+ _function_like = (
769
+ partial,
770
+ partialmethod,
771
+ types.FunctionType,
772
+ types.BuiltinFunctionType,
773
+ types.MethodType,
774
+ types.WrapperDescriptorType,
775
+ types.MethodWrapperType,
776
+ types.MemberDescriptorType,
777
+ )
778
+
779
+
780
+ def get_callable_return_type(
781
+ callable_obj: Any,
782
+ globalns: GlobalsNamespace | None = None,
783
+ localns: MappingNamespace | None = None,
784
+ ) -> Any | PydanticUndefinedType:
785
+ """Get the callable return type.
786
+
787
+ Args:
788
+ callable_obj: The callable to analyze.
789
+ globalns: The globals namespace to use during type annotation evaluation.
790
+ localns: The locals namespace to use during type annotation evaluation.
791
+
792
+ Returns:
793
+ The function return type.
794
+ """
795
+ if isinstance(callable_obj, type):
796
+ # types are callables, and we assume the return type
797
+ # is the type itself (e.g. `int()` results in an instance of `int`).
798
+ return callable_obj
799
+
800
+ if not isinstance(callable_obj, _function_like):
801
+ call_func = getattr(type(callable_obj), '__call__', None) # noqa: B004
802
+ if call_func is not None:
803
+ callable_obj = call_func
804
+
805
+ hints = get_function_type_hints(
806
+ unwrap_wrapped_function(callable_obj),
807
+ include_keys={'return'},
808
+ globalns=globalns,
809
+ localns=localns,
810
+ )
811
+ return hints.get('return', PydanticUndefined)
812
+
813
+
814
+ def count_positional_required_params(sig: Signature) -> int:
815
+ """Get the number of positional (required) arguments of a signature.
816
+
817
+ This function should only be used to inspect signatures of validation and serialization functions.
818
+ The first argument (the value being serialized or validated) is counted as a required argument
819
+ even if a default value exists.
820
+
821
+ Returns:
822
+ The number of positional arguments of a signature.
823
+ """
824
+ parameters = list(sig.parameters.values())
825
+ return sum(
826
+ 1
827
+ for param in parameters
828
+ if can_be_positional(param)
829
+ # First argument is the value being validated/serialized, and can have a default value
830
+ # (e.g. `float`, which has signature `(x=0, /)`). We assume other parameters (the info arg
831
+ # for instance) should be required, and thus without any default value.
832
+ and (param.default is Parameter.empty or param is parameters[0])
833
+ )
834
+
835
+
836
+ def ensure_property(f: Any) -> Any:
837
+ """Ensure that a function is a `property` or `cached_property`, or is a valid descriptor.
838
+
839
+ Args:
840
+ f: The function to check.
841
+
842
+ Returns:
843
+ The function, or a `property` or `cached_property` instance wrapping the function.
844
+ """
845
+ if ismethoddescriptor(f) or isdatadescriptor(f):
846
+ return f
847
+ else:
848
+ return property(f)
849
+
850
+
851
+ def _signature_no_eval(f: Callable[..., Any]) -> Signature:
852
+ """Get the signature of a callable without evaluating any annotations."""
853
+ if sys.version_info >= (3, 14):
854
+ from annotationlib import Format
855
+
856
+ return signature(f, annotation_format=Format.FORWARDREF)
857
+ else:
858
+ return signature(f)
data/miniconda3/envs/catiagent/lib/python3.11/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
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_discriminated_union.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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'] != 'union':
189
+ # If the schema is not a union, it probably means it just had a single member and
190
+ # was flattened by pydantic_core.
191
+ # However, it still may make sense to apply the discriminator to this schema,
192
+ # as a way to get discriminated-union-style error messages, so we allow this here.
193
+ schema = core_schema.union_schema([schema])
194
+
195
+ # Reverse the choices list before extending the stack so that they get handled in the order they occur
196
+ choices_schemas = [v[0] if isinstance(v, tuple) else v for v in schema['choices'][::-1]]
197
+ self._choices_to_handle.extend(choices_schemas)
198
+ while self._choices_to_handle:
199
+ choice = self._choices_to_handle.pop()
200
+ self._handle_choice(choice)
201
+
202
+ if self._discriminator_alias is not None and self._discriminator_alias != self.discriminator:
203
+ # * We need to annotate `discriminator` as a union here to handle both branches of this conditional
204
+ # * We need to annotate `discriminator` as list[list[str | int]] and not list[list[str]] due to the
205
+ # invariance of list, and because list[list[str | int]] is the type of the discriminator argument
206
+ # to tagged_union_schema below
207
+ # * See the docstring of pydantic_core.core_schema.tagged_union_schema for more details about how to
208
+ # interpret the value of the discriminator argument to tagged_union_schema. (The list[list[str]] here
209
+ # is the appropriate way to provide a list of fallback attributes to check for a discriminator value.)
210
+ discriminator: str | list[list[str | int]] = [[self.discriminator], [self._discriminator_alias]]
211
+ else:
212
+ discriminator = self.discriminator
213
+ return core_schema.tagged_union_schema(
214
+ choices=self._tagged_union_choices,
215
+ discriminator=discriminator,
216
+ custom_error_type=schema.get('custom_error_type'),
217
+ custom_error_message=schema.get('custom_error_message'),
218
+ custom_error_context=schema.get('custom_error_context'),
219
+ strict=False,
220
+ from_attributes=True,
221
+ ref=schema.get('ref'),
222
+ metadata=schema.get('metadata'),
223
+ serialization=schema.get('serialization'),
224
+ )
225
+
226
+ def _handle_choice(self, choice: core_schema.CoreSchema) -> None:
227
+ """This method handles the "middle" stage of recursion over the input schema.
228
+ Specifically, it is responsible for handling each choice of the outermost union
229
+ (and any "coalesced" choices obtained from inner unions).
230
+
231
+ Here, "handling" entails:
232
+ * Coalescing nested unions and compatible tagged-unions
233
+ * Tracking the presence of 'none' and 'nullable' schemas occurring as choices
234
+ * Validating that each allowed discriminator value maps to a unique choice
235
+ * Updating the _tagged_union_choices mapping that will ultimately be used to build the TaggedUnionSchema.
236
+ """
237
+ if choice['type'] == 'definition-ref':
238
+ if choice['schema_ref'] not in self.definitions:
239
+ raise MissingDefinitionForUnionRef(choice['schema_ref'])
240
+
241
+ if choice['type'] == 'none':
242
+ self._should_be_nullable = True
243
+ elif choice['type'] == 'definitions':
244
+ self._handle_choice(choice['schema'])
245
+ elif choice['type'] == 'nullable':
246
+ self._should_be_nullable = True
247
+ self._handle_choice(choice['schema']) # unwrap the nullable schema
248
+ elif choice['type'] == 'union':
249
+ # Reverse the choices list before extending the stack so that they get handled in the order they occur
250
+ choices_schemas = [v[0] if isinstance(v, tuple) else v for v in choice['choices'][::-1]]
251
+ self._choices_to_handle.extend(choices_schemas)
252
+ elif choice['type'] not in {
253
+ 'model',
254
+ 'typed-dict',
255
+ 'tagged-union',
256
+ 'lax-or-strict',
257
+ 'dataclass',
258
+ 'dataclass-args',
259
+ 'definition-ref',
260
+ } and not _core_utils.is_function_with_inner_schema(choice):
261
+ # We should eventually handle 'definition-ref' as well
262
+ err_str = f'The core schema type {choice["type"]!r} is not a valid discriminated union variant.'
263
+ if choice['type'] == 'list':
264
+ err_str += (
265
+ ' If you are making use of a list of union types, make sure the discriminator is applied to the '
266
+ 'union type and not the list (e.g. `list[Annotated[<T> | <U>, Field(discriminator=...)]]`).'
267
+ )
268
+ raise TypeError(err_str)
269
+ else:
270
+ if choice['type'] == 'tagged-union' and self._is_discriminator_shared(choice):
271
+ # In this case, this inner tagged-union is compatible with the outer tagged-union,
272
+ # and its choices can be coalesced into the outer TaggedUnionSchema.
273
+ subchoices = [x for x in choice['choices'].values() if not isinstance(x, (str, int))]
274
+ # Reverse the choices list before extending the stack so that they get handled in the order they occur
275
+ self._choices_to_handle.extend(subchoices[::-1])
276
+ return
277
+
278
+ inferred_discriminator_values = self._infer_discriminator_values_for_choice(choice, source_name=None)
279
+ self._set_unique_choice_for_values(choice, inferred_discriminator_values)
280
+
281
+ def _is_discriminator_shared(self, choice: core_schema.TaggedUnionSchema) -> bool:
282
+ """This method returns a boolean indicating whether the discriminator for the `choice`
283
+ is the same as that being used for the outermost tagged union. This is used to
284
+ determine whether this TaggedUnionSchema choice should be "coalesced" into the top level,
285
+ or whether it should be treated as a separate (nested) choice.
286
+ """
287
+ inner_discriminator = choice['discriminator']
288
+ return inner_discriminator == self.discriminator or (
289
+ isinstance(inner_discriminator, list)
290
+ and (self.discriminator in inner_discriminator or [self.discriminator] in inner_discriminator)
291
+ )
292
+
293
+ def _infer_discriminator_values_for_choice( # noqa C901
294
+ self, choice: core_schema.CoreSchema, source_name: str | None
295
+ ) -> list[str | int]:
296
+ """This function recurses over `choice`, extracting all discriminator values that should map to this choice.
297
+
298
+ `model_name` is accepted for the purpose of producing useful error messages.
299
+ """
300
+ if choice['type'] == 'definitions':
301
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=source_name)
302
+
303
+ elif _core_utils.is_function_with_inner_schema(choice):
304
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=source_name)
305
+
306
+ elif choice['type'] == 'lax-or-strict':
307
+ return sorted(
308
+ set(
309
+ self._infer_discriminator_values_for_choice(choice['lax_schema'], source_name=None)
310
+ + self._infer_discriminator_values_for_choice(choice['strict_schema'], source_name=None)
311
+ )
312
+ )
313
+
314
+ elif choice['type'] == 'tagged-union':
315
+ values: list[str | int] = []
316
+ # Ignore str/int "choices" since these are just references to other choices
317
+ subchoices = [x for x in choice['choices'].values() if not isinstance(x, (str, int))]
318
+ for subchoice in subchoices:
319
+ subchoice_values = self._infer_discriminator_values_for_choice(subchoice, source_name=None)
320
+ values.extend(subchoice_values)
321
+ return values
322
+
323
+ elif choice['type'] == 'union':
324
+ values = []
325
+ for subchoice in choice['choices']:
326
+ subchoice_schema = subchoice[0] if isinstance(subchoice, tuple) else subchoice
327
+ subchoice_values = self._infer_discriminator_values_for_choice(subchoice_schema, source_name=None)
328
+ values.extend(subchoice_values)
329
+ return values
330
+
331
+ elif choice['type'] == 'nullable':
332
+ self._should_be_nullable = True
333
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=None)
334
+
335
+ elif choice['type'] == 'model':
336
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=choice['cls'].__name__)
337
+
338
+ elif choice['type'] == 'dataclass':
339
+ return self._infer_discriminator_values_for_choice(choice['schema'], source_name=choice['cls'].__name__)
340
+
341
+ elif choice['type'] == 'model-fields':
342
+ return self._infer_discriminator_values_for_model_choice(choice, source_name=source_name)
343
+
344
+ elif choice['type'] == 'dataclass-args':
345
+ return self._infer_discriminator_values_for_dataclass_choice(choice, source_name=source_name)
346
+
347
+ elif choice['type'] == 'typed-dict':
348
+ return self._infer_discriminator_values_for_typed_dict_choice(choice, source_name=source_name)
349
+
350
+ elif choice['type'] == 'definition-ref':
351
+ schema_ref = choice['schema_ref']
352
+ if schema_ref not in self.definitions:
353
+ raise MissingDefinitionForUnionRef(schema_ref)
354
+ return self._infer_discriminator_values_for_choice(self.definitions[schema_ref], source_name=source_name)
355
+ else:
356
+ err_str = f'The core schema type {choice["type"]!r} is not a valid discriminated union variant.'
357
+ if choice['type'] == 'list':
358
+ err_str += (
359
+ ' If you are making use of a list of union types, make sure the discriminator is applied to the '
360
+ 'union type and not the list (e.g. `list[Annotated[<T> | <U>, Field(discriminator=...)]]`).'
361
+ )
362
+ raise TypeError(err_str)
363
+
364
+ def _infer_discriminator_values_for_typed_dict_choice(
365
+ self, choice: core_schema.TypedDictSchema, source_name: str | None = None
366
+ ) -> list[str | int]:
367
+ """This method just extracts the _infer_discriminator_values_for_choice logic specific to TypedDictSchema
368
+ for the sake of readability.
369
+ """
370
+ source = 'TypedDict' if source_name is None else f'TypedDict {source_name!r}'
371
+ field = choice['fields'].get(self.discriminator)
372
+ if field is None:
373
+ raise PydanticUserError(
374
+ f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field'
375
+ )
376
+ return self._infer_discriminator_values_for_field(field, source)
377
+
378
+ def _infer_discriminator_values_for_model_choice(
379
+ self, choice: core_schema.ModelFieldsSchema, source_name: str | None = None
380
+ ) -> list[str | int]:
381
+ source = 'ModelFields' if source_name is None else f'Model {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_dataclass_choice(
390
+ self, choice: core_schema.DataclassArgsSchema, source_name: str | None = None
391
+ ) -> list[str | int]:
392
+ source = 'DataclassArgs' if source_name is None else f'Dataclass {source_name!r}'
393
+ for field in choice['fields']:
394
+ if field['name'] == self.discriminator:
395
+ break
396
+ else:
397
+ raise PydanticUserError(
398
+ f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field'
399
+ )
400
+ return self._infer_discriminator_values_for_field(field, source)
401
+
402
+ def _infer_discriminator_values_for_field(self, field: CoreSchemaField, source: str) -> list[str | int]:
403
+ if field['type'] == 'computed-field':
404
+ # This should never occur as a discriminator, as it is only relevant to serialization
405
+ return []
406
+ alias = field.get('validation_alias', self.discriminator)
407
+ if not isinstance(alias, str):
408
+ raise PydanticUserError(
409
+ f'Alias {alias!r} is not supported in a discriminated union', code='discriminator-alias-type'
410
+ )
411
+ if self._discriminator_alias is None:
412
+ self._discriminator_alias = alias
413
+ elif self._discriminator_alias != alias:
414
+ raise PydanticUserError(
415
+ f'Aliases for discriminator {self.discriminator!r} must be the same '
416
+ f'(got {alias}, {self._discriminator_alias})',
417
+ code='discriminator-alias',
418
+ )
419
+ return self._infer_discriminator_values_for_inner_schema(field['schema'], source)
420
+
421
+ def _infer_discriminator_values_for_inner_schema(
422
+ self, schema: core_schema.CoreSchema, source: str
423
+ ) -> list[str | int]:
424
+ """When inferring discriminator values for a field, we typically extract the expected values from a literal
425
+ schema. This function does that, but also handles nested unions and defaults.
426
+ """
427
+ if schema['type'] == 'literal':
428
+ return schema['expected']
429
+
430
+ elif schema['type'] == 'union':
431
+ # Generally when multiple values are allowed they should be placed in a single `Literal`, but
432
+ # we add this case to handle the situation where a field is annotated as a `Union` of `Literal`s.
433
+ # For example, this lets us handle `Union[Literal['key'], Union[Literal['Key'], Literal['KEY']]]`
434
+ values: list[Any] = []
435
+ for choice in schema['choices']:
436
+ choice_schema = choice[0] if isinstance(choice, tuple) else choice
437
+ choice_values = self._infer_discriminator_values_for_inner_schema(choice_schema, source)
438
+ values.extend(choice_values)
439
+ return values
440
+
441
+ elif schema['type'] == 'default':
442
+ # This will happen if the field has a default value; we ignore it while extracting the discriminator values
443
+ return self._infer_discriminator_values_for_inner_schema(schema['schema'], source)
444
+
445
+ elif schema['type'] == 'function-after':
446
+ # After validators don't affect the discriminator values
447
+ return self._infer_discriminator_values_for_inner_schema(schema['schema'], source)
448
+
449
+ elif schema['type'] in {'function-before', 'function-wrap', 'function-plain'}:
450
+ validator_type = repr(schema['type'].split('-')[1])
451
+ raise PydanticUserError(
452
+ f'Cannot use a mode={validator_type} validator in the'
453
+ f' discriminator field {self.discriminator!r} of {source}',
454
+ code='discriminator-validator',
455
+ )
456
+
457
+ else:
458
+ raise PydanticUserError(
459
+ f'{source} needs field {self.discriminator!r} to be of type `Literal`',
460
+ code='discriminator-needs-literal',
461
+ )
462
+
463
+ def _set_unique_choice_for_values(self, choice: core_schema.CoreSchema, values: Sequence[str | int]) -> None:
464
+ """This method updates `self.tagged_union_choices` so that all provided (discriminator) `values` map to the
465
+ provided `choice`, validating that none of these values already map to another (different) choice.
466
+ """
467
+ for discriminator_value in values:
468
+ if discriminator_value in self._tagged_union_choices:
469
+ # It is okay if `value` is already in tagged_union_choices as long as it maps to the same value.
470
+ # Because tagged_union_choices may map values to other values, we need to walk the choices dict
471
+ # until we get to a "real" choice, and confirm that is equal to the one assigned.
472
+ existing_choice = self._tagged_union_choices[discriminator_value]
473
+ if existing_choice != choice:
474
+ raise TypeError(
475
+ f'Value {discriminator_value!r} for discriminator '
476
+ f'{self.discriminator!r} mapped to multiple choices'
477
+ )
478
+ else:
479
+ self._tagged_union_choices[discriminator_value] = choice
data/miniconda3/envs/catiagent/lib/python3.11/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
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_fields.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, signature
10
+ from re import Pattern
11
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar
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 ._namespace_utils import NsResolver
26
+ from ._repr import Representation
27
+ from ._utils import can_be_positional, get_first_not_none
28
+
29
+ if TYPE_CHECKING:
30
+ from annotated_types import BaseMetadata
31
+
32
+ from ..fields import FieldInfo
33
+ from ..main import BaseModel
34
+ from ._dataclasses import PydanticDataclass, StandardDataclass
35
+ from ._decorators import DecoratorInfos
36
+
37
+
38
+ class PydanticMetadata(Representation):
39
+ """Base class for annotation markers like `Strict`."""
40
+
41
+ __slots__ = ()
42
+
43
+
44
+ def pydantic_general_metadata(**metadata: Any) -> BaseMetadata:
45
+ """Create a new `_PydanticGeneralMetadata` class with the given metadata.
46
+
47
+ Args:
48
+ **metadata: The metadata to add.
49
+
50
+ Returns:
51
+ The new `_PydanticGeneralMetadata` class.
52
+ """
53
+ return _general_metadata_cls()(metadata) # type: ignore
54
+
55
+
56
+ @cache
57
+ def _general_metadata_cls() -> type[BaseMetadata]:
58
+ """Do it this way to avoid importing `annotated_types` at import time."""
59
+ from annotated_types import BaseMetadata
60
+
61
+ class _PydanticGeneralMetadata(PydanticMetadata, BaseMetadata):
62
+ """Pydantic general metadata like `max_digits`."""
63
+
64
+ def __init__(self, metadata: Any):
65
+ self.__dict__ = metadata
66
+
67
+ return _PydanticGeneralMetadata # type: ignore
68
+
69
+
70
+ def _check_protected_namespaces(
71
+ protected_namespaces: tuple[str | Pattern[str], ...],
72
+ ann_name: str,
73
+ bases: tuple[type[Any], ...],
74
+ cls_name: str,
75
+ ) -> None:
76
+ BaseModel = import_cached_base_model()
77
+
78
+ for protected_namespace in protected_namespaces:
79
+ ns_violation = False
80
+ if isinstance(protected_namespace, Pattern):
81
+ ns_violation = protected_namespace.match(ann_name) is not None
82
+ elif isinstance(protected_namespace, str):
83
+ ns_violation = ann_name.startswith(protected_namespace)
84
+
85
+ if ns_violation:
86
+ for b in bases:
87
+ if hasattr(b, ann_name):
88
+ if not (issubclass(b, BaseModel) and ann_name in getattr(b, '__pydantic_fields__', {})):
89
+ raise ValueError(
90
+ f'Field {ann_name!r} conflicts with member {getattr(b, ann_name)}'
91
+ f' of protected namespace {protected_namespace!r}.'
92
+ )
93
+ else:
94
+ valid_namespaces: list[str] = []
95
+ for pn in protected_namespaces:
96
+ if isinstance(pn, Pattern):
97
+ if not pn.match(ann_name):
98
+ valid_namespaces.append(f're.compile({pn.pattern!r})')
99
+ else:
100
+ if not ann_name.startswith(pn):
101
+ valid_namespaces.append(f"'{pn}'")
102
+
103
+ valid_namespaces_str = f'({", ".join(valid_namespaces)}{",)" if len(valid_namespaces) == 1 else ")"}'
104
+
105
+ warnings.warn(
106
+ f'Field {ann_name!r} in {cls_name!r} conflicts with protected namespace {protected_namespace!r}.\n\n'
107
+ f"You may be able to solve this by setting the 'protected_namespaces' configuration to {valid_namespaces_str}.",
108
+ UserWarning,
109
+ stacklevel=5,
110
+ )
111
+
112
+
113
+ def _update_fields_from_docstrings(cls: type[Any], fields: dict[str, FieldInfo], use_inspect: bool = False) -> None:
114
+ fields_docs = extract_docstrings_from_cls(cls, use_inspect=use_inspect)
115
+ for ann_name, field_info in fields.items():
116
+ if field_info.description is None and ann_name in fields_docs:
117
+ field_info.description = fields_docs[ann_name]
118
+
119
+
120
+ def _apply_field_title_generator_to_field_info(
121
+ title_generator: Callable[[str, FieldInfo], str],
122
+ field_name: str,
123
+ field_info: FieldInfo,
124
+ ):
125
+ if field_info.title is None:
126
+ title = title_generator(field_name, field_info)
127
+ if not isinstance(title, str):
128
+ raise TypeError(f'field_title_generator {title_generator} must return str, not {title.__class__}')
129
+
130
+ field_info.title = title
131
+
132
+
133
+ def _apply_alias_generator_to_field_info(
134
+ alias_generator: Callable[[str], str] | AliasGenerator, field_name: str, field_info: FieldInfo
135
+ ):
136
+ """Apply an alias generator to aliases on a `FieldInfo` instance if appropriate.
137
+
138
+ Args:
139
+ alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
140
+ field_name: The name of the field from which to generate the alias.
141
+ field_info: The `FieldInfo` instance to which the alias generator is (maybe) applied.
142
+ """
143
+ # Apply an alias_generator if
144
+ # 1. An alias is not specified
145
+ # 2. An alias is specified, but the priority is <= 1
146
+ if (
147
+ field_info.alias_priority is None
148
+ or field_info.alias_priority <= 1
149
+ or field_info.alias is None
150
+ or field_info.validation_alias is None
151
+ or field_info.serialization_alias is None
152
+ ):
153
+ alias, validation_alias, serialization_alias = None, None, None
154
+
155
+ if isinstance(alias_generator, AliasGenerator):
156
+ alias, validation_alias, serialization_alias = alias_generator.generate_aliases(field_name)
157
+ elif callable(alias_generator):
158
+ alias = alias_generator(field_name)
159
+ if not isinstance(alias, str):
160
+ raise TypeError(f'alias_generator {alias_generator} must return str, not {alias.__class__}')
161
+
162
+ # if priority is not set, we set to 1
163
+ # which supports the case where the alias_generator from a child class is used
164
+ # to generate an alias for a field in a parent class
165
+ if field_info.alias_priority is None or field_info.alias_priority <= 1:
166
+ field_info.alias_priority = 1
167
+
168
+ # if the priority is 1, then we set the aliases to the generated alias
169
+ if field_info.alias_priority == 1:
170
+ field_info.serialization_alias = get_first_not_none(serialization_alias, alias)
171
+ field_info.validation_alias = get_first_not_none(validation_alias, alias)
172
+ field_info.alias = alias
173
+
174
+ # if any of the aliases are not set, then we set them to the corresponding generated alias
175
+ if field_info.alias is None:
176
+ field_info.alias = alias
177
+ if field_info.serialization_alias is None:
178
+ field_info.serialization_alias = get_first_not_none(serialization_alias, alias)
179
+ if field_info.validation_alias is None:
180
+ field_info.validation_alias = get_first_not_none(validation_alias, alias)
181
+
182
+
183
+ def update_field_from_config(config_wrapper: ConfigWrapper, field_name: str, field_info: FieldInfo) -> None:
184
+ """Update the `FieldInfo` instance from the configuration set on the model it belongs to.
185
+
186
+ This will apply the title and alias generators from the configuration.
187
+
188
+ Args:
189
+ config_wrapper: The configuration from the model.
190
+ field_name: The field name the `FieldInfo` instance is attached to.
191
+ field_info: The `FieldInfo` instance to update.
192
+ """
193
+ field_title_generator = field_info.field_title_generator or config_wrapper.field_title_generator
194
+ if field_title_generator is not None:
195
+ _apply_field_title_generator_to_field_info(field_title_generator, field_name, field_info)
196
+ if config_wrapper.alias_generator is not None:
197
+ _apply_alias_generator_to_field_info(config_wrapper.alias_generator, field_name, field_info)
198
+
199
+
200
+ _deprecated_method_names = {'dict', 'json', 'copy', '_iter', '_copy_and_set_values', '_calculate_keys'}
201
+
202
+ _deprecated_classmethod_names = {
203
+ 'parse_obj',
204
+ 'parse_raw',
205
+ 'parse_file',
206
+ 'from_orm',
207
+ 'construct',
208
+ 'schema',
209
+ 'schema_json',
210
+ 'validate',
211
+ 'update_forward_refs',
212
+ '_get_value',
213
+ }
214
+
215
+
216
+ def collect_model_fields( # noqa: C901
217
+ cls: type[BaseModel],
218
+ config_wrapper: ConfigWrapper,
219
+ ns_resolver: NsResolver | None,
220
+ *,
221
+ typevars_map: Mapping[TypeVar, Any] | None = None,
222
+ ) -> tuple[dict[str, FieldInfo], set[str]]:
223
+ """Collect the fields and class variables names of a nascent Pydantic model.
224
+
225
+ The fields collection process is *lenient*, meaning it won't error if string annotations
226
+ fail to evaluate. If this happens, the original annotation (and assigned value, if any)
227
+ is stored on the created `FieldInfo` instance.
228
+
229
+ The `rebuild_model_fields()` should be called at a later point (e.g. when rebuilding the model),
230
+ and will make use of these stored attributes.
231
+
232
+ Args:
233
+ cls: BaseModel or dataclass.
234
+ config_wrapper: The config wrapper instance.
235
+ ns_resolver: Namespace resolver to use when getting model annotations.
236
+ typevars_map: A dictionary mapping type variables to their concrete types.
237
+
238
+ Returns:
239
+ A two-tuple containing model fields and class variables names.
240
+
241
+ Raises:
242
+ NameError:
243
+ - If there is a conflict between a field name and protected namespaces.
244
+ - If there is a field other than `root` in `RootModel`.
245
+ - If a field shadows an attribute in the parent model.
246
+ """
247
+ FieldInfo_ = import_cached_field_info()
248
+ BaseModel_ = import_cached_base_model()
249
+
250
+ bases = cls.__bases__
251
+ parent_fields_lookup: dict[str, FieldInfo] = {}
252
+ for base in reversed(bases):
253
+ if model_fields := getattr(base, '__pydantic_fields__', None):
254
+ parent_fields_lookup.update(model_fields)
255
+
256
+ type_hints = _typing_extra.get_model_type_hints(cls, ns_resolver=ns_resolver)
257
+
258
+ # https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older
259
+ # annotations is only used for finding fields in parent classes
260
+ annotations = _typing_extra.safe_get_annotations(cls)
261
+
262
+ fields: dict[str, FieldInfo] = {}
263
+
264
+ class_vars: set[str] = set()
265
+ for ann_name, (ann_type, evaluated) in type_hints.items():
266
+ if ann_name == 'model_config':
267
+ # We never want to treat `model_config` as a field
268
+ # Note: we may need to change this logic if/when we introduce a `BareModel` class with no
269
+ # protected namespaces (where `model_config` might be allowed as a field name)
270
+ continue
271
+
272
+ _check_protected_namespaces(
273
+ protected_namespaces=config_wrapper.protected_namespaces,
274
+ ann_name=ann_name,
275
+ bases=bases,
276
+ cls_name=cls.__name__,
277
+ )
278
+
279
+ if _typing_extra.is_classvar_annotation(ann_type):
280
+ class_vars.add(ann_name)
281
+ continue
282
+
283
+ assigned_value = getattr(cls, ann_name, PydanticUndefined)
284
+ if assigned_value is not PydanticUndefined and (
285
+ # One of the deprecated instance methods was used as a field name (e.g. `dict()`):
286
+ any(getattr(BaseModel_, depr_name, None) is assigned_value for depr_name in _deprecated_method_names)
287
+ # One of the deprecated class methods was used as a field name (e.g. `schema()`):
288
+ or (
289
+ hasattr(assigned_value, '__func__')
290
+ and any(
291
+ getattr(getattr(BaseModel_, depr_name, None), '__func__', None) is assigned_value.__func__ # pyright: ignore[reportAttributeAccessIssue]
292
+ for depr_name in _deprecated_classmethod_names
293
+ )
294
+ )
295
+ ):
296
+ # Then `assigned_value` would be the method, even though no default was specified:
297
+ assigned_value = PydanticUndefined
298
+
299
+ if not is_valid_field_name(ann_name):
300
+ continue
301
+ if cls.__pydantic_root_model__ and ann_name != 'root':
302
+ raise NameError(
303
+ f"Unexpected field with name {ann_name!r}; only 'root' is allowed as a field of a `RootModel`"
304
+ )
305
+
306
+ # when building a generic model with `MyModel[int]`, the generic_origin check makes sure we don't get
307
+ # "... shadows an attribute" warnings
308
+ generic_origin = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin')
309
+ for base in bases:
310
+ dataclass_fields = {
311
+ field.name for field in (dataclasses.fields(base) if dataclasses.is_dataclass(base) else ())
312
+ }
313
+ if hasattr(base, ann_name):
314
+ if base is generic_origin:
315
+ # Don't warn when "shadowing" of attributes in parametrized generics
316
+ continue
317
+
318
+ if ann_name in dataclass_fields:
319
+ # Don't warn when inheriting stdlib dataclasses whose fields are "shadowed" by defaults being set
320
+ # on the class instance.
321
+ continue
322
+
323
+ if ann_name not in annotations:
324
+ # Don't warn when a field exists in a parent class but has not been defined in the current class
325
+ continue
326
+
327
+ warnings.warn(
328
+ f'Field name "{ann_name}" in "{cls.__qualname__}" shadows an attribute in parent '
329
+ f'"{base.__qualname__}"',
330
+ UserWarning,
331
+ stacklevel=4,
332
+ )
333
+
334
+ if assigned_value is PydanticUndefined: # no assignment, just a plain annotation
335
+ if ann_name in annotations or ann_name not in parent_fields_lookup:
336
+ # field is either:
337
+ # - present in the current model's annotations (and *not* from parent classes)
338
+ # - not found on any base classes; this seems to be caused by fields bot getting
339
+ # generated due to models not being fully defined while initializing recursive models.
340
+ # Nothing stops us from just creating a `FieldInfo` for this type hint, so we do this.
341
+ field_info = FieldInfo_.from_annotation(ann_type, _source=AnnotationSource.CLASS)
342
+ if not evaluated:
343
+ field_info._complete = False
344
+ # Store the original annotation that should be used to rebuild
345
+ # the field info later:
346
+ field_info._original_annotation = ann_type
347
+ else:
348
+ # The field was present on one of the (possibly multiple) base classes
349
+ # copy the field to make sure typevar substitutions don't cause issues with the base classes
350
+ field_info = parent_fields_lookup[ann_name]._copy()
351
+
352
+ else: # An assigned value is present (either the default value, or a `Field()` function)
353
+ if isinstance(assigned_value, FieldInfo_) and ismethoddescriptor(assigned_value.default):
354
+ # `assigned_value` was fetched using `getattr`, which triggers a call to `__get__`
355
+ # for descriptors, so we do the same if the `= field(default=...)` form is used.
356
+ # Note that we only do this for method descriptors for now, we might want to
357
+ # extend this to any descriptor in the future (by simply checking for
358
+ # `hasattr(assigned_value.default, '__get__')`).
359
+ default = assigned_value.default.__get__(None, cls)
360
+ assigned_value.default = default
361
+ assigned_value._attributes_set['default'] = default
362
+
363
+ field_info = FieldInfo_.from_annotated_attribute(ann_type, assigned_value, _source=AnnotationSource.CLASS)
364
+ # Store the original annotation and assignment value that should be used to rebuild the field info later.
365
+ # Note that the assignment is always stored as the annotation might contain a type var that is later
366
+ # parameterized with an unknown forward reference (and we'll need it to rebuild the field info):
367
+ field_info._original_assignment = assigned_value
368
+ if not evaluated:
369
+ field_info._complete = False
370
+ field_info._original_annotation = ann_type
371
+ elif 'final' in field_info._qualifiers and not field_info.is_required():
372
+ warnings.warn(
373
+ f'Annotation {ann_name!r} is marked as final and has a default value. Pydantic treats {ann_name!r} as a '
374
+ 'class variable, but it will be considered as a normal field in V3 to be aligned with dataclasses. If you '
375
+ f'still want {ann_name!r} to be considered as a class variable, annotate it as: `ClassVar[<type>] = <default>.`',
376
+ category=PydanticDeprecatedSince211,
377
+ # Incorrect when `create_model` is used, but the chance that final with a default is used is low in that case:
378
+ stacklevel=4,
379
+ )
380
+ class_vars.add(ann_name)
381
+ continue
382
+
383
+ # attributes which are fields are removed from the class namespace:
384
+ # 1. To match the behaviour of annotation-only fields
385
+ # 2. To avoid false positives in the NameError check above
386
+ try:
387
+ delattr(cls, ann_name)
388
+ except AttributeError:
389
+ pass # indicates the attribute was on a parent class
390
+
391
+ # Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__
392
+ # to make sure the decorators have already been built for this exact class
393
+ decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__']
394
+ if ann_name in decorators.computed_fields:
395
+ raise TypeError(
396
+ f'Field {ann_name!r} of class {cls.__name__!r} overrides symbol of same name in a parent class. '
397
+ 'This override with a computed_field is incompatible.'
398
+ )
399
+ fields[ann_name] = field_info
400
+
401
+ if field_info._complete:
402
+ # If not complete, this will be called in `rebuild_model_fields()`:
403
+ update_field_from_config(config_wrapper, ann_name, field_info)
404
+
405
+ if typevars_map:
406
+ for field in fields.values():
407
+ if field._complete:
408
+ field.apply_typevars_map(typevars_map)
409
+
410
+ if config_wrapper.use_attribute_docstrings:
411
+ _update_fields_from_docstrings(cls, fields)
412
+ return fields, class_vars
413
+
414
+
415
+ def rebuild_model_fields(
416
+ cls: type[BaseModel],
417
+ *,
418
+ config_wrapper: ConfigWrapper,
419
+ ns_resolver: NsResolver,
420
+ typevars_map: Mapping[TypeVar, Any],
421
+ ) -> dict[str, FieldInfo]:
422
+ """Rebuild the (already present) model fields by trying to reevaluate annotations.
423
+
424
+ This function should be called whenever a model with incomplete fields is encountered.
425
+
426
+ Raises:
427
+ NameError: If one of the annotations failed to evaluate.
428
+
429
+ Note:
430
+ This function *doesn't* mutate the model fields in place, as it can be called during
431
+ schema generation, where you don't want to mutate other model's fields.
432
+ """
433
+ FieldInfo_ = import_cached_field_info()
434
+
435
+ rebuilt_fields: dict[str, FieldInfo] = {}
436
+ with ns_resolver.push(cls):
437
+ for f_name, field_info in cls.__pydantic_fields__.items():
438
+ if field_info._complete:
439
+ rebuilt_fields[f_name] = field_info
440
+ else:
441
+ existing_desc = field_info.description
442
+ ann = _typing_extra.eval_type(
443
+ field_info._original_annotation,
444
+ *ns_resolver.types_namespace,
445
+ )
446
+ ann = _generics.replace_types(ann, typevars_map)
447
+
448
+ if (assign := field_info._original_assignment) is PydanticUndefined:
449
+ new_field = FieldInfo_.from_annotation(ann, _source=AnnotationSource.CLASS)
450
+ else:
451
+ new_field = FieldInfo_.from_annotated_attribute(ann, assign, _source=AnnotationSource.CLASS)
452
+ # The description might come from the docstring if `use_attribute_docstrings` was `True`:
453
+ new_field.description = new_field.description if new_field.description is not None else existing_desc
454
+ update_field_from_config(config_wrapper, f_name, new_field)
455
+ rebuilt_fields[f_name] = new_field
456
+
457
+ return rebuilt_fields
458
+
459
+
460
+ def collect_dataclass_fields(
461
+ cls: type[StandardDataclass],
462
+ *,
463
+ config_wrapper: ConfigWrapper,
464
+ ns_resolver: NsResolver | None = None,
465
+ typevars_map: dict[Any, Any] | None = None,
466
+ ) -> dict[str, FieldInfo]:
467
+ """Collect the fields of a dataclass.
468
+
469
+ Args:
470
+ cls: dataclass.
471
+ config_wrapper: The config wrapper instance.
472
+ ns_resolver: Namespace resolver to use when getting dataclass annotations.
473
+ Defaults to an empty instance.
474
+ typevars_map: A dictionary mapping type variables to their concrete types.
475
+
476
+ Returns:
477
+ The dataclass fields.
478
+ """
479
+ FieldInfo_ = import_cached_field_info()
480
+
481
+ fields: dict[str, FieldInfo] = {}
482
+ ns_resolver = ns_resolver or NsResolver()
483
+ dataclass_fields = cls.__dataclass_fields__
484
+
485
+ # The logic here is similar to `_typing_extra.get_cls_type_hints`,
486
+ # although we do it manually as stdlib dataclasses already have annotations
487
+ # collected in each class:
488
+ for base in reversed(cls.__mro__):
489
+ if not dataclasses.is_dataclass(base):
490
+ continue
491
+
492
+ with ns_resolver.push(base):
493
+ for ann_name, dataclass_field in dataclass_fields.items():
494
+ base_anns = _typing_extra.safe_get_annotations(base)
495
+
496
+ if ann_name not in base_anns:
497
+ # `__dataclass_fields__`contains every field, even the ones from base classes.
498
+ # Only collect the ones defined on `base`.
499
+ continue
500
+
501
+ globalns, localns = ns_resolver.types_namespace
502
+ ann_type, evaluated = _typing_extra.try_eval_type(dataclass_field.type, globalns, localns)
503
+
504
+ if _typing_extra.is_classvar_annotation(ann_type):
505
+ continue
506
+
507
+ if (
508
+ not dataclass_field.init
509
+ and dataclass_field.default is dataclasses.MISSING
510
+ and dataclass_field.default_factory is dataclasses.MISSING
511
+ ):
512
+ # TODO: We should probably do something with this so that validate_assignment behaves properly
513
+ # Issue: https://github.com/pydantic/pydantic/issues/5470
514
+ continue
515
+
516
+ if isinstance(dataclass_field.default, FieldInfo_):
517
+ if dataclass_field.default.init_var:
518
+ if dataclass_field.default.init is False:
519
+ raise PydanticUserError(
520
+ f'Dataclass field {ann_name} has init=False and init_var=True, but these are mutually exclusive.',
521
+ code='clashing-init-and-init-var',
522
+ )
523
+
524
+ # TODO: same note as above re validate_assignment
525
+ continue
526
+ field_info = FieldInfo_.from_annotated_attribute(
527
+ ann_type, dataclass_field.default, _source=AnnotationSource.DATACLASS
528
+ )
529
+ field_info._original_assignment = dataclass_field.default
530
+ else:
531
+ field_info = FieldInfo_.from_annotated_attribute(
532
+ ann_type, dataclass_field, _source=AnnotationSource.DATACLASS
533
+ )
534
+ field_info._original_assignment = dataclass_field
535
+
536
+ if not evaluated:
537
+ field_info._complete = False
538
+ field_info._original_annotation = ann_type
539
+
540
+ fields[ann_name] = field_info
541
+ update_field_from_config(config_wrapper, ann_name, field_info)
542
+
543
+ if field_info.default is not PydanticUndefined and isinstance(
544
+ getattr(cls, ann_name, field_info), FieldInfo_
545
+ ):
546
+ # We need this to fix the default when the "default" from __dataclass_fields__ is a pydantic.FieldInfo
547
+ setattr(cls, ann_name, field_info.default)
548
+
549
+ if typevars_map:
550
+ for field in fields.values():
551
+ # We don't pass any ns, as `field.annotation`
552
+ # was already evaluated. TODO: is this method relevant?
553
+ # Can't we juste use `_generics.replace_types`?
554
+ field.apply_typevars_map(typevars_map)
555
+
556
+ if config_wrapper.use_attribute_docstrings:
557
+ _update_fields_from_docstrings(
558
+ cls,
559
+ fields,
560
+ # We can't rely on the (more reliable) frame inspection method
561
+ # for stdlib dataclasses:
562
+ use_inspect=not hasattr(cls, '__is_pydantic_dataclass__'),
563
+ )
564
+
565
+ return fields
566
+
567
+
568
+ def rebuild_dataclass_fields(
569
+ cls: type[PydanticDataclass],
570
+ *,
571
+ config_wrapper: ConfigWrapper,
572
+ ns_resolver: NsResolver,
573
+ typevars_map: Mapping[TypeVar, Any],
574
+ ) -> dict[str, FieldInfo]:
575
+ """Rebuild the (already present) dataclass fields by trying to reevaluate annotations.
576
+
577
+ This function should be called whenever a dataclass with incomplete fields is encountered.
578
+
579
+ Raises:
580
+ NameError: If one of the annotations failed to evaluate.
581
+
582
+ Note:
583
+ This function *doesn't* mutate the dataclass fields in place, as it can be called during
584
+ schema generation, where you don't want to mutate other dataclass's fields.
585
+ """
586
+ FieldInfo_ = import_cached_field_info()
587
+
588
+ rebuilt_fields: dict[str, FieldInfo] = {}
589
+ with ns_resolver.push(cls):
590
+ for f_name, field_info in cls.__pydantic_fields__.items():
591
+ if field_info._complete:
592
+ rebuilt_fields[f_name] = field_info
593
+ else:
594
+ existing_desc = field_info.description
595
+ ann = _typing_extra.eval_type(
596
+ field_info._original_annotation,
597
+ *ns_resolver.types_namespace,
598
+ )
599
+ ann = _generics.replace_types(ann, typevars_map)
600
+ new_field = FieldInfo_.from_annotated_attribute(
601
+ ann,
602
+ field_info._original_assignment,
603
+ _source=AnnotationSource.DATACLASS,
604
+ )
605
+
606
+ # The description might come from the docstring if `use_attribute_docstrings` was `True`:
607
+ new_field.description = new_field.description if new_field.description is not None else existing_desc
608
+ update_field_from_config(config_wrapper, f_name, new_field)
609
+ rebuilt_fields[f_name] = new_field
610
+
611
+ return rebuilt_fields
612
+
613
+
614
+ def is_valid_field_name(name: str) -> bool:
615
+ return not name.startswith('_')
616
+
617
+
618
+ def is_valid_privateattr_name(name: str) -> bool:
619
+ return name.startswith('_') and not name.startswith('__')
620
+
621
+
622
+ def takes_validated_data_argument(
623
+ default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any],
624
+ ) -> TypeIs[Callable[[dict[str, Any]], Any]]:
625
+ """Whether the provided default factory callable has a validated data parameter."""
626
+ try:
627
+ sig = signature(default_factory)
628
+ except (ValueError, TypeError):
629
+ # `inspect.signature` might not be able to infer a signature, e.g. with C objects.
630
+ # In this case, we assume no data argument is present:
631
+ return False
632
+
633
+ parameters = list(sig.parameters.values())
634
+
635
+ return len(parameters) == 1 and can_be_positional(parameters[0]) and parameters[0].default is Parameter.empty
data/miniconda3/envs/catiagent/lib/python3.11/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
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_generate_schema.py ADDED
The diff for this file is too large to render. See raw diff
 
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_generics.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: ContextVar[GenericTypesCache | None] = ContextVar('_GENERIC_TYPES_CACHE', default=None)
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 (Ex.: list | str) is represented with a types.UnionType object that does not have __getitem__.
311
+ # We also cannot use isinstance() since we have to compare types.
312
+ if sys.version_info >= (3, 10) and origin_type is types.UnionType:
313
+ return reduce(operator.or_, resolved_type_args)
314
+ # NotRequired[T] and Required[T] don't support tuple type resolved_type_args, hence the condition below
315
+ return origin_type[resolved_type_args[0] if len(resolved_type_args) == 1 else resolved_type_args]
316
+
317
+ # We handle pydantic generic models separately as they don't have the same
318
+ # semantics as "typing" classes or generic aliases
319
+
320
+ if not origin_type and is_model_class(type_):
321
+ parameters = type_.__pydantic_generic_metadata__['parameters']
322
+ if not parameters:
323
+ return type_
324
+ resolved_type_args = tuple(replace_types(t, type_map) for t in parameters)
325
+ if all_identical(parameters, resolved_type_args):
326
+ return type_
327
+ return type_[resolved_type_args]
328
+
329
+ # Handle special case for typehints that can have lists as arguments.
330
+ # `typing.Callable[[int, str], int]` is an example for this.
331
+ if isinstance(type_, list):
332
+ resolved_list = [replace_types(element, type_map) for element in type_]
333
+ if all_identical(type_, resolved_list):
334
+ return type_
335
+ return resolved_list
336
+
337
+ # If all else fails, we try to resolve the type directly and otherwise just
338
+ # return the input with no modifications.
339
+ return type_map.get(type_, type_)
340
+
341
+
342
+ def map_generic_model_arguments(cls: type[BaseModel], args: tuple[Any, ...]) -> dict[TypeVar, Any]:
343
+ """Return a mapping between the parameters of a generic model and the provided arguments during parameterization.
344
+
345
+ Raises:
346
+ TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments).
347
+
348
+ Example:
349
+ ```python {test="skip" lint="skip"}
350
+ class Model[T, U, V = int](BaseModel): ...
351
+
352
+ map_generic_model_arguments(Model, (str, bytes))
353
+ #> {T: str, U: bytes, V: int}
354
+
355
+ map_generic_model_arguments(Model, (str,))
356
+ #> TypeError: Too few arguments for <class '__main__.Model'>; actual 1, expected at least 2
357
+
358
+ map_generic_model_arguments(Model, (str, bytes, int, complex))
359
+ #> TypeError: Too many arguments for <class '__main__.Model'>; actual 4, expected 3
360
+ ```
361
+
362
+ Note:
363
+ This function is analogous to the private `typing._check_generic_specialization` function.
364
+ """
365
+ parameters = cls.__pydantic_generic_metadata__['parameters']
366
+ expected_len = len(parameters)
367
+ typevars_map: dict[TypeVar, Any] = {}
368
+
369
+ _missing = object()
370
+ for parameter, argument in zip_longest(parameters, args, fillvalue=_missing):
371
+ if parameter is _missing:
372
+ raise TypeError(f'Too many arguments for {cls}; actual {len(args)}, expected {expected_len}')
373
+
374
+ if argument is _missing:
375
+ param = cast(TypeVar, parameter)
376
+ try:
377
+ has_default = param.has_default() # pyright: ignore[reportAttributeAccessIssue]
378
+ except AttributeError:
379
+ # Happens if using `typing.TypeVar` (and not `typing_extensions`) on Python < 3.13.
380
+ has_default = False
381
+ if has_default:
382
+ # The default might refer to other type parameters. For an example, see:
383
+ # https://typing.python.org/en/latest/spec/generics.html#type-parameters-as-parameters-to-generics
384
+ typevars_map[param] = replace_types(param.__default__, typevars_map) # pyright: ignore[reportAttributeAccessIssue]
385
+ else:
386
+ expected_len -= sum(hasattr(p, 'has_default') and p.has_default() for p in parameters) # pyright: ignore[reportAttributeAccessIssue]
387
+ raise TypeError(f'Too few arguments for {cls}; actual {len(args)}, expected at least {expected_len}')
388
+ else:
389
+ param = cast(TypeVar, parameter)
390
+ typevars_map[param] = argument
391
+
392
+ return typevars_map
393
+
394
+
395
+ _generic_recursion_cache: ContextVar[set[str] | None] = ContextVar('_generic_recursion_cache', default=None)
396
+
397
+
398
+ @contextmanager
399
+ def generic_recursion_self_type(
400
+ origin: type[BaseModel], args: tuple[Any, ...]
401
+ ) -> Iterator[PydanticRecursiveRef | None]:
402
+ """This contextmanager should be placed around the recursive calls used to build a generic type,
403
+ and accept as arguments the generic origin type and the type arguments being passed to it.
404
+
405
+ If the same origin and arguments are observed twice, it implies that a self-reference placeholder
406
+ can be used while building the core schema, and will produce a schema_ref that will be valid in the
407
+ final parent schema.
408
+ """
409
+ previously_seen_type_refs = _generic_recursion_cache.get()
410
+ if previously_seen_type_refs is None:
411
+ previously_seen_type_refs = set()
412
+ token = _generic_recursion_cache.set(previously_seen_type_refs)
413
+ else:
414
+ token = None
415
+
416
+ try:
417
+ type_ref = get_type_ref(origin, args_override=args)
418
+ if type_ref in previously_seen_type_refs:
419
+ self_type = PydanticRecursiveRef(type_ref=type_ref)
420
+ yield self_type
421
+ else:
422
+ previously_seen_type_refs.add(type_ref)
423
+ yield
424
+ previously_seen_type_refs.remove(type_ref)
425
+ finally:
426
+ if token:
427
+ _generic_recursion_cache.reset(token)
428
+
429
+
430
+ def recursively_defined_type_refs() -> set[str]:
431
+ visited = _generic_recursion_cache.get()
432
+ if not visited:
433
+ return set() # not in a generic recursion, so there are no types
434
+
435
+ return visited.copy() # don't allow modifications
436
+
437
+
438
+ def get_cached_generic_type_early(parent: type[BaseModel], typevar_values: Any) -> type[BaseModel] | None:
439
+ """The use of a two-stage cache lookup approach was necessary to have the highest performance possible for
440
+ repeated calls to `__class_getitem__` on generic types (which may happen in tighter loops during runtime),
441
+ while still ensuring that certain alternative parametrizations ultimately resolve to the same type.
442
+
443
+ As a concrete example, this approach was necessary to make Model[List[T]][int] equal to Model[List[int]].
444
+ The approach could be modified to not use two different cache keys at different points, but the
445
+ _early_cache_key is optimized to be as quick to compute as possible (for repeated-access speed), and the
446
+ _late_cache_key is optimized to be as "correct" as possible, so that two types that will ultimately be the
447
+ same after resolving the type arguments will always produce cache hits.
448
+
449
+ If we wanted to move to only using a single cache key per type, we would either need to always use the
450
+ slower/more computationally intensive logic associated with _late_cache_key, or would need to accept
451
+ that Model[List[T]][int] is a different type than Model[List[T]][int]. Because we rely on subclass relationships
452
+ during validation, I think it is worthwhile to ensure that types that are functionally equivalent are actually
453
+ equal.
454
+ """
455
+ generic_types_cache = _GENERIC_TYPES_CACHE.get()
456
+ if generic_types_cache is None:
457
+ generic_types_cache = GenericTypesCache()
458
+ _GENERIC_TYPES_CACHE.set(generic_types_cache)
459
+ return generic_types_cache.get(_early_cache_key(parent, typevar_values))
460
+
461
+
462
+ def get_cached_generic_type_late(
463
+ parent: type[BaseModel], typevar_values: Any, origin: type[BaseModel], args: tuple[Any, ...]
464
+ ) -> type[BaseModel] | None:
465
+ """See the docstring of `get_cached_generic_type_early` for more information about the two-stage cache lookup."""
466
+ generic_types_cache = _GENERIC_TYPES_CACHE.get()
467
+ if (
468
+ generic_types_cache is None
469
+ ): # pragma: no cover (early cache is guaranteed to run first and initialize the cache)
470
+ generic_types_cache = GenericTypesCache()
471
+ _GENERIC_TYPES_CACHE.set(generic_types_cache)
472
+ cached = generic_types_cache.get(_late_cache_key(origin, args, typevar_values))
473
+ if cached is not None:
474
+ set_cached_generic_type(parent, typevar_values, cached, origin, args)
475
+ return cached
476
+
477
+
478
+ def set_cached_generic_type(
479
+ parent: type[BaseModel],
480
+ typevar_values: tuple[Any, ...],
481
+ type_: type[BaseModel],
482
+ origin: type[BaseModel] | None = None,
483
+ args: tuple[Any, ...] | None = None,
484
+ ) -> None:
485
+ """See the docstring of `get_cached_generic_type_early` for more information about why items are cached with
486
+ two different keys.
487
+ """
488
+ generic_types_cache = _GENERIC_TYPES_CACHE.get()
489
+ if (
490
+ generic_types_cache is None
491
+ ): # pragma: no cover (cache lookup is guaranteed to run first and initialize the cache)
492
+ generic_types_cache = GenericTypesCache()
493
+ _GENERIC_TYPES_CACHE.set(generic_types_cache)
494
+ generic_types_cache[_early_cache_key(parent, typevar_values)] = type_
495
+ if len(typevar_values) == 1:
496
+ generic_types_cache[_early_cache_key(parent, typevar_values[0])] = type_
497
+ if origin and args:
498
+ generic_types_cache[_late_cache_key(origin, args, typevar_values)] = type_
499
+
500
+
501
+ def _union_orderings_key(typevar_values: Any) -> Any:
502
+ """This is intended to help differentiate between Union types with the same arguments in different order.
503
+
504
+ Thanks to caching internal to the `typing` module, it is not possible to distinguish between
505
+ List[Union[int, float]] and List[Union[float, int]] (and similarly for other "parent" origins besides List)
506
+ because `typing` considers Union[int, float] to be equal to Union[float, int].
507
+
508
+ However, you _can_ distinguish between (top-level) Union[int, float] vs. Union[float, int].
509
+ Because we parse items as the first Union type that is successful, we get slightly more consistent behavior
510
+ if we make an effort to distinguish the ordering of items in a union. It would be best if we could _always_
511
+ get the exact-correct order of items in the union, but that would require a change to the `typing` module itself.
512
+ (See https://github.com/python/cpython/issues/86483 for reference.)
513
+ """
514
+ if isinstance(typevar_values, tuple):
515
+ return tuple(_union_orderings_key(value) for value in typevar_values)
516
+ elif typing_objects.is_union(typing_extensions.get_origin(typevar_values)):
517
+ return get_args(typevar_values)
518
+ else:
519
+ return ()
520
+
521
+
522
+ def _early_cache_key(cls: type[BaseModel], typevar_values: Any) -> GenericTypesCacheKey:
523
+ """This is intended for minimal computational overhead during lookups of cached types.
524
+
525
+ Note that this is overly simplistic, and it's possible that two different cls/typevar_values
526
+ inputs would ultimately result in the same type being created in BaseModel.__class_getitem__.
527
+ To handle this, we have a fallback _late_cache_key that is checked later if the _early_cache_key
528
+ lookup fails, and should result in a cache hit _precisely_ when the inputs to __class_getitem__
529
+ would result in the same type.
530
+ """
531
+ return cls, typevar_values, _union_orderings_key(typevar_values)
532
+
533
+
534
+ def _late_cache_key(origin: type[BaseModel], args: tuple[Any, ...], typevar_values: Any) -> GenericTypesCacheKey:
535
+ """This is intended for use later in the process of creating a new type, when we have more information
536
+ about the exact args that will be passed. If it turns out that a different set of inputs to
537
+ __class_getitem__ resulted in the same inputs to the generic type creation process, we can still
538
+ return the cached type, and update the cache with the _early_cache_key as well.
539
+ """
540
+ # The _union_orderings_key is placed at the start here to ensure there cannot be a collision with an
541
+ # _early_cache_key, as that function will always produce a BaseModel subclass as the first item in the key,
542
+ # whereas this function will always produce a tuple as the first item in the key.
543
+ return _union_orderings_key(typevar_values), origin, args
data/miniconda3/envs/catiagent/lib/python3.11/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()
data/miniconda3/envs/catiagent/lib/python3.11/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
data/miniconda3/envs/catiagent/lib/python3.11/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 = {}
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_known_annotated_metadata.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
34
+ BYTES_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
35
+
36
+ LIST_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
37
+ TUPLE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
38
+ SET_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST}
39
+ DICT_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
40
+ GENERATOR_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT}
41
+ SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST}
42
+
43
+ FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
44
+ DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS}
45
+ INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT}
46
+ BOOL_CONSTRAINTS = STRICT
47
+ UUID_CONSTRAINTS = STRICT
48
+
49
+ DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
50
+ TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
51
+ TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}
52
+ LAX_OR_STRICT_CONSTRAINTS = STRICT
53
+ ENUM_CONSTRAINTS = STRICT
54
+ COMPLEX_CONSTRAINTS = STRICT
55
+
56
+ UNION_CONSTRAINTS = {'union_mode'}
57
+ URL_CONSTRAINTS = {
58
+ 'max_length',
59
+ 'allowed_schemes',
60
+ 'host_required',
61
+ 'default_host',
62
+ 'default_port',
63
+ 'default_path',
64
+ }
65
+
66
+ TEXT_SCHEMA_TYPES = ('str', 'bytes', 'url', 'multi-host-url')
67
+ SEQUENCE_SCHEMA_TYPES = ('list', 'tuple', 'set', 'frozenset', 'generator', *TEXT_SCHEMA_TYPES)
68
+ NUMERIC_SCHEMA_TYPES = ('float', 'int', 'date', 'time', 'timedelta', 'datetime')
69
+
70
+ CONSTRAINTS_TO_ALLOWED_SCHEMAS: dict[str, set[str]] = defaultdict(set)
71
+
72
+ constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [
73
+ (STR_CONSTRAINTS, TEXT_SCHEMA_TYPES),
74
+ (BYTES_CONSTRAINTS, ('bytes',)),
75
+ (LIST_CONSTRAINTS, ('list',)),
76
+ (TUPLE_CONSTRAINTS, ('tuple',)),
77
+ (SET_CONSTRAINTS, ('set', 'frozenset')),
78
+ (DICT_CONSTRAINTS, ('dict',)),
79
+ (GENERATOR_CONSTRAINTS, ('generator',)),
80
+ (FLOAT_CONSTRAINTS, ('float',)),
81
+ (INT_CONSTRAINTS, ('int',)),
82
+ (DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime', 'timedelta')),
83
+ # TODO: this is a bit redundant, we could probably avoid some of these
84
+ (STRICT, (*TEXT_SCHEMA_TYPES, *SEQUENCE_SCHEMA_TYPES, *NUMERIC_SCHEMA_TYPES, 'typed-dict', 'model')),
85
+ (UNION_CONSTRAINTS, ('union',)),
86
+ (URL_CONSTRAINTS, ('url', 'multi-host-url')),
87
+ (BOOL_CONSTRAINTS, ('bool',)),
88
+ (UUID_CONSTRAINTS, ('uuid',)),
89
+ (LAX_OR_STRICT_CONSTRAINTS, ('lax-or-strict',)),
90
+ (ENUM_CONSTRAINTS, ('enum',)),
91
+ (DECIMAL_CONSTRAINTS, ('decimal',)),
92
+ (COMPLEX_CONSTRAINTS, ('complex',)),
93
+ ]
94
+
95
+ for constraints, schemas in constraint_schema_pairings:
96
+ for c in constraints:
97
+ CONSTRAINTS_TO_ALLOWED_SCHEMAS[c].update(schemas)
98
+
99
+
100
+ def as_jsonable_value(v: Any) -> Any:
101
+ if type(v) not in (int, str, float, bytes, bool, type(None)):
102
+ return to_jsonable_python(v)
103
+ return v
104
+
105
+
106
+ def expand_grouped_metadata(annotations: Iterable[Any]) -> Iterable[Any]:
107
+ """Expand the annotations.
108
+
109
+ Args:
110
+ annotations: An iterable of annotations.
111
+
112
+ Returns:
113
+ An iterable of expanded annotations.
114
+
115
+ Example:
116
+ ```python
117
+ from annotated_types import Ge, Len
118
+
119
+ from pydantic._internal._known_annotated_metadata import expand_grouped_metadata
120
+
121
+ print(list(expand_grouped_metadata([Ge(4), Len(5)])))
122
+ #> [Ge(ge=4), MinLen(min_length=5)]
123
+ ```
124
+ """
125
+ import annotated_types as at
126
+
127
+ FieldInfo = import_cached_field_info()
128
+
129
+ for annotation in annotations:
130
+ if isinstance(annotation, at.GroupedMetadata):
131
+ yield from annotation
132
+ elif isinstance(annotation, FieldInfo):
133
+ yield from annotation.metadata
134
+ # this is a bit problematic in that it results in duplicate metadata
135
+ # all of our "consumers" can handle it, but it is not ideal
136
+ # we probably should split up FieldInfo into:
137
+ # - annotated types metadata
138
+ # - individual metadata known only to Pydantic
139
+ annotation = copy(annotation)
140
+ annotation.metadata = []
141
+ yield annotation
142
+ else:
143
+ yield annotation
144
+
145
+
146
+ @lru_cache
147
+ def _get_at_to_constraint_map() -> dict[type, str]:
148
+ """Return a mapping of annotated types to constraints.
149
+
150
+ Normally, we would define a mapping like this in the module scope, but we can't do that
151
+ because we don't permit module level imports of `annotated_types`, in an attempt to speed up
152
+ the import time of `pydantic`. We still only want to have this dictionary defined in one place,
153
+ so we use this function to cache the result.
154
+ """
155
+ import annotated_types as at
156
+
157
+ return {
158
+ at.Gt: 'gt',
159
+ at.Ge: 'ge',
160
+ at.Lt: 'lt',
161
+ at.Le: 'le',
162
+ at.MultipleOf: 'multiple_of',
163
+ at.MinLen: 'min_length',
164
+ at.MaxLen: 'max_length',
165
+ }
166
+
167
+
168
+ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | None: # noqa: C901
169
+ """Apply `annotation` to `schema` if it is an annotation we know about (Gt, Le, etc.).
170
+ Otherwise return `None`.
171
+
172
+ This does not handle all known annotations. If / when it does, it can always
173
+ return a CoreSchema and return the unmodified schema if the annotation should be ignored.
174
+
175
+ Assumes that GroupedMetadata has already been expanded via `expand_grouped_metadata`.
176
+
177
+ Args:
178
+ annotation: The annotation.
179
+ schema: The schema.
180
+
181
+ Returns:
182
+ An updated schema with annotation if it is an annotation we know about, `None` otherwise.
183
+
184
+ Raises:
185
+ RuntimeError: If a constraint can't be applied to a specific schema type.
186
+ ValueError: If an unknown constraint is encountered.
187
+ """
188
+ import annotated_types as at
189
+
190
+ from ._validators import NUMERIC_VALIDATOR_LOOKUP, forbid_inf_nan_check
191
+
192
+ schema = schema.copy()
193
+ schema_update, other_metadata = collect_known_metadata([annotation])
194
+ schema_type = schema['type']
195
+
196
+ chain_schema_constraints: set[str] = {
197
+ 'pattern',
198
+ 'strip_whitespace',
199
+ 'to_lower',
200
+ 'to_upper',
201
+ 'coerce_numbers_to_str',
202
+ }
203
+ chain_schema_steps: list[CoreSchema] = []
204
+
205
+ for constraint, value in schema_update.items():
206
+ if constraint not in CONSTRAINTS_TO_ALLOWED_SCHEMAS:
207
+ raise ValueError(f'Unknown constraint {constraint}')
208
+ allowed_schemas = CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint]
209
+
210
+ # if it becomes necessary to handle more than one constraint
211
+ # in this recursive case with function-after or function-wrap, we should refactor
212
+ # this is a bit challenging because we sometimes want to apply constraints to the inner schema,
213
+ # whereas other times we want to wrap the existing schema with a new one that enforces a new constraint.
214
+ if schema_type in {'function-before', 'function-wrap', 'function-after'} and constraint == 'strict':
215
+ schema['schema'] = apply_known_metadata(annotation, schema['schema']) # type: ignore # schema is function schema
216
+ return schema
217
+
218
+ # if we're allowed to apply constraint directly to the schema, like le to int, do that
219
+ if schema_type in allowed_schemas:
220
+ if constraint == 'union_mode' and schema_type == 'union':
221
+ schema['mode'] = value # type: ignore # schema is UnionSchema
222
+ else:
223
+ schema[constraint] = value
224
+ continue
225
+
226
+ # else, apply a function after validator to the schema to enforce the corresponding constraint
227
+ if constraint in chain_schema_constraints:
228
+
229
+ def _apply_constraint_with_incompatibility_info(
230
+ value: Any, handler: cs.ValidatorFunctionWrapHandler
231
+ ) -> Any:
232
+ try:
233
+ x = handler(value)
234
+ except ValidationError as ve:
235
+ # if the error is about the type, it's likely that the constraint is incompatible the type of the field
236
+ # for example, the following invalid schema wouldn't be caught during schema build, but rather at this point
237
+ # with a cryptic 'string_type' error coming from the string validator,
238
+ # that we'd rather express as a constraint incompatibility error (TypeError)
239
+ # Annotated[list[int], Field(pattern='abc')]
240
+ if 'type' in ve.errors()[0]['type']:
241
+ raise TypeError(
242
+ f"Unable to apply constraint '{constraint}' to supplied value {value} for schema of type '{schema_type}'" # noqa: B023
243
+ )
244
+ raise ve
245
+ return x
246
+
247
+ chain_schema_steps.append(
248
+ cs.no_info_wrap_validator_function(
249
+ _apply_constraint_with_incompatibility_info, cs.str_schema(**{constraint: value})
250
+ )
251
+ )
252
+ elif constraint in NUMERIC_VALIDATOR_LOOKUP:
253
+ if constraint in LENGTH_CONSTRAINTS:
254
+ inner_schema = schema
255
+ while inner_schema['type'] in {'function-before', 'function-wrap', 'function-after'}:
256
+ inner_schema = inner_schema['schema'] # type: ignore
257
+ inner_schema_type = inner_schema['type']
258
+ if inner_schema_type == 'list' or (
259
+ inner_schema_type == 'json-or-python' and inner_schema['json_schema']['type'] == 'list' # type: ignore
260
+ ):
261
+ js_constraint_key = 'minItems' if constraint == 'min_length' else 'maxItems'
262
+ else:
263
+ js_constraint_key = 'minLength' if constraint == 'min_length' else 'maxLength'
264
+ else:
265
+ js_constraint_key = constraint
266
+
267
+ schema = cs.no_info_after_validator_function(
268
+ partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schema
269
+ )
270
+ metadata = schema.get('metadata', {})
271
+ if (existing_json_schema_updates := metadata.get('pydantic_js_updates')) is not None:
272
+ metadata['pydantic_js_updates'] = {
273
+ **existing_json_schema_updates,
274
+ **{js_constraint_key: as_jsonable_value(value)},
275
+ }
276
+ else:
277
+ metadata['pydantic_js_updates'] = {js_constraint_key: as_jsonable_value(value)}
278
+ schema['metadata'] = metadata
279
+ elif constraint == 'allow_inf_nan' and value is False:
280
+ schema = cs.no_info_after_validator_function(
281
+ forbid_inf_nan_check,
282
+ schema,
283
+ )
284
+ else:
285
+ # It's rare that we'd get here, but it's possible if we add a new constraint and forget to handle it
286
+ # Most constraint errors are caught at runtime during attempted application
287
+ raise RuntimeError(f"Unable to apply constraint '{constraint}' to schema of type '{schema_type}'")
288
+
289
+ for annotation in other_metadata:
290
+ if (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
291
+ constraint = at_to_constraint_map[annotation_type]
292
+ validator = NUMERIC_VALIDATOR_LOOKUP.get(constraint)
293
+ if validator is None:
294
+ raise ValueError(f'Unknown constraint {constraint}')
295
+ schema = cs.no_info_after_validator_function(
296
+ partial(validator, {constraint: getattr(annotation, constraint)}), schema
297
+ )
298
+ continue
299
+ elif isinstance(annotation, (at.Predicate, at.Not)):
300
+ predicate_name = f'{annotation.func.__qualname__!r} ' if hasattr(annotation.func, '__qualname__') else ''
301
+
302
+ # Note: B023 is ignored because even though we iterate over `other_metadata`, it is guaranteed
303
+ # to be of length 1. `apply_known_metadata()` is called from `GenerateSchema`, where annotations
304
+ # were already expanded via `expand_grouped_metadata()`. Confusing, but this falls into the annotations
305
+ # refactor.
306
+ if isinstance(annotation, at.Predicate):
307
+
308
+ def val_func(v: Any) -> Any:
309
+ predicate_satisfied = annotation.func(v) # noqa: B023
310
+ if not predicate_satisfied:
311
+ raise PydanticCustomError(
312
+ 'predicate_failed',
313
+ f'Predicate {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
314
+ )
315
+ return v
316
+
317
+ else:
318
+
319
+ def val_func(v: Any) -> Any:
320
+ predicate_satisfied = annotation.func(v) # noqa: B023
321
+ if predicate_satisfied:
322
+ raise PydanticCustomError(
323
+ 'not_operation_failed',
324
+ f'Not of {predicate_name}failed', # pyright: ignore[reportArgumentType] # noqa: B023
325
+ )
326
+ return v
327
+
328
+ schema = cs.no_info_after_validator_function(val_func, schema)
329
+ else:
330
+ # ignore any other unknown metadata
331
+ return None
332
+
333
+ if chain_schema_steps:
334
+ chain_schema_steps = [schema] + chain_schema_steps
335
+ return cs.chain_schema(chain_schema_steps)
336
+
337
+ return schema
338
+
339
+
340
+ def collect_known_metadata(annotations: Iterable[Any]) -> tuple[dict[str, Any], list[Any]]:
341
+ """Split `annotations` into known metadata and unknown annotations.
342
+
343
+ Args:
344
+ annotations: An iterable of annotations.
345
+
346
+ Returns:
347
+ A tuple contains a dict of known metadata and a list of unknown annotations.
348
+
349
+ Example:
350
+ ```python
351
+ from annotated_types import Gt, Len
352
+
353
+ from pydantic._internal._known_annotated_metadata import collect_known_metadata
354
+
355
+ print(collect_known_metadata([Gt(1), Len(42), ...]))
356
+ #> ({'gt': 1, 'min_length': 42}, [Ellipsis])
357
+ ```
358
+ """
359
+ annotations = expand_grouped_metadata(annotations)
360
+
361
+ res: dict[str, Any] = {}
362
+ remaining: list[Any] = []
363
+
364
+ for annotation in annotations:
365
+ # isinstance(annotation, PydanticMetadata) also covers ._fields:_PydanticGeneralMetadata
366
+ if isinstance(annotation, PydanticMetadata):
367
+ res.update(annotation.__dict__)
368
+ # we don't use dataclasses.asdict because that recursively calls asdict on the field values
369
+ elif (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()):
370
+ constraint = at_to_constraint_map[annotation_type]
371
+ res[constraint] = getattr(annotation, constraint)
372
+ elif isinstance(annotation, type) and issubclass(annotation, PydanticMetadata):
373
+ # also support PydanticMetadata classes being used without initialisation,
374
+ # e.g. `Annotated[int, Strict]` as well as `Annotated[int, Strict()]`
375
+ res.update({k: v for k, v in vars(annotation).items() if not k.startswith('_')})
376
+ else:
377
+ remaining.append(annotation)
378
+ # Nones can sneak in but pydantic-core will reject them
379
+ # 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)
380
+ # but this is simple enough to kick that can down the road
381
+ res = {k: v for k, v in res.items() if v is not None}
382
+ return res, remaining
383
+
384
+
385
+ def check_metadata(metadata: dict[str, Any], allowed: Iterable[str], source_type: Any) -> None:
386
+ """A small utility function to validate that the given metadata can be applied to the target.
387
+ More than saving lines of code, this gives us a consistent error message for all of our internal implementations.
388
+
389
+ Args:
390
+ metadata: A dict of metadata.
391
+ allowed: An iterable of allowed metadata.
392
+ source_type: The source type.
393
+
394
+ Raises:
395
+ TypeError: If there is metadatas that can't be applied on source type.
396
+ """
397
+ unknown = metadata.keys() - set(allowed)
398
+ if unknown:
399
+ raise TypeError(
400
+ f'The following constraints cannot be applied to {source_type!r}: {", ".join([f"{k!r}" for k in unknown])}'
401
+ )
data/miniconda3/envs/catiagent/lib/python3.11/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
+ )
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/pydantic/_internal/_model_construction.py ADDED
@@ -0,0 +1,848 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ else:
45
+ PydanticModelField = object()
46
+ PydanticModelPrivateAttr = object()
47
+
48
+ object_setattr = object.__setattr__
49
+
50
+
51
+ class _ModelNamespaceDict(dict):
52
+ """A dictionary subclass that intercepts attribute setting on model classes and
53
+ warns about overriding of decorators.
54
+ """
55
+
56
+ def __setitem__(self, k: str, v: object) -> None:
57
+ existing: Any = self.get(k, None)
58
+ if existing and v is not existing and isinstance(existing, PydanticDescriptorProxy):
59
+ warnings.warn(
60
+ f'`{k}` overrides an existing Pydantic `{existing.decorator_info.decorator_repr}` decorator',
61
+ stacklevel=2,
62
+ )
63
+
64
+ return super().__setitem__(k, v)
65
+
66
+
67
+ def NoInitField(
68
+ *,
69
+ init: Literal[False] = False,
70
+ ) -> Any:
71
+ """Only for typing purposes. Used as default value of `__pydantic_fields_set__`,
72
+ `__pydantic_extra__`, `__pydantic_private__`, so they could be ignored when
73
+ synthesizing the `__init__` signature.
74
+ """
75
+
76
+
77
+ # For ModelMetaclass.register():
78
+ _T = TypeVar('_T')
79
+
80
+
81
+ @dataclass_transform(kw_only_default=True, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr, NoInitField))
82
+ class ModelMetaclass(ABCMeta):
83
+ def __new__(
84
+ mcs,
85
+ cls_name: str,
86
+ bases: tuple[type[Any], ...],
87
+ namespace: dict[str, Any],
88
+ __pydantic_generic_metadata__: PydanticGenericMetadata | None = None,
89
+ __pydantic_reset_parent_namespace__: bool = True,
90
+ _create_model_module: str | None = None,
91
+ **kwargs: Any,
92
+ ) -> type:
93
+ """Metaclass for creating Pydantic models.
94
+
95
+ Args:
96
+ cls_name: The name of the class to be created.
97
+ bases: The base classes of the class to be created.
98
+ namespace: The attribute dictionary of the class to be created.
99
+ __pydantic_generic_metadata__: Metadata for generic models.
100
+ __pydantic_reset_parent_namespace__: Reset parent namespace.
101
+ _create_model_module: The module of the class to be created, if created by `create_model`.
102
+ **kwargs: Catch-all for any other keyword arguments.
103
+
104
+ Returns:
105
+ The new class created by the metaclass.
106
+ """
107
+ # Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we rely on the fact
108
+ # that `BaseModel` itself won't have any bases, but any subclass of it will, to determine whether the `__new__`
109
+ # call we're in the middle of is for the `BaseModel` class.
110
+ if bases:
111
+ raw_annotations: dict[str, Any]
112
+ if sys.version_info >= (3, 14):
113
+ if (
114
+ '__annotations__' in namespace
115
+ ): # `from __future__ import annotations` was used in the model's module
116
+ raw_annotations = namespace['__annotations__']
117
+ else:
118
+ # See https://docs.python.org/3.14/library/annotationlib.html#using-annotations-in-a-metaclass:
119
+ from annotationlib import Format, call_annotate_function, get_annotate_from_class_namespace
120
+
121
+ if annotate := get_annotate_from_class_namespace(namespace):
122
+ raw_annotations = call_annotate_function(annotate, format=Format.FORWARDREF)
123
+ else:
124
+ raw_annotations = {}
125
+ else:
126
+ raw_annotations = namespace.get('__annotations__', {})
127
+
128
+ base_field_names, class_vars, base_private_attributes = mcs._collect_bases_data(bases)
129
+
130
+ config_wrapper = ConfigWrapper.for_model(bases, namespace, raw_annotations, kwargs)
131
+ namespace['model_config'] = config_wrapper.config_dict
132
+ private_attributes = inspect_namespace(
133
+ namespace, raw_annotations, config_wrapper.ignored_types, class_vars, base_field_names
134
+ )
135
+ if private_attributes or base_private_attributes:
136
+ original_model_post_init = get_model_post_init(namespace, bases)
137
+ if original_model_post_init is not None:
138
+ # if there are private_attributes and a model_post_init function, we handle both
139
+
140
+ @wraps(original_model_post_init)
141
+ def wrapped_model_post_init(self: BaseModel, context: Any, /) -> None:
142
+ """We need to both initialize private attributes and call the user-defined model_post_init
143
+ method.
144
+ """
145
+ init_private_attributes(self, context)
146
+ original_model_post_init(self, context)
147
+
148
+ namespace['model_post_init'] = wrapped_model_post_init
149
+ else:
150
+ namespace['model_post_init'] = init_private_attributes
151
+
152
+ namespace['__class_vars__'] = class_vars
153
+ namespace['__private_attributes__'] = {**base_private_attributes, **private_attributes}
154
+
155
+ cls = cast('type[BaseModel]', super().__new__(mcs, cls_name, bases, namespace, **kwargs))
156
+ BaseModel_ = import_cached_base_model()
157
+
158
+ mro = cls.__mro__
159
+ if Generic in mro and mro.index(Generic) < mro.index(BaseModel_):
160
+ warnings.warn(
161
+ GenericBeforeBaseModelWarning(
162
+ 'Classes should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) '
163
+ 'for pydantic generics to work properly.'
164
+ ),
165
+ stacklevel=2,
166
+ )
167
+
168
+ cls.__pydantic_custom_init__ = not getattr(cls.__init__, '__pydantic_base_init__', False)
169
+ cls.__pydantic_post_init__ = (
170
+ None if cls.model_post_init is BaseModel_.model_post_init else 'model_post_init'
171
+ )
172
+
173
+ cls.__pydantic_setattr_handlers__ = {}
174
+
175
+ cls.__pydantic_decorators__ = DecoratorInfos.build(cls)
176
+ cls.__pydantic_decorators__.update_from_config(config_wrapper)
177
+
178
+ # Use the getattr below to grab the __parameters__ from the `typing.Generic` parent class
179
+ if __pydantic_generic_metadata__:
180
+ cls.__pydantic_generic_metadata__ = __pydantic_generic_metadata__
181
+ else:
182
+ parent_parameters = getattr(cls, '__pydantic_generic_metadata__', {}).get('parameters', ())
183
+ parameters = getattr(cls, '__parameters__', None) or parent_parameters
184
+ if parameters and parent_parameters and not all(x in parameters for x in parent_parameters):
185
+ from ..root_model import RootModelRootType
186
+
187
+ missing_parameters = tuple(x for x in parameters if x not in parent_parameters)
188
+ if RootModelRootType in parent_parameters and RootModelRootType not in parameters:
189
+ # This is a special case where the user has subclassed `RootModel`, but has not parametrized
190
+ # RootModel with the generic type identifiers being used. Ex:
191
+ # class MyModel(RootModel, Generic[T]):
192
+ # root: T
193
+ # Should instead just be:
194
+ # class MyModel(RootModel[T]):
195
+ # root: T
196
+ parameters_str = ', '.join([x.__name__ for x in missing_parameters])
197
+ error_message = (
198
+ f'{cls.__name__} is a subclass of `RootModel`, but does not include the generic type identifier(s) '
199
+ f'{parameters_str} in its parameters. '
200
+ f'You should parametrize RootModel directly, e.g., `class {cls.__name__}(RootModel[{parameters_str}]): ...`.'
201
+ )
202
+ else:
203
+ combined_parameters = parent_parameters + missing_parameters
204
+ parameters_str = ', '.join([str(x) for x in combined_parameters])
205
+ generic_type_label = f'typing.Generic[{parameters_str}]'
206
+ error_message = (
207
+ f'All parameters must be present on typing.Generic;'
208
+ f' you should inherit from {generic_type_label}.'
209
+ )
210
+ if Generic not in bases: # pragma: no cover
211
+ # We raise an error here not because it is desirable, but because some cases are mishandled.
212
+ # It would be nice to remove this error and still have things behave as expected, it's just
213
+ # challenging because we are using a custom `__class_getitem__` to parametrize generic models,
214
+ # and not returning a typing._GenericAlias from it.
215
+ bases_str = ', '.join([x.__name__ for x in bases] + [generic_type_label])
216
+ error_message += (
217
+ f' Note: `typing.Generic` must go last: `class {cls.__name__}({bases_str}): ...`)'
218
+ )
219
+ raise TypeError(error_message)
220
+
221
+ cls.__pydantic_generic_metadata__ = {
222
+ 'origin': None,
223
+ 'args': (),
224
+ 'parameters': parameters,
225
+ }
226
+
227
+ cls.__pydantic_complete__ = False # Ensure this specific class gets completed
228
+
229
+ # preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487
230
+ # for attributes not in `new_namespace` (e.g. private attributes)
231
+ for name, obj in private_attributes.items():
232
+ obj.__set_name__(cls, name)
233
+
234
+ if __pydantic_reset_parent_namespace__:
235
+ cls.__pydantic_parent_namespace__ = build_lenient_weakvaluedict(parent_frame_namespace())
236
+ parent_namespace: dict[str, Any] | None = getattr(cls, '__pydantic_parent_namespace__', None)
237
+ if isinstance(parent_namespace, dict):
238
+ parent_namespace = unpack_lenient_weakvaluedict(parent_namespace)
239
+
240
+ ns_resolver = NsResolver(parent_namespace=parent_namespace)
241
+
242
+ set_model_fields(cls, config_wrapper=config_wrapper, ns_resolver=ns_resolver)
243
+
244
+ # This is also set in `complete_model_class()`, after schema gen because they are recreated.
245
+ # We set them here as well for backwards compatibility:
246
+ cls.__pydantic_computed_fields__ = {
247
+ k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()
248
+ }
249
+
250
+ if config_wrapper.defer_build:
251
+ set_model_mocks(cls)
252
+ else:
253
+ # Any operation that requires accessing the field infos instances should be put inside
254
+ # `complete_model_class()`:
255
+ complete_model_class(
256
+ cls,
257
+ config_wrapper,
258
+ ns_resolver,
259
+ raise_errors=False,
260
+ create_model_module=_create_model_module,
261
+ )
262
+
263
+ if config_wrapper.frozen and '__hash__' not in namespace:
264
+ set_default_hash_func(cls, bases)
265
+
266
+ # using super(cls, cls) on the next line ensures we only call the parent class's __pydantic_init_subclass__
267
+ # I believe the `type: ignore` is only necessary because mypy doesn't realize that this code branch is
268
+ # only hit for _proper_ subclasses of BaseModel
269
+ super(cls, cls).__pydantic_init_subclass__(**kwargs) # type: ignore[misc]
270
+ return cls
271
+ else:
272
+ # These are instance variables, but have been assigned to `NoInitField` to trick the type checker.
273
+ for instance_slot in '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__':
274
+ namespace.pop(
275
+ instance_slot,
276
+ None, # In case the metaclass is used with a class other than `BaseModel`.
277
+ )
278
+ namespace.get('__annotations__', {}).clear()
279
+ return super().__new__(mcs, cls_name, bases, namespace, **kwargs)
280
+
281
+ if not TYPE_CHECKING: # pragma: no branch
282
+ # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
283
+
284
+ def __getattr__(self, item: str) -> Any:
285
+ """This is necessary to keep attribute access working for class attribute access."""
286
+ private_attributes = self.__dict__.get('__private_attributes__')
287
+ if private_attributes and item in private_attributes:
288
+ return private_attributes[item]
289
+ raise AttributeError(item)
290
+
291
+ @classmethod
292
+ def __prepare__(cls, *args: Any, **kwargs: Any) -> dict[str, object]:
293
+ return _ModelNamespaceDict()
294
+
295
+ # Due to performance and memory issues, in the ABCMeta.__subclasscheck__ implementation, we don't support
296
+ # registered virtual subclasses. See https://github.com/python/cpython/issues/92810#issuecomment-2762454345.
297
+ # This may change once the CPython gets fixed (possibly in 3.15), in which case we should conditionally
298
+ # define `register()`.
299
+ def register(self, subclass: type[_T]) -> type[_T]:
300
+ warnings.warn(
301
+ f"For performance reasons, virtual subclasses registered using '{self.__qualname__}.register()' "
302
+ "are not supported in 'isinstance()' and 'issubclass()' checks.",
303
+ stacklevel=2,
304
+ )
305
+ return super().register(subclass)
306
+
307
+ __instancecheck__ = type.__instancecheck__ # pyright: ignore[reportAssignmentType]
308
+ __subclasscheck__ = type.__subclasscheck__ # pyright: ignore[reportAssignmentType]
309
+
310
+ @staticmethod
311
+ def _collect_bases_data(bases: tuple[type[Any], ...]) -> tuple[set[str], set[str], dict[str, ModelPrivateAttr]]:
312
+ BaseModel = import_cached_base_model()
313
+
314
+ field_names: set[str] = set()
315
+ class_vars: set[str] = set()
316
+ private_attributes: dict[str, ModelPrivateAttr] = {}
317
+ for base in bases:
318
+ if issubclass(base, BaseModel) and base is not BaseModel:
319
+ # model_fields might not be defined yet in the case of generics, so we use getattr here:
320
+ field_names.update(getattr(base, '__pydantic_fields__', {}).keys())
321
+ class_vars.update(base.__class_vars__)
322
+ private_attributes.update(base.__private_attributes__)
323
+ return field_names, class_vars, private_attributes
324
+
325
+ @property
326
+ @deprecated(
327
+ 'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.', category=None
328
+ )
329
+ def __fields__(self) -> dict[str, FieldInfo]:
330
+ warnings.warn(
331
+ 'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.',
332
+ PydanticDeprecatedSince20,
333
+ stacklevel=2,
334
+ )
335
+ return getattr(self, '__pydantic_fields__', {})
336
+
337
+ @property
338
+ def __pydantic_fields_complete__(self) -> bool:
339
+ """Whether the fields where successfully collected (i.e. type hints were successfully resolves).
340
+
341
+ This is a private attribute, not meant to be used outside Pydantic.
342
+ """
343
+ if '__pydantic_fields__' not in self.__dict__:
344
+ return False
345
+
346
+ field_infos = cast('dict[str, FieldInfo]', self.__pydantic_fields__) # pyright: ignore[reportAttributeAccessIssue]
347
+
348
+ return all(field_info._complete for field_info in field_infos.values())
349
+
350
+ def __dir__(self) -> list[str]:
351
+ attributes = list(super().__dir__())
352
+ if '__fields__' in attributes:
353
+ attributes.remove('__fields__')
354
+ return attributes
355
+
356
+
357
+ def init_private_attributes(self: BaseModel, context: Any, /) -> None:
358
+ """This function is meant to behave like a BaseModel method to initialise private attributes.
359
+
360
+ It takes context as an argument since that's what pydantic-core passes when calling it.
361
+
362
+ Args:
363
+ self: The BaseModel instance.
364
+ context: The context.
365
+ """
366
+ if getattr(self, '__pydantic_private__', None) is None:
367
+ pydantic_private = {}
368
+ for name, private_attr in self.__private_attributes__.items():
369
+ default = private_attr.get_default()
370
+ if default is not PydanticUndefined:
371
+ pydantic_private[name] = default
372
+ object_setattr(self, '__pydantic_private__', pydantic_private)
373
+
374
+
375
+ def get_model_post_init(namespace: dict[str, Any], bases: tuple[type[Any], ...]) -> Callable[..., Any] | None:
376
+ """Get the `model_post_init` method from the namespace or the class bases, or `None` if not defined."""
377
+ if 'model_post_init' in namespace:
378
+ return namespace['model_post_init']
379
+
380
+ BaseModel = import_cached_base_model()
381
+
382
+ model_post_init = get_attribute_from_bases(bases, 'model_post_init')
383
+ if model_post_init is not BaseModel.model_post_init:
384
+ return model_post_init
385
+
386
+
387
+ def inspect_namespace( # noqa C901
388
+ namespace: dict[str, Any],
389
+ raw_annotations: dict[str, Any],
390
+ ignored_types: tuple[type[Any], ...],
391
+ base_class_vars: set[str],
392
+ base_class_fields: set[str],
393
+ ) -> dict[str, ModelPrivateAttr]:
394
+ """Iterate over the namespace and:
395
+ * gather private attributes
396
+ * check for items which look like fields but are not (e.g. have no annotation) and warn.
397
+
398
+ Args:
399
+ namespace: The attribute dictionary of the class to be created.
400
+ raw_annotations: The (non-evaluated) annotations of the model.
401
+ ignored_types: A tuple of ignore types.
402
+ base_class_vars: A set of base class class variables.
403
+ base_class_fields: A set of base class fields.
404
+
405
+ Returns:
406
+ A dict contains private attributes info.
407
+
408
+ Raises:
409
+ TypeError: If there is a `__root__` field in model.
410
+ NameError: If private attribute name is invalid.
411
+ PydanticUserError:
412
+ - If a field does not have a type annotation.
413
+ - If a field on base class was overridden by a non-annotated attribute.
414
+ """
415
+ from ..fields import ModelPrivateAttr, PrivateAttr
416
+
417
+ FieldInfo = import_cached_field_info()
418
+
419
+ all_ignored_types = ignored_types + default_ignored_types()
420
+
421
+ private_attributes: dict[str, ModelPrivateAttr] = {}
422
+
423
+ if '__root__' in raw_annotations or '__root__' in namespace:
424
+ raise TypeError("To define root models, use `pydantic.RootModel` rather than a field called '__root__'")
425
+
426
+ ignored_names: set[str] = set()
427
+ for var_name, value in list(namespace.items()):
428
+ if var_name == 'model_config' or var_name == '__pydantic_extra__':
429
+ continue
430
+ elif (
431
+ isinstance(value, type)
432
+ and value.__module__ == namespace['__module__']
433
+ and '__qualname__' in namespace
434
+ and value.__qualname__.startswith(f'{namespace["__qualname__"]}.')
435
+ ):
436
+ # `value` is a nested type defined in this namespace; don't error
437
+ continue
438
+ elif isinstance(value, all_ignored_types) or value.__class__.__module__ == 'functools':
439
+ ignored_names.add(var_name)
440
+ continue
441
+ elif isinstance(value, ModelPrivateAttr):
442
+ if var_name.startswith('__'):
443
+ raise NameError(
444
+ 'Private attributes must not use dunder names;'
445
+ f' use a single underscore prefix instead of {var_name!r}.'
446
+ )
447
+ elif is_valid_field_name(var_name):
448
+ raise NameError(
449
+ 'Private attributes must not use valid field names;'
450
+ f' use sunder names, e.g. {"_" + var_name!r} instead of {var_name!r}.'
451
+ )
452
+ private_attributes[var_name] = value
453
+ del namespace[var_name]
454
+ elif isinstance(value, FieldInfo) and not is_valid_field_name(var_name):
455
+ suggested_name = var_name.lstrip('_') or 'my_field' # don't suggest '' for all-underscore name
456
+ raise NameError(
457
+ f'Fields must not use names with leading underscores;'
458
+ f' e.g., use {suggested_name!r} instead of {var_name!r}.'
459
+ )
460
+
461
+ elif var_name.startswith('__'):
462
+ continue
463
+ elif is_valid_privateattr_name(var_name):
464
+ if var_name not in raw_annotations or not is_classvar_annotation(raw_annotations[var_name]):
465
+ private_attributes[var_name] = cast(ModelPrivateAttr, PrivateAttr(default=value))
466
+ del namespace[var_name]
467
+ elif var_name in base_class_vars:
468
+ continue
469
+ elif var_name not in raw_annotations:
470
+ if var_name in base_class_fields:
471
+ raise PydanticUserError(
472
+ f'Field {var_name!r} defined on a base class was overridden by a non-annotated attribute. '
473
+ f'All field definitions, including overrides, require a type annotation.',
474
+ code='model-field-overridden',
475
+ )
476
+ elif isinstance(value, FieldInfo):
477
+ raise PydanticUserError(
478
+ f'Field {var_name!r} requires a type annotation', code='model-field-missing-annotation'
479
+ )
480
+ else:
481
+ raise PydanticUserError(
482
+ f'A non-annotated attribute was detected: `{var_name} = {value!r}`. All model fields require a '
483
+ f'type annotation; if `{var_name}` is not meant to be a field, you may be able to resolve this '
484
+ f"error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`.",
485
+ code='model-field-missing-annotation',
486
+ )
487
+
488
+ for ann_name, ann_type in raw_annotations.items():
489
+ if (
490
+ is_valid_privateattr_name(ann_name)
491
+ and ann_name not in private_attributes
492
+ and ann_name not in ignored_names
493
+ # This condition can be a false negative when `ann_type` is stringified,
494
+ # but it is handled in most cases in `set_model_fields`:
495
+ and not is_classvar_annotation(ann_type)
496
+ and ann_type not in all_ignored_types
497
+ and getattr(ann_type, '__module__', None) != 'functools'
498
+ ):
499
+ if isinstance(ann_type, str):
500
+ # Walking up the frames to get the module namespace where the model is defined
501
+ # (as the model class wasn't created yet, we unfortunately can't use `cls.__module__`):
502
+ frame = sys._getframe(2)
503
+ if frame is not None:
504
+ try:
505
+ ann_type = eval_type_backport(
506
+ _make_forward_ref(ann_type, is_argument=False, is_class=True),
507
+ globalns=frame.f_globals,
508
+ localns=frame.f_locals,
509
+ )
510
+ except (NameError, TypeError):
511
+ pass
512
+
513
+ if typing_objects.is_annotated(get_origin(ann_type)):
514
+ _, *metadata = get_args(ann_type)
515
+ private_attr = next((v for v in metadata if isinstance(v, ModelPrivateAttr)), None)
516
+ if private_attr is not None:
517
+ private_attributes[ann_name] = private_attr
518
+ continue
519
+ private_attributes[ann_name] = PrivateAttr()
520
+
521
+ return private_attributes
522
+
523
+
524
+ def set_default_hash_func(cls: type[BaseModel], bases: tuple[type[Any], ...]) -> None:
525
+ base_hash_func = get_attribute_from_bases(bases, '__hash__')
526
+ new_hash_func = make_hash_func(cls)
527
+ if base_hash_func in {None, object.__hash__} or getattr(base_hash_func, '__code__', None) == new_hash_func.__code__:
528
+ # If `__hash__` is some default, we generate a hash function.
529
+ # It will be `None` if not overridden from BaseModel.
530
+ # It may be `object.__hash__` if there is another
531
+ # parent class earlier in the bases which doesn't override `__hash__` (e.g. `typing.Generic`).
532
+ # It may be a value set by `set_default_hash_func` if `cls` is a subclass of another frozen model.
533
+ # In the last case we still need a new hash function to account for new `model_fields`.
534
+ cls.__hash__ = new_hash_func
535
+
536
+
537
+ def make_hash_func(cls: type[BaseModel]) -> Any:
538
+ getter = operator.itemgetter(*cls.__pydantic_fields__.keys()) if cls.__pydantic_fields__ else lambda _: 0
539
+
540
+ def hash_func(self: Any) -> int:
541
+ try:
542
+ return hash(getter(self.__dict__))
543
+ except KeyError:
544
+ # In rare cases (such as when using the deprecated copy method), the __dict__ may not contain
545
+ # all model fields, which is how we can get here.
546
+ # getter(self.__dict__) is much faster than any 'safe' method that accounts for missing keys,
547
+ # and wrapping it in a `try` doesn't slow things down much in the common case.
548
+ return hash(getter(SafeGetItemProxy(self.__dict__)))
549
+
550
+ return hash_func
551
+
552
+
553
+ def set_model_fields(
554
+ cls: type[BaseModel],
555
+ config_wrapper: ConfigWrapper,
556
+ ns_resolver: NsResolver | None,
557
+ ) -> None:
558
+ """Collect and set `cls.__pydantic_fields__` and `cls.__class_vars__`.
559
+
560
+ Args:
561
+ cls: BaseModel or dataclass.
562
+ config_wrapper: The config wrapper instance.
563
+ ns_resolver: Namespace resolver to use when getting model annotations.
564
+ """
565
+ typevars_map = get_model_typevars_map(cls)
566
+ fields, class_vars = collect_model_fields(cls, config_wrapper, ns_resolver, typevars_map=typevars_map)
567
+
568
+ cls.__pydantic_fields__ = fields
569
+ cls.__class_vars__.update(class_vars)
570
+
571
+ for k in class_vars:
572
+ # Class vars should not be private attributes
573
+ # We remove them _here_ and not earlier because we rely on inspecting the class to determine its classvars,
574
+ # but private attributes are determined by inspecting the namespace _prior_ to class creation.
575
+ # In the case that a classvar with a leading-'_' is defined via a ForwardRef (e.g., when using
576
+ # `__future__.annotations`), we want to remove the private attribute which was detected _before_ we knew it
577
+ # evaluated to a classvar
578
+
579
+ value = cls.__private_attributes__.pop(k, None)
580
+ if value is not None and value.default is not PydanticUndefined:
581
+ setattr(cls, k, value.default)
582
+
583
+
584
+ def complete_model_class(
585
+ cls: type[BaseModel],
586
+ config_wrapper: ConfigWrapper,
587
+ ns_resolver: NsResolver,
588
+ *,
589
+ raise_errors: bool = True,
590
+ call_on_complete_hook: bool = True,
591
+ create_model_module: str | None = None,
592
+ ) -> bool:
593
+ """Finish building a model class.
594
+
595
+ This logic must be called after class has been created since validation functions must be bound
596
+ and `get_type_hints` requires a class object.
597
+
598
+ Args:
599
+ cls: BaseModel or dataclass.
600
+ config_wrapper: The config wrapper instance.
601
+ ns_resolver: The namespace resolver instance to use during schema building.
602
+ raise_errors: Whether to raise errors.
603
+ call_on_complete_hook: Whether to call the `__pydantic_on_complete__` hook.
604
+ create_model_module: The module of the class to be created, if created by `create_model`.
605
+
606
+ Returns:
607
+ `True` if the model is successfully completed, else `False`.
608
+
609
+ Raises:
610
+ PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation` occurs in`__get_pydantic_core_schema__`
611
+ and `raise_errors=True`.
612
+ """
613
+ typevars_map = get_model_typevars_map(cls)
614
+
615
+ if not cls.__pydantic_fields_complete__:
616
+ # Note: when coming from `ModelMetaclass.__new__()`, this results in fields being built twice.
617
+ # We do so a second time here so that we can get the `NameError` for the specific undefined annotation.
618
+ # Alternatively, we could let `GenerateSchema()` raise the error, but there are cases where incomplete
619
+ # fields are inherited in `collect_model_fields()` and can actually have their annotation resolved in the
620
+ # generate schema process. As we want to avoid having `__pydantic_fields_complete__` set to `False`
621
+ # when `__pydantic_complete__` is `True`, we rebuild here:
622
+ try:
623
+ cls.__pydantic_fields__ = rebuild_model_fields(
624
+ cls,
625
+ config_wrapper=config_wrapper,
626
+ ns_resolver=ns_resolver,
627
+ typevars_map=typevars_map,
628
+ )
629
+ except NameError as e:
630
+ exc = PydanticUndefinedAnnotation.from_name_error(e)
631
+ set_model_mocks(cls, f'`{exc.name}`')
632
+ if raise_errors:
633
+ raise exc from e
634
+
635
+ if not raise_errors and not cls.__pydantic_fields_complete__:
636
+ # No need to continue with schema gen, it is guaranteed to fail
637
+ return False
638
+
639
+ assert cls.__pydantic_fields_complete__
640
+
641
+ gen_schema = GenerateSchema(
642
+ config_wrapper,
643
+ ns_resolver,
644
+ typevars_map,
645
+ )
646
+
647
+ try:
648
+ schema = gen_schema.generate_schema(cls)
649
+ except PydanticUndefinedAnnotation as e:
650
+ if raise_errors:
651
+ raise
652
+ set_model_mocks(cls, f'`{e.name}`')
653
+ return False
654
+
655
+ core_config = config_wrapper.core_config(title=cls.__name__)
656
+
657
+ try:
658
+ schema = gen_schema.clean_schema(schema)
659
+ except InvalidSchemaError:
660
+ set_model_mocks(cls)
661
+ return False
662
+
663
+ # This needs to happen *after* model schema generation, as the return type
664
+ # of the properties are evaluated and the `ComputedFieldInfo` are recreated:
665
+ cls.__pydantic_computed_fields__ = {k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()}
666
+
667
+ set_deprecated_descriptors(cls)
668
+
669
+ cls.__pydantic_core_schema__ = schema
670
+
671
+ cls.__pydantic_validator__ = create_schema_validator(
672
+ schema,
673
+ cls,
674
+ create_model_module or cls.__module__,
675
+ cls.__qualname__,
676
+ 'create_model' if create_model_module else 'BaseModel',
677
+ core_config,
678
+ config_wrapper.plugin_settings,
679
+ )
680
+ cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config)
681
+
682
+ # set __signature__ attr only for model class, but not for its instances
683
+ # (because instances can define `__call__`, and `inspect.signature` shouldn't
684
+ # use the `__signature__` attribute and instead generate from `__call__`).
685
+ cls.__signature__ = LazyClassAttribute(
686
+ '__signature__',
687
+ partial(
688
+ generate_pydantic_signature,
689
+ init=cls.__init__,
690
+ fields=cls.__pydantic_fields__,
691
+ validate_by_name=config_wrapper.validate_by_name,
692
+ extra=config_wrapper.extra,
693
+ ),
694
+ )
695
+
696
+ cls.__pydantic_complete__ = True
697
+
698
+ if call_on_complete_hook:
699
+ cls.__pydantic_on_complete__()
700
+
701
+ return True
702
+
703
+
704
+ def set_deprecated_descriptors(cls: type[BaseModel]) -> None:
705
+ """Set data descriptors on the class for deprecated fields."""
706
+ for field, field_info in cls.__pydantic_fields__.items():
707
+ if (msg := field_info.deprecation_message) is not None:
708
+ desc = _DeprecatedFieldDescriptor(msg)
709
+ desc.__set_name__(cls, field)
710
+ setattr(cls, field, desc)
711
+
712
+ for field, computed_field_info in cls.__pydantic_computed_fields__.items():
713
+ if (
714
+ (msg := computed_field_info.deprecation_message) is not None
715
+ # Avoid having two warnings emitted:
716
+ and not hasattr(unwrap_wrapped_function(computed_field_info.wrapped_property), '__deprecated__')
717
+ ):
718
+ desc = _DeprecatedFieldDescriptor(msg, computed_field_info.wrapped_property)
719
+ desc.__set_name__(cls, field)
720
+ setattr(cls, field, desc)
721
+
722
+
723
+ class _DeprecatedFieldDescriptor:
724
+ """Read-only data descriptor used to emit a runtime deprecation warning before accessing a deprecated field.
725
+
726
+ Attributes:
727
+ msg: The deprecation message to be emitted.
728
+ wrapped_property: The property instance if the deprecated field is a computed field, or `None`.
729
+ field_name: The name of the field being deprecated.
730
+ """
731
+
732
+ field_name: str
733
+
734
+ def __init__(self, msg: str, wrapped_property: property | None = None) -> None:
735
+ self.msg = msg
736
+ self.wrapped_property = wrapped_property
737
+
738
+ def __set_name__(self, cls: type[BaseModel], name: str) -> None:
739
+ self.field_name = name
740
+
741
+ def __get__(self, obj: BaseModel | None, obj_type: type[BaseModel] | None = None) -> Any:
742
+ if obj is None:
743
+ if self.wrapped_property is not None:
744
+ return self.wrapped_property.__get__(None, obj_type)
745
+ raise AttributeError(self.field_name)
746
+
747
+ warnings.warn(self.msg, DeprecationWarning, stacklevel=2)
748
+
749
+ if self.wrapped_property is not None:
750
+ return self.wrapped_property.__get__(obj, obj_type)
751
+ return obj.__dict__[self.field_name]
752
+
753
+ # Defined to make it a data descriptor and take precedence over the instance's dictionary.
754
+ # Note that it will not be called when setting a value on a model instance
755
+ # as `BaseModel.__setattr__` is defined and takes priority.
756
+ def __set__(self, obj: Any, value: Any) -> NoReturn:
757
+ raise AttributeError(self.field_name)
758
+
759
+
760
+ class _PydanticWeakRef:
761
+ """Wrapper for `weakref.ref` that enables `pickle` serialization.
762
+
763
+ Cloudpickle fails to serialize `weakref.ref` objects due to an arcane error related
764
+ to abstract base classes (`abc.ABC`). This class works around the issue by wrapping
765
+ `weakref.ref` instead of subclassing it.
766
+
767
+ See https://github.com/pydantic/pydantic/issues/6763 for context.
768
+
769
+ Semantics:
770
+ - If not pickled, behaves the same as a `weakref.ref`.
771
+ - If pickled along with the referenced object, the same `weakref.ref` behavior
772
+ will be maintained between them after unpickling.
773
+ - If pickled without the referenced object, after unpickling the underlying
774
+ reference will be cleared (`__call__` will always return `None`).
775
+ """
776
+
777
+ def __init__(self, obj: Any):
778
+ if obj is None:
779
+ # The object will be `None` upon deserialization if the serialized weakref
780
+ # had lost its underlying object.
781
+ self._wr = None
782
+ else:
783
+ self._wr = weakref.ref(obj)
784
+
785
+ def __call__(self) -> Any:
786
+ if self._wr is None:
787
+ return None
788
+ else:
789
+ return self._wr()
790
+
791
+ def __reduce__(self) -> tuple[Callable, tuple[weakref.ReferenceType | None]]:
792
+ return _PydanticWeakRef, (self(),)
793
+
794
+
795
+ def build_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None:
796
+ """Takes an input dictionary, and produces a new value that (invertibly) replaces the values with weakrefs.
797
+
798
+ We can't just use a WeakValueDictionary because many types (including int, str, etc.) can't be stored as values
799
+ in a WeakValueDictionary.
800
+
801
+ The `unpack_lenient_weakvaluedict` function can be used to reverse this operation.
802
+ """
803
+ if d is None:
804
+ return None
805
+ result = {}
806
+ for k, v in d.items():
807
+ try:
808
+ proxy = _PydanticWeakRef(v)
809
+ except TypeError:
810
+ proxy = v
811
+ result[k] = proxy
812
+ return result
813
+
814
+
815
+ def unpack_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None:
816
+ """Inverts the transform performed by `build_lenient_weakvaluedict`."""
817
+ if d is None:
818
+ return None
819
+
820
+ result = {}
821
+ for k, v in d.items():
822
+ if isinstance(v, _PydanticWeakRef):
823
+ v = v()
824
+ if v is not None:
825
+ result[k] = v
826
+ else:
827
+ result[k] = v
828
+ return result
829
+
830
+
831
+ @cache
832
+ def default_ignored_types() -> tuple[type[Any], ...]:
833
+ from ..fields import ComputedFieldInfo
834
+
835
+ ignored_types = [
836
+ FunctionType,
837
+ property,
838
+ classmethod,
839
+ staticmethod,
840
+ PydanticDescriptorProxy,
841
+ ComputedFieldInfo,
842
+ TypeAliasType, # from `typing_extensions`
843
+ ]
844
+
845
+ if sys.version_info >= (3, 12):
846
+ ignored_types.append(typing.TypeAliasType)
847
+
848
+ return tuple(ignored_types)
data/miniconda3/envs/catiagent/lib/python3.11/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)