Coverage for pydantic/plugin/__init__.py: 85.00%
20 statements
« prev ^ index » next coverage.py v7.8.1, created at 2025-05-22 20:36 +0000
« prev ^ index » next coverage.py v7.8.1, created at 2025-05-22 20:36 +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 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
9from typing import Any, Callable, Literal, NamedTuple 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
11from pydantic_core import CoreConfig, CoreSchema, ValidationError 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
12from typing_extensions import Protocol, TypeAlias 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
14__all__ = ( 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
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]' 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
28class SchemaTypePath(NamedTuple): 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
29 """Path defining where `schema_type` was defined, or where `TypeAdapter` was called."""
31 module: str 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
32 name: str 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
35SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call'] 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
38class PydanticPluginProtocol(Protocol): 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
39 """Protocol defining the interface for Pydantic plugins.""" 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
41 def new_schema_validator( 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
42 self,
43 schema: CoreSchema, 1abcdeufghijklmnopqrst
44 schema_type: Any, 1abcdeufghijklmnopqrst
45 schema_type_path: SchemaTypePath, 1abcdeufghijklmnopqrst
46 schema_kind: SchemaKind, 1abcdeufghijklmnopqrst
47 config: CoreConfig | None, 1abcdeufghijklmnopqrst
48 plugin_settings: dict[str, object], 1abcdeufghijklmnopqrst
49 ) -> tuple[ 1abcdeufghijklmnopqrst
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): 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
74 """Base class for plugin callbacks protocols. 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
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] 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
81 """`on_enter` is changed to be more specific on all subclasses""" 1vwxyabcdefzABCghijkDElmnoFGHIpqrst
83 def on_success(self, result: Any) -> None: 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
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: 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
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: 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
100 """Callback to be notified of validation exceptions.
102 Args:
103 exception: The exception raised during validation.
104 """
105 return
108class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
109 """Event handler for `SchemaValidator.validate_python`."""
111 def on_enter( 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
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 """
134 pass
137class ValidateJsonHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
138 """Event handler for `SchemaValidator.validate_json`."""
140 def on_enter( 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
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.
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
164StringInput: TypeAlias = 'dict[str, StringInput]' 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
167class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
168 """Event handler for `SchemaValidator.validate_strings`."""
170 def on_enter( 1JKvwxyabcdeufLMzABCghijkNDElmnoOPFGHIpqrst
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.
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