Coverage for pydantic/plugin/__init__.py: 100.00%
17 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-05 10:27 +0000
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-05 10:27 +0000
1"""!!! abstract "Usage Documentation"
2 [Build a Plugin](../concepts/plugins.md#build-a-plugin)
4Plugin interface for Pydantic plugins, and related types.
5"""
7from __future__ import annotations 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
9from typing import Any, Callable, Literal, NamedTuple 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
11from pydantic_core import CoreConfig, CoreSchema, ValidationError 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
12from typing_extensions import Protocol, TypeAlias 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
14__all__ = ( 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
15 'PydanticPluginProtocol',
16 'BaseValidateHandlerProtocol',
17 'ValidatePythonHandlerProtocol',
18 'ValidateJsonHandlerProtocol',
19 'ValidateStringsHandlerProtocol',
20 'NewSchemaReturns',
21 'SchemaTypePath',
22 'SchemaKind',
23)
25NewSchemaReturns: TypeAlias = 'tuple[ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None]' 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
28class SchemaTypePath(NamedTuple): 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
29 """Path defining where `schema_type` was defined, or where `TypeAdapter` was called."""
31 module: str 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
32 name: str 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
35SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call'] 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
38class PydanticPluginProtocol(Protocol): 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
39 """Protocol defining the interface for Pydantic plugins.""" 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
41 def new_schema_validator( 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
42 self,
43 schema: CoreSchema, 1abcderfghijklmnopq
44 schema_type: Any, 1abcderfghijklmnopq
45 schema_type_path: SchemaTypePath, 1abcderfghijklmnopq
46 schema_kind: SchemaKind, 1abcderfghijklmnopq
47 config: CoreConfig | None, 1abcderfghijklmnopq
48 plugin_settings: dict[str, object], 1abcderfghijklmnopq
49 ) -> tuple[ 1abcderfghijklmnopq
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.
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.
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.
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`.')
73class BaseValidateHandlerProtocol(Protocol): 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
74 """Base class for plugin callbacks protocols. 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
76 You shouldn't implement this protocol directly, instead use one of the subclasses with adds the correctly
77 typed `on_error` method.
78 """
80 on_enter: Callable[..., None] 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
81 """`on_enter` is changed to be more specific on all subclasses""" 1stuvabcdefwxyzghijklABCDmnopq
83 def on_success(self, result: Any) -> None: 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
84 """Callback to be notified of successful validation.
86 Args:
87 result: The result of the validation.
88 """
89 return
91 def on_error(self, error: ValidationError) -> None: 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
92 """Callback to be notified of validation errors.
94 Args:
95 error: The validation error.
96 """
97 return
99 def on_exception(self, exception: Exception) -> None: 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
100 """Callback to be notified of validation exceptions.
102 Args:
103 exception: The exception raised during validation.
104 """
105 return
108class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
109 """Event handler for `SchemaValidator.validate_python`."""
111 def on_enter( 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
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.
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 """
136class ValidateJsonHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
137 """Event handler for `SchemaValidator.validate_json`."""
139 def on_enter( 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
140 self,
141 input: str | bytes | bytearray,
142 *,
143 strict: bool | None = None,
144 context: dict[str, Any] | None = None,
145 self_instance: Any | None = None,
146 by_alias: bool | None = None,
147 by_name: bool | None = None,
148 ) -> None:
149 """Callback to be notified of validation start, and create an instance of the event handler.
151 Args:
152 input: The JSON data to be validated.
153 strict: Whether to validate the object in strict mode.
154 context: The context to use for validation, this is passed to functional validators.
155 self_instance: An instance of a model to set attributes on from validation, this is used when running
156 validation from the `__init__` method of a model.
157 by_alias: Whether to use the field's alias to match the input data to an attribute.
158 by_name: Whether to use the field's name to match the input data to an attribute.
159 """
162StringInput: TypeAlias = 'dict[str, StringInput]' 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
165class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
166 """Event handler for `SchemaValidator.validate_strings`."""
168 def on_enter( 1EFstuvabcderfGHwxyzghijklIJABCDmnopq
169 self,
170 input: StringInput,
171 *,
172 strict: bool | None = None,
173 context: dict[str, Any] | None = None,
174 by_alias: bool | None = None,
175 by_name: bool | None = None,
176 ) -> None:
177 """Callback to be notified of validation start, and create an instance of the event handler.
179 Args:
180 input: The string data to be validated.
181 strict: Whether to validate the object in strict mode.
182 context: The context to use for validation, this is passed to functional validators.
183 by_alias: Whether to use the field's alias to match the input data to an attribute.
184 by_name: Whether to use the field's name to match the input data to an attribute.
185 """