pboot-validator 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. pboot_validator/__init__.py +461 -0
  2. pboot_validator/_internal/__init__.py +0 -0
  3. pboot_validator/_internal/_config.py +408 -0
  4. pboot_validator/_internal/_contextlib.py +84 -0
  5. pboot_validator/_internal/_core_metadata.py +97 -0
  6. pboot_validator/_internal/_core_utils.py +156 -0
  7. pboot_validator/_internal/_dataclasses.py +327 -0
  8. pboot_validator/_internal/_decorators.py +906 -0
  9. pboot_validator/_internal/_decorators_v1.py +174 -0
  10. pboot_validator/_internal/_discriminated_union.py +510 -0
  11. pboot_validator/_internal/_docs_extraction.py +128 -0
  12. pboot_validator/_internal/_fields.py +910 -0
  13. pboot_validator/_internal/_forward_ref.py +23 -0
  14. pboot_validator/_internal/_generate_schema.py +3053 -0
  15. pboot_validator/_internal/_generics.py +572 -0
  16. pboot_validator/_internal/_git.py +27 -0
  17. pboot_validator/_internal/_import_utils.py +20 -0
  18. pboot_validator/_internal/_known_annotated_metadata.py +412 -0
  19. pboot_validator/_internal/_mock_val_ser.py +241 -0
  20. pboot_validator/_internal/_model_construction.py +833 -0
  21. pboot_validator/_internal/_namespace_utils.py +300 -0
  22. pboot_validator/_internal/_repr.py +129 -0
  23. pboot_validator/_internal/_schema_gather.py +49 -0
  24. pboot_validator/_internal/_schema_generation_shared.py +126 -0
  25. pboot_validator/_internal/_serializers.py +59 -0
  26. pboot_validator/_internal/_signature.py +193 -0
  27. pboot_validator/_internal/_type_refs.py +128 -0
  28. pboot_validator/_internal/_typing_extra.py +506 -0
  29. pboot_validator/_internal/_utils.py +433 -0
  30. pboot_validator/_internal/_validate_call.py +141 -0
  31. pboot_validator/_internal/_validators.py +541 -0
  32. pboot_validator/_migration.py +317 -0
  33. pboot_validator/alias_generators.py +62 -0
  34. pboot_validator/aliases.py +136 -0
  35. pboot_validator/annotated_handlers.py +123 -0
  36. pboot_validator/class_validators.py +5 -0
  37. pboot_validator/color.py +605 -0
  38. pboot_validator/config.py +1295 -0
  39. pboot_validator/dataclasses.py +385 -0
  40. pboot_validator/datetime_parse.py +5 -0
  41. pboot_validator/decorator.py +5 -0
  42. pboot_validator/deprecated/__init__.py +0 -0
  43. pboot_validator/deprecated/class_validators.py +257 -0
  44. pboot_validator/deprecated/config.py +72 -0
  45. pboot_validator/deprecated/copy_internals.py +224 -0
  46. pboot_validator/deprecated/decorator.py +286 -0
  47. pboot_validator/deprecated/json.py +142 -0
  48. pboot_validator/deprecated/parse.py +81 -0
  49. pboot_validator/deprecated/tools.py +104 -0
  50. pboot_validator/env_settings.py +5 -0
  51. pboot_validator/error_wrappers.py +5 -0
  52. pboot_validator/errors.py +185 -0
  53. pboot_validator/experimental/__init__.py +1 -0
  54. pboot_validator/experimental/arguments_schema.py +44 -0
  55. pboot_validator/experimental/missing_sentinel.py +29 -0
  56. pboot_validator/experimental/pipeline.py +684 -0
  57. pboot_validator/fields.py +2065 -0
  58. pboot_validator/functional_serializers.py +461 -0
  59. pboot_validator/functional_validators.py +920 -0
  60. pboot_validator/generics.py +5 -0
  61. pboot_validator/json.py +5 -0
  62. pboot_validator/json_schema.py +3283 -0
  63. pboot_validator/main.py +1947 -0
  64. pboot_validator/mypy.py +1469 -0
  65. pboot_validator/networks.py +1417 -0
  66. pboot_validator/parse.py +5 -0
  67. pboot_validator/plugin/__init__.py +190 -0
  68. pboot_validator/plugin/_loader.py +56 -0
  69. pboot_validator/plugin/_schema_validator.py +152 -0
  70. pboot_validator/py.typed +0 -0
  71. pboot_validator/root_model.py +189 -0
  72. pboot_validator/schema.py +5 -0
  73. pboot_validator/tools.py +5 -0
  74. pboot_validator/type_adapter.py +780 -0
  75. pboot_validator/types.py +3405 -0
  76. pboot_validator/typing.py +5 -0
  77. pboot_validator/utils.py +5 -0
  78. pboot_validator/v1/__init__.py +131 -0
  79. pboot_validator/v1/_hypothesis_plugin.py +391 -0
  80. pboot_validator/v1/annotated_types.py +72 -0
  81. pboot_validator/v1/class_validators.py +361 -0
  82. pboot_validator/v1/color.py +494 -0
  83. pboot_validator/v1/config.py +191 -0
  84. pboot_validator/v1/dataclasses.py +503 -0
  85. pboot_validator/v1/datetime_parse.py +248 -0
  86. pboot_validator/v1/decorator.py +264 -0
  87. pboot_validator/v1/env_settings.py +350 -0
  88. pboot_validator/v1/error_wrappers.py +161 -0
  89. pboot_validator/v1/errors.py +646 -0
  90. pboot_validator/v1/fields.py +1253 -0
  91. pboot_validator/v1/generics.py +400 -0
  92. pboot_validator/v1/json.py +112 -0
  93. pboot_validator/v1/main.py +1130 -0
  94. pboot_validator/v1/mypy.py +950 -0
  95. pboot_validator/v1/networks.py +747 -0
  96. pboot_validator/v1/parse.py +66 -0
  97. pboot_validator/v1/py.typed +0 -0
  98. pboot_validator/v1/schema.py +1163 -0
  99. pboot_validator/v1/tools.py +92 -0
  100. pboot_validator/v1/types.py +1213 -0
  101. pboot_validator/v1/typing.py +627 -0
  102. pboot_validator/v1/utils.py +807 -0
  103. pboot_validator/v1/validators.py +768 -0
  104. pboot_validator/v1/version.py +38 -0
  105. pboot_validator/validate_call_decorator.py +121 -0
  106. pboot_validator/validators.py +5 -0
  107. pboot_validator/version.py +113 -0
  108. pboot_validator/warnings.py +130 -0
  109. pboot_validator-1.0.0.dist-info/METADATA +93 -0
  110. pboot_validator-1.0.0.dist-info/RECORD +112 -0
  111. pboot_validator-1.0.0.dist-info/WHEEL +4 -0
  112. pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,5 @@
