1"""!!! abstract "Usage Documentation"
2 [Build a Plugin](../concepts/plugins.md#build-a-plugin)
3
4Plugin interface for Pydantic plugins, and related types.
5"""
6
7from __future__ import annotations
8
9from typing import Any, Callable, Literal, NamedTuple
10
11from pydantic_core import CoreConfig, CoreSchema, ValidationError
12from typing_extensions import Protocol, TypeAlias
13
14__all__ = (
15 'PydanticPluginProtocol',
16 'BaseValidateHandlerProtocol',
17 'ValidatePythonHandlerProtocol',
18 'ValidateJsonHandlerProtocol',
19 'ValidateStringsHandlerProtocol',
20 'NewSchemaReturns',
21 'SchemaTypePath',
22 'SchemaKind',
23)
24
25NewSchemaReturns: TypeAlias = 'tuple[ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None]'
26
27
28class SchemaTypePath(NamedTuple):
29 """Path defining where `schema_type` was defined, or where `TypeAdapter` was called."""
30
31 module: str
32 name: str
33
34
35SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call']
36
37
38class PydanticPluginProtocol(Protocol):
39 """Protocol defining the interface for Pydantic plugins."""
40
41 def new_schema_validator(
42 self,
43 schema: CoreSchema,
44 schema_type: Any,
45 schema_type_path: SchemaTypePath,
46 schema_kind: SchemaKind,
47 config: CoreConfig | None,
48 plugin_settings: dict[str, object],
49 ) -> tuple[
50 ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None
51 ]:
52 """This method is called for each plugin every time a new [`SchemaValidator`][pydantic_core.SchemaValidator]
53 is created.
54
55 It should return an event handler for each of the three validation methods, or `None` if the plugin does not
56 implement that method.
57
58 Args:
59 schema: The schema to validate against.
60 schema_type: The original type which the schema was created from, e.g. the model class.
61 schema_type_path: Path defining where `schema_type` was defined, or where `TypeAdapter` was called.
62 schema_kind: The kind of schema to validate against.
63 config: The config to use for validation.
64 plugin_settings: Any plugin settings.
65
66 Returns:
67 A tuple of optional event handlers for each of the three validation methods -
68 `validate_python`, `validate_json`, `validate_strings`.
69 """
70 raise NotImplementedError('Pydantic plugins should implement `new_schema_validator`.')
71
72
73class BaseValidateHandlerProtocol(Protocol):
74 """Base class for plugin callbacks protocols.
75
76 You shouldn't implement this protocol directly, instead use one of the subclasses with adds the correctly
77 typed `on_error` method.
78 """
79
80 on_enter: Callable[..., None]
81 """`on_enter` is changed to be more specific on all subclasses"""
82
83 def on_success(self, result: Any) -> None:
84 """Callback to be notified of successful validation.
85
86 Args:
87 result: The result of the validation.
88 """
89 return
90
91 def on_error(self, error: ValidationError) -> None:
92 """Callback to be notified of validation errors.
93
94 Args:
95 error: The validation error.
96 """
97 return
98
99 def on_exception(self, exception: Exception) -> None:
100 """Callback to be notified of validation exceptions.
101
102 Args:
103 exception: The exception raised during validation.
104 """
105 return
106
107
108class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
109 """Event handler for `SchemaValidator.validate_python`."""
110
111 def on_enter(
112 self,
113 input: Any,
114 *,
115 strict: bool | None = None,
116 from_attributes: bool | None = None,
117 context: dict[str, 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 from_attributes: Whether to validate objects as inputs by extracting attributes.
128 context: The context to use for validation, this is passed to functional validators.
129 self_instance: An instance of a model to set attributes on from validation, this is used when running
130 validation from the `__init__` method of a model.
131 by_alias: Whether to use the field's alias to match the input data to an attribute.
132 by_name: Whether to use the field's name to match the input data to an attribute.
133 """
134 pass
135
136
137class 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 context: dict[str, Any] | None = None,
146 self_instance: Any | None = None,
147 by_alias: bool | None = None,
148 by_name: bool | None = None,
149 ) -> None:
150 """Callback to be notified of validation start, and create an instance of the event handler.
151
152 Args:
153 input: The JSON data to be validated.
154 strict: Whether to validate the object in strict mode.
155 context: The context to use for validation, this is passed to functional validators.
156 self_instance: An instance of a model to set attributes on from validation, this is used when running
157 validation from the `__init__` method of a model.
158 by_alias: Whether to use the field's alias to match the input data to an attribute.
159 by_name: Whether to use the field's name to match the input data to an attribute.
160 """
161 pass
162
163
164StringInput: TypeAlias = 'dict[str, StringInput]'
165
166
167class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol):
168 """Event handler for `SchemaValidator.validate_strings`."""
169
170 def on_enter(
171 self,
172 input: StringInput,
173 *,
174 strict: bool | None = None,
175 context: dict[str, Any] | None = None,
176 by_alias: bool | None = None,
177 by_name: bool | None = None,
178 ) -> None:
179 """Callback to be notified of validation start, and create an instance of the event handler.
180
181 Args:
182 input: The string data to be validated.
183 strict: Whether to validate the object in strict mode.
184 context: The context to use for validation, this is passed to functional validators.
185 by_alias: Whether to use the field's alias to match the input data to an attribute.
186 by_name: Whether to use the field's name to match the input data to an attribute.
187 """
188 pass