Core functionality for Pydantic validation and serialization
npx @tessl/cli install tessl/pypi-pydantic-core@2.39.00
# Pydantic Core
1
2
Pydantic Core is a high-performance validation and serialization library implemented in Rust with Python bindings. It provides the foundational validation engine for Pydantic V2, offering approximately 17x performance improvements over pure Python implementations. The library handles schema-based validation, JSON parsing and serialization, error handling with detailed validation messages, and support for complex data types.
3
4
## Package Information
5
6
- **Package Name**: pydantic-core
7
- **Language**: Rust with Python bindings
8
- **Installation**: `pip install pydantic-core`
9
10
## Core Imports
11
12
```python
13
import pydantic_core
14
```
15
16
Main classes and functions:
17
18
```python
19
from pydantic_core import (
20
SchemaValidator,
21
SchemaSerializer,
22
ValidationError,
23
from_json,
24
to_json,
25
to_jsonable_python
26
)
27
```
28
29
Schema building functions:
30
31
```python
32
from pydantic_core.core_schema import (
33
CoreConfig,
34
str_schema,
35
int_schema,
36
dict_schema,
37
list_schema,
38
model_schema
39
)
40
```
41
42
## Basic Usage
43
44
```python
45
from pydantic_core import SchemaValidator, ValidationError
46
from pydantic_core.core_schema import str_schema, int_schema, dict_schema
47
48
# Define a schema for user data
49
user_schema = dict_schema({
50
'name': str_schema(min_length=1),
51
'age': int_schema(ge=0, le=120),
52
'email': str_schema()
53
})
54
55
# Create a validator
56
validator = SchemaValidator(user_schema)
57
58
# Validate valid data
59
valid_data = {'name': 'John', 'age': 30, 'email': 'john@example.com'}
60
result = validator.validate_python(valid_data)
61
print(result) # {'name': 'John', 'age': 30, 'email': 'john@example.com'}
62
63
# Handle validation errors
64
try:
65
invalid_data = {'name': '', 'age': -5, 'email': 'invalid'}
66
validator.validate_python(invalid_data)
67
except ValidationError as e:
68
print(e.error_count()) # Number of errors
69
for error in e.errors():
70
print(f"Field: {error['loc']}, Error: {error['msg']}")
71
```
72
73
## Architecture
74
75
Pydantic Core is built around several key concepts:
76
77
- **Schema Definition**: Use schema builder functions to define validation rules
78
- **Validators**: SchemaValidator instances that validate data against schemas
79
- **Serializers**: SchemaSerializer instances that convert validated data to various formats
80
- **Error Handling**: Detailed ValidationError exceptions with location and context information
81
- **JSON Processing**: High-performance JSON parsing and serialization functions
82
83
The Rust implementation provides the performance-critical validation logic while maintaining a Python-friendly API through PyO3 bindings.
84
85
## Capabilities
86
87
### Core Validation and Serialization
88
89
Main classes for validating data against schemas and serializing validated data to various output formats including JSON, Python dictionaries, and custom formats.
90
91
```python { .api }
92
class SchemaValidator:
93
def __init__(self, schema: CoreSchema, config: CoreConfig = None): ...
94
def validate_python(self, value, *, strict=None, from_attributes=None, context=None): ...
95
def validate_json(self, json_data, *, strict=None, context=None): ...
96
def validate_strings(self, str_data, *, strict=None, context=None): ...
97
98
class SchemaSerializer:
99
def __init__(self, schema: CoreSchema, config: CoreConfig = None): ...
100
def to_python(self, value, *, mode='python', by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False): ...
101
def to_json(self, value, *, indent=None, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False): ...
102
```
103
104
[Validation and Serialization](./validation-serialization.md)
105
106
### Schema Building
107
108
Comprehensive set of functions for building validation schemas for all Python data types, from basic types like strings and integers to complex structures like models and typed dictionaries.
109
110
```python { .api }
111
def str_schema(*, min_length=None, max_length=None, pattern=None, strip_whitespace=False, to_lower=False, to_upper=False): ...
112
def int_schema(*, gt=None, ge=None, lt=None, le=None, multiple_of=None): ...
113
def dict_schema(keys_schema=None, values_schema=None, *, min_length=None, max_length=None): ...
114
def list_schema(items_schema, *, min_length=None, max_length=None): ...
115
def model_schema(cls_name: str, schema: dict, *, model_name=None, config=None, custom_init=None, root_model=False, post_init=None, ref=None, serialization=None, extra_validator=None): ...
116
```
117
118
[Schema Building](./schema-building.md)
119
120
### JSON Processing
121
122
High-performance JSON parsing and serialization functions with extensive configuration options for handling edge cases, infinity/NaN values, and custom serialization formats.
123
124
```python { .api }
125
def from_json(data, *, allow_inf_nan=True, cache_strings='all', allow_partial='off'): ...
126
def to_json(obj, *, indent=None, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False) -> bytes: ...
127
def to_jsonable_python(obj, *, fallback=None, serialize_as_any=False, when_used='json'): ...
128
129
# Utility functions
130
def list_all_errors() -> list[ErrorTypeInfo]: ...
131
132
# Build information
133
__version__: str
134
build_profile: str
135
build_info: str
136
_recursion_limit: int
137
```
138
139
[JSON Processing](./json-processing.md)
140
141
### Error Handling
142
143
Comprehensive error handling system with detailed error information, location tracking, and support for custom error messages and error type definitions.
144
145
```python { .api }
146
class ValidationError(ValueError):
147
def errors(self) -> list[ErrorDetails]: ...
148
def error_count(self) -> int: ...
149
def __str__(self) -> str: ...
150
151
class PydanticCustomError(ValueError):
152
def __init__(self, error_type: str, message_template: str, context: dict = None): ...
153
154
class PydanticKnownError(ValueError):
155
def __init__(self, error_type: ErrorType, context: dict = None): ...
156
```
157
158
[Error Handling](./error-handling.md)
159
160
### URL and Network Types
161
162
Specialized validation and handling for URLs and multi-host URLs commonly used in database connections and network configurations.
163
164
```python { .api }
165
class Url:
166
scheme: str
167
username: str | None
168
password: str | None
169
host: str | None
170
port: int | None
171
path: str | None
172
query: str | None
173
fragment: str | None
174
175
class MultiHostUrl:
176
scheme: str
177
username: str | None
178
password: str | None
179
hosts: list[MultiHostHost]
180
path: str | None
181
query: str | None
182
fragment: str | None
183
```
184
185
[URL and Network Types](./url-network.md)
186
187
### Special Values and Utilities
188
189
Sentinel values, utility classes, and helper functions for advanced validation scenarios and edge case handling.
190
191
```python { .api }
192
# Sentinel values
193
PydanticUndefined: PydanticUndefinedType
194
MISSING: Sentinel
195
UNSET: Sentinel # Alias for MISSING
196
197
# Utility classes
198
class Some:
199
def __init__(self, value): ...
200
201
class ArgsKwargs:
202
def __init__(self, args: tuple, kwargs: dict): ...
203
204
# Marker classes
205
class PydanticOmit: ...
206
class PydanticUseDefault: ...
207
```
208
209
[Special Values and Utilities](./special-values.md)
210
211
## Types
212
213
```python { .api }
214
# Core type aliases
215
CoreSchema = Union[AnySchema, NoneSchema, BoolSchema, IntSchema, FloatSchema, StrSchema, BytesSchema, DateSchema, TimeSchema, DatetimeSchema, TimedeltaSchema, LiteralSchema, EnumSchema, IsInstanceSchema, CallableSchema, ListSchema, TupleSchema, SetSchema, FrozensetSchema, GeneratorSchema, DictSchema, AfterValidatorFunctionSchema, BeforeValidatorFunctionSchema, WrapValidatorFunctionSchema, PlainValidatorFunctionSchema, WithInfoAfterValidatorFunctionSchema, WithInfoBeforeValidatorFunctionSchema, WithInfoWrapValidatorFunctionSchema, WithInfoPlainValidatorFunctionSchema, ChainSchema, LaxOrStrictSchema, UnionSchema, TaggedUnionSchema, ModelSchema, ModelFieldsSchema, DataclassSchema, TypedDictSchema, CallableSchema, ArgumentsSchema, CustomErrorSchema, JsonSchema, UrlSchema, MultiHostUrlSchema, DecimalSchema, UuidSchema, NoInfoSchema, CustomSchema, NullableSchema, DefaultSchema, WithInfoSchema, DefinitionsSchema, DefinitionReferenceSchema, ValidatorSchema, SerializerSchema, JsonOrPythonSchema]
216
217
CoreSchemaType = Literal[
218
'any', 'none', 'bool', 'int', 'float', 'str', 'bytes', 'date', 'time',
219
'datetime', 'timedelta', 'frozenset', 'list', 'dict', 'function',
220
'generator', 'tuple', 'set', 'is_instance', 'callable', 'literal',
221
'enum', 'union', 'tagged_union', 'chain', 'model', 'model_fields',
222
'dataclass', 'typed_dict', 'json', 'url', 'multi_host_url', 'uuid',
223
'decimal', 'no_info', 'custom', 'arguments', 'nullable', 'default',
224
'with_info', 'definitions', 'definition_ref', 'validator',
225
'serializer', 'lax_or_strict', 'json_or_python'
226
]
227
228
# Error and context types
229
ErrorDetails = TypedDict('ErrorDetails', {
230
'type': str,
231
'loc': tuple[int | str, ...],
232
'msg': str,
233
'input': Any,
234
'ctx': NotRequired[dict[str, Any]],
235
'url': NotRequired[str]
236
})
237
238
InitErrorDetails = TypedDict('InitErrorDetails', {
239
'type': Union[str, PydanticCustomError],
240
'loc': NotRequired[tuple[int | str, ...]],
241
'input': Any,
242
'ctx': NotRequired[dict[str, Any]]
243
})
244
245
ErrorTypeInfo = TypedDict('ErrorTypeInfo', {
246
'type': ErrorType,
247
'message_template_python': str,
248
'example_message_python': str,
249
'message_template_json': NotRequired[str],
250
'example_message_json': NotRequired[str],
251
'example_context': dict[str, Any] | None
252
})
253
254
MultiHostHost = TypedDict('MultiHostHost', {
255
'username': str | None,
256
'password': str | None,
257
'host': str | None,
258
'port': int | None
259
})
260
```