1
+ """The `parse` module is a backport module from V1."""
2
+
3
+ from ._migration import getattr_migration
4
+
5
+ __getattr__ = getattr_migration(__name__)
@@ -0,0 +1,190 @@
1
+ """Plugin interface for Pydantic plugins, and related types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any, Literal, NamedTuple, TypeAlias
7
+
8
+ from pydantic_core import CoreConfig, CoreSchema, ValidationError
9
+ from typing_extensions import Protocol
10
+
11
+ from pboot_validator.config import ExtraValues
12
+
13
+ __all__ = (
14
+ 'PydanticPluginProtocol',
15
+ 'BaseValidateHandlerProtocol',
16
+ 'ValidatePythonHandlerProtocol',
17
+ 'ValidateJsonHandlerProtocol',
18
+ 'ValidateStringsHandlerProtocol',
19
+ 'NewSchemaReturns',
20
+ 'SchemaTypePath',
21
+ 'SchemaKind',
22
+ )
23
+
24
+ NewSchemaReturns: TypeAlias = 'tuple[ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None]'
25
+
26
+
27
+ class SchemaTypePath(NamedTuple):
28
+ """Path defining where `schema_type` was defined, or where `TypeAdapter` was called."""
29
+
30
+ module: str
31
+ name: str
32
+
33
+
34
+ SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call']
35
+
36
+
37
+ class PydanticPluginProtocol(Protocol):
38
+ """Protocol defining the interface for Pydantic plugins."""
39
+
40
+ def new_schema_validator(
41
+ self,
42
+ schema: CoreSchema,
43
+ schema_type: Any,
44
+ schema_type_path: SchemaTypePath,
45
+ schema_kind: SchemaKind,
46
+ config: CoreConfig | None,
47
+ plugin_settings: dict[str, object],
48
+ ) -> tuple[
49
+ ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None
50
+ ]:
51
+ """This method is called for each plugin every time a new [`SchemaValidator`][pydantic_core.SchemaValidator]
52
+ is created.
53
+
54
+ It should return an event handler for each of the three validation methods, or `None` if the plugin does not
55
+ implement that method.
56
+
57
+ Args:
58
+ schema: The schema to validate against.
59
+ schema_type: The original type which the schema was created from, e.g. the model class.
60
+ schema_type_path: Path defining where `schema_type` was defined, or where `TypeAdapter` was called.
61
+ schema_kind: The kind of schema to validate against.
62
+ config: The config to use for validation.
63
+ plugin_settings: Any plugin settings.
64
+
65
+ Returns:
66
+ A tuple of optional event handlers for each of the three validation methods -
67
+ `validate_python`, `validate_json`, `validate_strings`.
68
+ """
69
+ raise NotImplementedError('Pydantic plugins should implement `new_schema_validator`.')
70
+
71
+
72
+ class BaseValidateHandlerProtocol(Protocol):
73
+ """Base class for plugin callbacks protocols.
74
+
75
+ You shouldn't implement this protocol directly, instead use one of the subclasses with adds the correctly
76
+ typed `on_error` method.
77
+ """
78
+
79
+ on_enter: Callable[..., None]
80
+ """`on_enter` is changed to be more specific on all subclasses"""
81
+
82
+ def on_success(self, result: Any) -> None:
83
+ """Callback to be notified of successful validation.
84
+
85
+ Args:
86
+ result: The result of the validation.
87
+ """
88
+ return
89
+
90
+ def on_error(self, error: ValidationError) -> None:
91
+ """Callback to be notified of validation errors.
92
+
93
+ Args:
94
+ error: The validation error.
95
+ """
96
+ return
97
+
98
+ def on_exception(self, exception: Exception) -> None:
99
+ """Callback to be notified of validation exceptions.
100
+
101
+ Args:
102
+ exception: The exception raised during validation.
103
+ """
104
+ return
105
+
106
+
107
+ class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
108
+ """Event handler for `SchemaValidator.validate_python`."""
109
+
110
+ def on_enter(
111
+ self,
112
+ input: Any,
113
+ *,
114
+ strict: bool | None = None,
115
+ extra: ExtraValues | None = None,
116
+ from_attributes: bool | None = None,
117
+ context: Any | None = None,
118
+ self_instance: Any | None = None,
119
+ by_alias: bool | None = None,
120
+ by_name: bool | None = None,
121
+ ) -> None:
122
+ """Callback to be notified of validation start, and create an instance of the event handler.
123
+
124
+ Args:
125
+ input: The input to be validated.
126
+ strict: Whether to validate the object in strict mode.
127
+ extra: Whether to ignore, allow, or forbid extra data during model validation.
128
+ from_attributes: Whether to validate objects as inputs by extracting attributes.
129
+ context: The context to use for validation, this is passed to functional validators.
130
+ self_instance: An instance of a model to set attributes on from validation, this is used when running
131
+ validation from the `__init__` method of a model.
132
+ by_alias: Whether to use the field's alias to match the input data to an attribute.
133
+ by_name: Whether to use the field's name to match the input data to an attribute.
134
+ """
135
+
136
+
137
+ class ValidateJsonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
138
+ """Event handler for `SchemaValidator.validate_json`."""
139
+
140
+ def on_enter(
141
+ self,
142
+ input: str | bytes | bytearray,
143
+ *,
144
+ strict: bool | None = None,
145
+ extra: ExtraValues | None = None,
146
+ context: Any | None = None,
147
+ self_instance: Any | None = None,
148
+ by_alias: bool | None = None,
149
+ by_name: bool | None = None,
150
+ ) -> None:
151
+ """Callback to be notified of validation start, and create an instance of the event handler.
152
+
153
+ Args:
154
+ input: The JSON data to be validated.
155
+ strict: Whether to validate the object in strict mode.
156
+ extra: Whether to ignore, allow, or forbid extra data during model validation.
157
+ context: The context to use for validation, this is passed to functional validators.
158
+ self_instance: An instance of a model to set attributes on from validation, this is used when running
159
+ validation from the `__init__` method of a model.
160
+ by_alias: Whether to use the field's alias to match the input data to an attribute.
161
+ by_name: Whether to use the field's name to match the input data to an attribute.
162
+ """
163
+
164
+
165
+ StringInput: TypeAlias = 'dict[str, StringInput]'
166
+
167
+
168
+ class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
169
+ """Event handler for `SchemaValidator.validate_strings`."""
170
+
171
+ def on_enter(
172
+ self,
173
+ input: StringInput,
174
+ *,
175
+ strict: bool | None = None,
176
+ extra: ExtraValues | None = None,
177
+ context: Any | None = None,
178
+ by_alias: bool | None = None,
179
+ by_name: bool | None = None,
180
+ ) -> None:
181
+ """Callback to be notified of validation start, and create an instance of the event handler.
182
+
183
+ Args:
184
+ input: The string data to be validated.
185
+ strict: Whether to validate the object in strict mode.
186
+ extra: Whether to ignore, allow, or forbid extra data during model validation.
187
+ context: The context to use for validation, this is passed to functional validators.
188
+ by_alias: Whether to use the field's alias to match the input data to an attribute.
189
+ by_name: Whether to use the field's name to match the input data to an attribute.
190
+ """
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import warnings
5
+ from collections.abc import Iterable
6
+ from importlib.metadata import entry_points
7
+ from typing import TYPE_CHECKING, Final
8
+
9
+ if TYPE_CHECKING:
10
+ from . import PydanticPluginProtocol
11
+
12
+
13
+ PYDANTIC_ENTRY_POINT_GROUP: Final[str] = 'pboot_validator'
14
+
15
+ # cache of plugins
16
+ _plugins: dict[str, PydanticPluginProtocol] | None = None
17
+ # return no plugins while loading plugins to avoid recursion and errors while importing plugins
18
+ # this means that if plugins use pydantic
19
+ _loading_plugins: bool = False
20
+
21
+
22
+ def get_plugins() -> Iterable[PydanticPluginProtocol]:
23
+ """Load plugins for Pydantic.
24
+
25
+ Plugins are discovered using the `pydantic` entry point group, as documented in
26
+ https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/#using-package-metadata.
27
+ """
28
+ disabled_plugins = os.getenv('PYDANTIC_DISABLE_PLUGINS')
29
+ global _plugins, _loading_plugins
30
+ if _loading_plugins:
31
+ # this happens when plugins themselves use pydantic, we return no plugins
32
+ return ()
33
+ elif disabled_plugins in ('__all__', '1', 'true'):
34
+ return ()
35
+ elif _plugins is None:
36
+ _plugins = {}
37
+ # set _loading_plugins so any plugins that use pydantic don't themselves use plugins
38
+ _loading_plugins = True
39
+ try:
40
+ for entry_point in entry_points(group=PYDANTIC_ENTRY_POINT_GROUP):
41
+ if entry_point.value in _plugins:
42
+ continue
43
+ if disabled_plugins is not None and entry_point.name in disabled_plugins.split(','):
44
+ continue
45
+ try:
46
+ _plugins[entry_point.value] = entry_point.load()
47
+ except (ImportError, AttributeError) as e:
48
+ warnings.warn(
49
+ f'{e.__class__.__name__} while loading the `{entry_point.name}` Pydantic plugin, '
50
+ f'this plugin will not be installed.\n\n{e!r}',
51
+ stacklevel=2,
52
+ )
53
+ finally:
54
+ _loading_plugins = False
55
+
56
+ return _plugins.values()
@@ -0,0 +1,152 @@
1
+ """Pluggable schema validator for pboot_validator."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ from collections.abc import Callable, Iterable
7
+ from typing import TYPE_CHECKING, Any, Literal, TypeVar
8
+
9
+ from pydantic_core import CoreConfig, CoreSchema, SchemaValidator, ValidationError
10
+ from typing_extensions import ParamSpec
11
+
12
+ if TYPE_CHECKING:
13
+ from . import BaseValidateHandlerProtocol, PydanticPluginProtocol, SchemaKind, SchemaTypePath
14
+
15
+
16
+ P = ParamSpec('P')
17
+ R = TypeVar('R')
18
+ Event = Literal['on_validate_python', 'on_validate_json', 'on_validate_strings']
19
+ events: list[Event] = list(Event.__args__) # type: ignore
20
+
21
+
22
+ def create_schema_validator(
23
+ schema: CoreSchema,
24
+ schema_type: Any,
25
+ schema_type_module: str,
26
+ schema_type_name: str,
27
+ schema_kind: SchemaKind,
28
+ config: CoreConfig | None = None,
29
+ plugin_settings: dict[str, Any] | None = None,
30
+ _use_prebuilt: bool = True,
31
+ ) -> SchemaValidator | PluggableSchemaValidator:
32
+ """Create a `SchemaValidator` or `PluggableSchemaValidator` if plugins are installed.
33
+
34
+ Returns:
35
+ If plugins are installed then return `PluggableSchemaValidator`, otherwise return `SchemaValidator`.
36
+ """
37
+ from . import SchemaTypePath
38
+ from ._loader import get_plugins
39
+
40
+ plugins = get_plugins()
41
+ if plugins:
42
+ return PluggableSchemaValidator(
43
+ schema,
44
+ schema_type,
45
+ SchemaTypePath(schema_type_module, schema_type_name),
46
+ schema_kind,
47
+ config,
48
+ plugins,
49
+ plugin_settings or {},
50
+ _use_prebuilt=_use_prebuilt,
51
+ )
52
+ else:
53
+ return SchemaValidator(schema, config, _use_prebuilt=_use_prebuilt)
54
+
55
+
56
+ class PluggableSchemaValidator:
57
+ """Pluggable schema validator."""
58
+
59
+ __slots__ = '_schema_validator', 'validate_json', 'validate_python', 'validate_strings'
60
+
61
+ def __init__(
62
+ self,
63
+ schema: CoreSchema,
64
+ schema_type: Any,
65
+ schema_type_path: SchemaTypePath,
66
+ schema_kind: SchemaKind,
67
+ config: CoreConfig | None,
68
+ plugins: Iterable[PydanticPluginProtocol],
69
+ plugin_settings: dict[str, Any],
70
+ _use_prebuilt: bool = True,
71
+ ) -> None:
72
+ self._schema_validator = SchemaValidator(schema, config, _use_prebuilt=_use_prebuilt)
73
+
74
+ python_event_handlers: list[BaseValidateHandlerProtocol] = []
75
+ json_event_handlers: list[BaseValidateHandlerProtocol] = []
76
+ strings_event_handlers: list[BaseValidateHandlerProtocol] = []
77
+ for plugin in plugins:
78
+ try:
79
+ p, j, s = plugin.new_schema_validator(
80
+ schema, schema_type, schema_type_path, schema_kind, config, plugin_settings
81
+ )
82
+ except TypeError as e: # pragma: no cover
83
+ raise TypeError(f'Error using plugin `{plugin.__module__}:{plugin.__class__.__name__}`: {e}') from e
84
+ if p is not None:
85
+ python_event_handlers.append(p)
86
+ if j is not None:
87
+ json_event_handlers.append(j)
88
+ if s is not None:
89
+ strings_event_handlers.append(s)
90
+
91
+ self.validate_python = build_wrapper(self._schema_validator.validate_python, python_event_handlers)
92
+ self.validate_json = build_wrapper(self._schema_validator.validate_json, json_event_handlers)
93
+ self.validate_strings = build_wrapper(self._schema_validator.validate_strings, strings_event_handlers)
94
+
95
+ # Used to allow reuse of validators in pydantic-core (see pydantic-core/src/validators/prebuilt.rs):
96
+ @property
97
+ def __pydantic_schema_validator__(self) -> SchemaValidator:
98
+ """The underlying pydantic-core `SchemaValidator`.
99
+
100
+ This is a private attribute, not meant to be used outside Pydantic.
101
+ """
102
+ return self._schema_validator
103
+
104
+ def __getattr__(self, name: str) -> Any:
105
+ return getattr(self._schema_validator, name)
106
+
107
+
108
+ def build_wrapper(func: Callable[P, R], event_handlers: list[BaseValidateHandlerProtocol]) -> Callable[P, R]:
109
+ if not event_handlers:
110
+ return func
111
+ else:
112
+ on_enters = tuple(h.on_enter for h in event_handlers if filter_handlers(h, 'on_enter'))
113
+ on_successes = tuple(h.on_success for h in event_handlers if filter_handlers(h, 'on_success'))
114
+ on_errors = tuple(h.on_error for h in event_handlers if filter_handlers(h, 'on_error'))
115
+ on_exceptions = tuple(h.on_exception for h in event_handlers if filter_handlers(h, 'on_exception'))
116
+
117
+ @functools.wraps(func)
118
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
119
+ for on_enter_handler in on_enters:
120
+ on_enter_handler(*args, **kwargs)
121
+
122
+ try:
123
+ result = func(*args, **kwargs)
124
+ except ValidationError as error:
125
+ for on_error_handler in on_errors:
126
+ on_error_handler(error)
127
+ raise
128
+ except Exception as exception:
129
+ for on_exception_handler in on_exceptions:
130
+ on_exception_handler(exception)
131
+ raise
132
+ else:
133
+ for on_success_handler in on_successes:
134
+ on_success_handler(result)
135
+ return result
136
+
137
+ return wrapper
138
+
139
+
140
+ def filter_handlers(handler_cls: BaseValidateHandlerProtocol, method_name: str) -> bool:
141
+ """Filter out handler methods which are not implemented by the plugin directly - e.g. those that are missing
142
+ or are inherited from the protocol.
143
+ """
144
+ handler = getattr(handler_cls, method_name, None)
145
+ if handler is None:
146
+ return False
147
+ elif handler.__module__ == 'pboot_validator.plugin':
148
+ # this is the original handler, from the protocol due to runtime inheritance
149
+ # we don't want to call it
150
+ return False
151
+ else:
152
+ return True
File without changes
@@ -0,0 +1,189 @@
1
+ """RootModel class and type definitions."""
2
+
3
+ from __future__ import annotations as _annotations
4
+
5
+ from collections.abc import Callable
6
+ from copy import copy, deepcopy
7
+ from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar
8
+
9
+ from pydantic_core import PydanticUndefined
10
+ from typing_extensions import Self, dataclass_transform
11
+
12
+ from . import PydanticUserError
13
+ from ._internal import _model_construction, _repr
14
+ from .main import BaseModel, _object_setattr
15
+
16
+ if TYPE_CHECKING:
17
+ from .fields import Field as PydanticModelField
18
+ from .fields import PrivateAttr as PydanticModelPrivateAttr
19
+ from .main import IncEx
20
+
21
+ # dataclass_transform could be applied to RootModel directly, but `ModelMetaclass`'s dataclass_transform
22
+ # takes priority (at least with pyright). We trick type checkers into thinking we apply dataclass_transform
23
+ # on a new metaclass.
24
+ @dataclass_transform(kw_only_default=False, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr))
25
+ class _RootModelMetaclass(_model_construction.ModelMetaclass): ...
26
+ else:
27
+ _RootModelMetaclass = _model_construction.ModelMetaclass
28
+
29
+ __all__ = ('RootModel',)
30
+
31
+ RootModelRootType = TypeVar('RootModelRootType')
32
+
33
+
34
+ class RootModel(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetaclass):
35
+ """!!! abstract "Usage Documentation"
36
+ [`RootModel` and Custom Root Types](../concepts/models.md#rootmodel-and-custom-root-types)
37
+
38
+ A Pydantic `BaseModel` for the root object of the model.
39
+
40
+ Attributes:
41
+ root: The root object of the model.
42
+ __pydantic_root_model__: Whether the model is a RootModel.
43
+ __pydantic_private__: Private fields in the model.
44
+ __pydantic_extra__: Extra fields in the model.
45
+
46
+ """
47
+
48
+ __pydantic_root_model__ = True
49
+ __pydantic_private__ = None
50
+ __pydantic_extra__ = None
51
+
52
+ root: RootModelRootType
53
+
54
+ def __init_subclass__(cls, **kwargs):
55
+ extra = cls.model_config.get('extra')
56
+ if extra is not None:
57
+ raise PydanticUserError(
58
+ "`RootModel` does not support setting `model_config['extra']`", code='root-model-extra'
59
+ )
60
+ super().__init_subclass__(**kwargs)
61
+
62
+ def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None: # type: ignore
63
+ __tracebackhide__ = True
64
+ if data:
65
+ if root is not PydanticUndefined:
66
+ raise ValueError(
67
+ '"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments'
68
+ )
69
+ root = data # type: ignore
70
+ self.__pydantic_validator__.validate_python(root, self_instance=self)
71
+
72
+ __init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess]
73
+
74
+ @classmethod
75
+ def model_construct(cls, root: RootModelRootType, _fields_set: set[str] | None = None) -> Self: # type: ignore
76
+ """Create a new model using the provided root object and update fields set.
77
+
78
+ Args:
79
+ root: The root object of the model.
80
+ _fields_set: The set of fields to be updated.
81
+
82
+ Returns:
83
+ The new model.
84
+
85
+ Raises:
86
+ NotImplemented: If the model is not a subclass of `RootModel`.
87
+ """
88
+ return super().model_construct(root=root, _fields_set=_fields_set)
89
+
90
+ def __getstate__(self) -> dict[Any, Any]:
91
+ return {
92
+ '__dict__': self.__dict__,
93
+ '__pydantic_fields_set__': self.__pydantic_fields_set__,
94
+ }
95
+
96
+ def __setstate__(self, state: dict[Any, Any]) -> None:
97
+ _object_setattr(self, '__pydantic_fields_set__', state['__pydantic_fields_set__'])
98
+ _object_setattr(self, '__dict__', state['__dict__'])
99
+
100
+ def __copy__(self) -> Self:
101
+ """Returns a shallow copy of the model."""
102
+ cls = type(self)
103
+ m = cls.__new__(cls)
104
+ new_dict = copy(self.__dict__)
105
+ new_dict['root'] = copy(self.__dict__['root']) # pyright: ignore[reportIndexIssue] (https://github.com/microsoft/pyright/issues/11548)
106
+ _object_setattr(m, '__dict__', new_dict)
107
+ _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
108
+ return m
109
+
110
+ def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
111
+ """Returns a deep copy of the model."""
112
+ if memo is None:
113
+ memo = {}
114
+ cls = type(self)
115
+ m = cls.__new__(cls)
116
+ memo[id(self)] = m
117
+ _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
118
+ # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
119
+ # and attempting a deepcopy would be marginally slower.
120
+ _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
121
+ return m
122
+
123
+ if TYPE_CHECKING:
124
+ # This `model_dump()` definition is only provided to get a more accurate return type for type checkers
125
+ # (no override is actually necessary at runtime). Generally, the return type will be `RootModelRootType`,
126
+ # assuming that `RootModelRootType` is not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel`
127
+ # subclass, then the return type will likely be `dict[str, Any]`, as `model_dump()` calls are recursive.
128
+ # The return type could even be something different, in the case of a custom serializer. Thus, `Any` is
129
+ # used here to catch all of these cases.
130
+
131
+ def model_dump( # type: ignore
132
+ self,
133
+ *,
134
+ mode: Literal['json', 'python'] | str = 'python',
135
+ include: IncEx | None = None,
136
+ exclude: IncEx | None = None,
137
+ context: Any | None = None,
138
+ by_alias: bool | None = None,
139
+ exclude_unset: bool = False,
140
+ exclude_defaults: bool = False,
141
+ exclude_none: bool = False,
142
+ exclude_computed_fields: bool = False,
143
+ round_trip: bool = False,
144
+ warnings: bool | Literal['none', 'warn', 'error'] = True,
145
+ fallback: Callable[[Any], Any] | None = None,
146
+ serialize_as_any: bool = False,
147
+ polymorphic_serialization: bool | None = None,
148
+ ) -> Any:
149
+ """!!! abstract "Usage Documentation"
150
+ [`model_dump`](../concepts/serialization.md#python-mode)
151
+
152
+ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
153
+
154
+ Args:
155
+ mode: The mode in which `to_python` should run.
156
+ If mode is 'json', the output will only contain JSON serializable types.
157
+ If mode is 'python', the output may contain non-JSON-serializable Python objects.
158
+ include: A set of fields to include in the output.
159
+ exclude: A set of fields to exclude from the output.
160
+ context: Additional context to pass to the serializer.
161
+ by_alias: Whether to use the field's alias in the dictionary key if defined.
162
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
163
+ exclude_defaults: Whether to exclude fields that are set to their default value.
164
+ exclude_none: Whether to exclude fields that have a value of `None`.
165
+ exclude_computed_fields: Whether to exclude computed fields.
166
+ While this can be useful for round-tripping, it is usually recommended to use the dedicated
167
+ `round_trip` parameter instead.
168
+ round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
169
+ warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
170
+ "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
171
+ fallback: A function to call when an unknown value is encountered. If not provided,
172
+ a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
173
+ serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
174
+ polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
175
+
176
+ Returns:
177
+ A dictionary representation of the model.
178
+ """
179
+ ...
180
+
181
+ def __eq__(self, other: Any) -> bool:
182
+ if not isinstance(other, RootModel):
183
+ return NotImplemented
184
+ return self.__pydantic_fields__['root'].annotation == other.__pydantic_fields__[
185
+ 'root'
186
+ ].annotation and super().__eq__(other)
187
+
188
+ def __repr_args__(self) -> _repr.ReprArgs:
189
+ yield 'root', self.root
@@ -0,0 +1,5 @@
1
+ """The `schema` module is a backport module from V1."""
2
+
3
+ from ._migration import getattr_migration
4
+
5
+ __getattr__ = getattr_migration(__name__)
@@ -0,0 +1,5 @@
1
+ """The `tools` module is a backport module from V1."""
2
+
3
+ from ._migration import getattr_migration
4
+
5
+ __getattr__ = getattr_migration(__name__)