Coverage for pydantic/plugin/__init__.py: 85.00%
20 statements
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-13 19:35 +0000
« prev ^ index » next coverage.py v7.6.12, created at 2025-02-13 19:35 +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 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
9from typing import Any, Callable, Literal, NamedTuple 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
11from pydantic_core import CoreConfig, CoreSchema, ValidationError 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
12from typing_extensions import Protocol, TypeAlias 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
14__all__ = ( 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
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]' 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
28class SchemaTypePath(NamedTuple): 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
29 """Path defining where `schema_type` was defined, or where `TypeAdapter` was called."""
31 module: str 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
32 name: str 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
35SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call'] 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
38class PydanticPluginProtocol(Protocol): 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
39 """Protocol defining the interface for Pydantic plugins.""" 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
41 def new_schema_validator( 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
42 self,
43 schema: CoreSchema, 1abcdrefghijklmnopq
44 schema_type: Any, 1abcdrefghijklmnopq
45 schema_type_path: SchemaTypePath, 1abcdrefghijklmnopq
46 schema_kind: SchemaKind, 1abcdrefghijklmnopq
47 config: CoreConfig | None, 1abcdrefghijklmnopq
48 plugin_settings: dict[str, object], 1abcdrefghijklmnopq
49 ) -> tuple[ 1abcdrefghijklmnopq
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): 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
74 """Base class for plugin callbacks protocols. 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
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] 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
81 """`on_enter` is changed to be more specific on all subclasses""" 1stuvabcdewxyzfghiABjklmCDEFnopq
83 def on_success(self, result: Any) -> None: 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
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: 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
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: 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
100 """Callback to be notified of validation exceptions.
102 Args:
103 exception: The exception raised during validation.
104 """
105 return
108class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
109 """Event handler for `SchemaValidator.validate_python`."""
111 def on_enter( 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
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 ) -> None:
120 """Callback to be notified of validation start, and create an instance of the event handler.
122 Args:
123 input: The input to be validated.
124 strict: Whether to validate the object in strict mode.
125 from_attributes: Whether to validate objects as inputs by extracting attributes.
126 context: The context to use for validation, this is passed to functional validators.
127 self_instance: An instance of a model to set attributes on from validation, this is used when running
128 validation from the `__init__` method of a model.
129 """
130 pass
133class ValidateJsonHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
134 """Event handler for `SchemaValidator.validate_json`."""
136 def on_enter( 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
137 self,
138 input: str | bytes | bytearray,
139 *,
140 strict: bool | None = None,
141 context: dict[str, Any] | None = None,
142 self_instance: Any | None = None,
143 ) -> None:
144 """Callback to be notified of validation start, and create an instance of the event handler.
146 Args:
147 input: The JSON data to be validated.
148 strict: Whether to validate the object in strict mode.
149 context: The context to use for validation, this is passed to functional validators.
150 self_instance: An instance of a model to set attributes on from validation, this is used when running
151 validation from the `__init__` method of a model.
152 """
153 pass
156StringInput: TypeAlias = 'dict[str, StringInput]' 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
159class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol): 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
160 """Event handler for `SchemaValidator.validate_strings`."""
162 def on_enter( 1GHstuvabcdreIJwxyzfghiKABjklmLMCDEFnopq
163 self, input: StringInput, *, strict: bool | None = None, context: dict[str, Any] | None = None
164 ) -> None:
165 """Callback to be notified of validation start, and create an instance of the event handler.
167 Args:
168 input: The string data to be validated.
169 strict: Whether to validate the object in strict mode.
170 context: The context to use for validation, this is passed to functional validators.
171 """
172 pass