1"""Convert python types to pydantic-core schema."""
2
3from __future__ import annotations as _annotations
4
5import collections.abc
6import dataclasses
7import datetime
8import inspect
9import os
10import pathlib
11import re
12import sys
13import typing
14import warnings
15from collections.abc import Callable, Generator, Iterable, Iterator, Mapping
16from contextlib import contextmanager
17from copy import copy
18from decimal import Decimal
19from enum import Enum
20from fractions import Fraction
21from functools import partial
22from inspect import Parameter, _ParameterKind
23from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
24from itertools import chain
25from operator import attrgetter
26from types import EllipsisType, FunctionType, GenericAlias, LambdaType, MethodType, NoneType
27from typing import (
28 TYPE_CHECKING,
29 Any,
30 ClassVar,
31 ForwardRef,
32 Literal,
33 TypeAlias,
34 TypeVar,
35 cast,
36 overload,
37)
38from uuid import UUID
39from zoneinfo import ZoneInfo
40
41import typing_extensions
42from pydantic_core import (
43 MISSING,
44 CoreSchema,
45 MultiHostUrl,
46 PydanticCustomError,
47 PydanticSerializationUnexpectedValue,
48 PydanticUndefined,
49 Url,
50 core_schema,
51 to_jsonable_python,
52)
53from typing_extensions import ( # noqa: UP035 (for `get_args` and `get_origin`)
54 TypeAliasType,
55 get_args,
56 get_origin,
57 is_typeddict,
58)
59from typing_inspection import typing_objects
60from typing_inspection.introspection import AnnotationSource, get_literal_values, is_union_origin
61
62from ..aliases import AliasChoices, AliasPath
63from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
64from ..config import ConfigDict, JsonDict, JsonEncoder, JsonSchemaExtraCallable
65from ..errors import (
66 PydanticForbiddenQualifier,
67 PydanticInvalidForJsonSchema,
68 PydanticSchemaGenerationError,
69 PydanticUndefinedAnnotation,
70 PydanticUserError,
71)
72from ..functional_validators import AfterValidator, BeforeValidator, FieldValidatorModes, PlainValidator, WrapValidator
73from ..json_schema import JsonSchemaValue
74from ..version import version_short
75from ..warnings import (
76 ArbitraryTypeWarning,
77 PydanticDeprecatedSince20,
78 TypedDictExtraConfigWarning,
79 UnsupportedFieldAttributeWarning,
80)
81from . import _decorators, _discriminated_union, _known_annotated_metadata, _repr, _type_refs, _typing_extra
82from ._config import ConfigWrapper, ConfigWrapperStack
83from ._core_metadata import CoreMetadata, update_core_metadata
84from ._core_utils import (
85 get_ref,
86 is_list_like_schema_with_items_schema,
87)
88from ._decorators import (
89 Decorator,
90 DecoratorInfos,
91 FieldSerializerDecoratorInfo,
92 FieldValidatorDecoratorInfo,
93 ModelSerializerDecoratorInfo,
94 ModelValidatorDecoratorInfo,
95 RootValidatorDecoratorInfo,
96 ValidatorDecoratorInfo,
97 get_attribute_from_bases,
98 inspect_field_serializer,
99 inspect_model_serializer,
100 inspect_validator,
101 mro,
102)
103from ._docs_extraction import extract_docstrings_from_cls
104from ._fields import (
105 collect_dataclass_fields,
106 rebuild_dataclass_fields,
107 rebuild_model_fields,
108 takes_validated_data_argument,
109 update_field_from_config,
110)
111from ._forward_ref import PydanticRecursiveRef
112from ._generics import get_model_typevars_map, get_standard_typevars_map, replace_types
113from ._import_utils import import_cached_base_model, import_cached_field_info
114from ._mock_val_ser import MockCoreSchema
115from ._namespace_utils import NamespacesTuple, NsResolver
116from ._schema_gather import MissingDefinitionError, gather_schemas_for_cleaning
117from ._schema_generation_shared import CallbackGetCoreSchemaHandler
118from ._utils import lenient_issubclass, smart_deepcopy
119
120if TYPE_CHECKING:
121 from ..fields import ComputedFieldInfo, FieldInfo
122 from ..main import BaseModel
123 from ..types import Discriminator
124 from ._dataclasses import StandardDataclass
125 from ._schema_generation_shared import GetJsonSchemaFunction
126
127if sys.version_info >= (3, 15):
128 from builtins import frozendict
129
130_SUPPORTS_TYPEDDICT = sys.version_info >= (3, 12)
131
132FieldDecoratorInfo: TypeAlias = ValidatorDecoratorInfo | FieldValidatorDecoratorInfo | FieldSerializerDecoratorInfo
133FieldDecoratorInfoType = TypeVar('FieldDecoratorInfoType', bound=FieldDecoratorInfo)
134AnyFieldDecorator = (
135 Decorator[ValidatorDecoratorInfo] | Decorator[FieldValidatorDecoratorInfo] | Decorator[FieldSerializerDecoratorInfo]
136)
137
138ModifyCoreSchemaWrapHandler: TypeAlias = GetCoreSchemaHandler
139GetCoreSchemaFunction: TypeAlias = Callable[[Any, ModifyCoreSchemaWrapHandler], core_schema.CoreSchema]
140ParametersCallback: TypeAlias = Callable[[int, str, Any], Literal['skip'] | None]
141
142TUPLE_TYPES: list[type] = [typing.Tuple, tuple] # noqa: UP006
143
144# Note: This does not play very well with type checkers. For example,
145# `a: LambdaType = lambda x: x` will raise a type error by Pyright.
146ValidateCallSupportedTypes: TypeAlias = LambdaType | FunctionType | MethodType | partial
147
148
149VALIDATE_CALL_SUPPORTED_TYPES = get_args(ValidateCallSupportedTypes)
150UNSUPPORTED_STANDALONE_FIELDINFO_ATTRIBUTES: list[tuple[str, Any]] = [
151 ('alias', None),
152 ('validation_alias', None),
153 ('serialization_alias', None),
154 # will be set if any alias is set, so disable it to avoid double warnings:
155 # 'alias_priority',
156 ('default', PydanticUndefined),
157 ('default_factory', None),
158 ('exclude', None),
159 ('deprecated', None),
160 ('repr', True),
161 ('validate_default', None),
162 ('frozen', None),
163 ('init', None),
164 ('init_var', None),
165 ('kw_only', None),
166]
167"""`FieldInfo` attributes (and their default value) that can't be used outside of a model (e.g. in a type adapter or a PEP 695 type alias)."""
168
169_mode_to_validator: dict[
170 FieldValidatorModes, type[BeforeValidator | AfterValidator | PlainValidator | WrapValidator]
171] = {'before': BeforeValidator, 'after': AfterValidator, 'plain': PlainValidator, 'wrap': WrapValidator}
172
173
174def check_validator_fields_against_field_name(
175 info: FieldDecoratorInfo,
176 field: str,
177) -> bool:
178 """Check if field name is in validator fields.
179
180 Args:
181 info: The field info.
182 field: The field name to check.
183
184 Returns:
185 `True` if field name is in validator fields, `False` otherwise.
186 """
187 fields = info.fields
188 return '*' in fields or field in fields
189
190
191def check_decorator_fields_exist(decorators: Iterable[AnyFieldDecorator], fields: Iterable[str]) -> None:
192 """Check if the defined fields in decorators exist in `fields` param.
193
194 It ignores the check for a decorator if the decorator has `*` as field or `check_fields=False`.
195
196 Args:
197 decorators: An iterable of decorators.
198 fields: An iterable of fields name.
199
200 Raises:
201 PydanticUserError: If one of the field names does not exist in `fields` param.
202 """
203 fields = set(fields)
204 for dec in decorators:
205 if '*' in dec.info.fields:
206 continue
207 if dec.info.check_fields is False:
208 continue
209 for field in dec.info.fields:
210 if field not in fields:
211 raise PydanticUserError(
212 f'Decorators defined with incorrect fields: {dec.cls_ref}.{dec.cls_var_name}'
213 " (use check_fields=False if you're inheriting from the model and intended this)",
214 code='decorator-missing-field',
215 )
216
217
218def filter_field_decorator_info_by_field(
219 validator_functions: Iterable[Decorator[FieldDecoratorInfoType]], field: str
220) -> list[Decorator[FieldDecoratorInfoType]]:
221 return [dec for dec in validator_functions if check_validator_fields_against_field_name(dec.info, field)]
222
223
224def apply_each_item_validators(
225 schema: core_schema.CoreSchema,
226 each_item_validators: list[Decorator[ValidatorDecoratorInfo]],
227) -> core_schema.CoreSchema:
228 # This V1 compatibility shim should eventually be removed
229
230 # fail early if each_item_validators is empty
231 if not each_item_validators:
232 return schema
233
234 # push down any `each_item=True` validators
235 # note that this won't work for any Annotated types that get wrapped by a function validator
236 # but that's okay because that didn't exist in V1
237 if schema['type'] == 'nullable':
238 schema['schema'] = apply_each_item_validators(schema['schema'], each_item_validators)
239 return schema
240 elif schema['type'] == 'missing-sentinel' and 'schema' in schema:
241 schema['schema'] = apply_each_item_validators(schema['schema'], each_item_validators)
242 return schema
243 elif schema['type'] == 'tuple':
244 if (variadic_item_index := schema.get('variadic_item_index')) is not None:
245 schema['items_schema'][variadic_item_index] = apply_validators(
246 schema['items_schema'][variadic_item_index],
247 each_item_validators,
248 )
249 elif is_list_like_schema_with_items_schema(schema):
250 inner_schema = schema.get('items_schema', core_schema.any_schema())
251 schema['items_schema'] = apply_validators(inner_schema, each_item_validators)
252 elif schema['type'] == 'dict':
253 inner_schema = schema.get('values_schema', core_schema.any_schema())
254 schema['values_schema'] = apply_validators(inner_schema, each_item_validators)
255 else:
256 raise TypeError(
257 f'`@validator(..., each_item=True)` cannot be applied to fields with a schema of {schema["type"]}'
258 )
259 return schema
260
261
262def _extract_json_schema_info_from_field_info(
263 info: FieldInfo | ComputedFieldInfo,
264) -> tuple[JsonDict | None, JsonDict | JsonSchemaExtraCallable | None]:
265 json_schema_updates = {
266 'title': info.title,
267 'description': info.description,
268 'deprecated': bool(info.deprecated) or info.deprecated == '' or None,
269 'examples': to_jsonable_python(info.examples),
270 }
271 json_schema_updates = {k: v for k, v in json_schema_updates.items() if v is not None}
272 return (json_schema_updates or None, info.json_schema_extra)
273
274
275JsonEncoders = dict[type[Any], JsonEncoder]
276
277
278def _add_custom_serialization_from_json_encoders(
279 json_encoders: JsonEncoders | None, tp: Any, schema: CoreSchema
280) -> CoreSchema:
281 """Iterate over the json_encoders and add the first matching encoder to the schema.
282
283 Args:
284 json_encoders: A dictionary of types and their encoder functions.
285 tp: The type to check for a matching encoder.
286 schema: The schema to add the encoder to.
287 """
288 if not json_encoders:
289 return schema
290 if 'serialization' in schema:
291 return schema
292 # Check the class type and its superclasses for a matching encoder
293 # Decimal.__class__.__mro__ (and probably other cases) doesn't include Decimal itself
294 # if the type is a GenericAlias (e.g. from list[int]) we need to use __class__ instead of .__mro__
295 for base in (tp, *getattr(tp, '__mro__', tp.__class__.__mro__)[:-1]):
296 encoder = json_encoders.get(base)
297 if encoder is None:
298 continue
299
300 warnings.warn(
301 f'`json_encoders` is deprecated. See https://pydantic.dev/docs/validation/{version_short()}/concepts/serialization/#custom-serializers for alternatives',
302 PydanticDeprecatedSince20,
303 )
304
305 # TODO: in theory we should check that the schema accepts a serialization key
306 schema['serialization'] = core_schema.plain_serializer_function_ser_schema(encoder, when_used='json')
307 return schema
308
309 return schema
310
311
312GENERATE_SCHEMA_ERRORS = (
313 PydanticForbiddenQualifier,
314 PydanticInvalidForJsonSchema,
315 PydanticSchemaGenerationError,
316 PydanticUndefinedAnnotation,
317)
318"""Errors raised during core schema generation. This does *not* include `InvalidSchemaError`, which is raised during schema cleaning."""
319
320
321def _get_typed_dict_extra_items(typed_dict_cls: type[Any]) -> tuple[bool, Any, bool]:
322 """Return whether the TypedDict class is closed, the type of its extra items and whether
323 they are read-only (as per PEP 728).
324
325 The `__closed__` and `__extra_items__` attributes only reflect the arguments passed to the class itself,
326 so the first class in the (virtual) MRO explicitly specifying one of them is used.
327 `extra_items=Never` is normalized to `closed=True`, and the `ReadOnly` qualifier is stripped.
328 """
329 for base in mro(typed_dict_cls):
330 # `__closed__` is `None` when not specified:
331 closed = base.__dict__.get('__closed__')
332 extra_items = base.__dict__.get('__extra_items__', typing_extensions.NoExtraItems)
333 if closed is not None or not typing_objects.is_noextraitems(extra_items):
334 break
335 else:
336 return False, typing_extensions.NoExtraItems, False
337
338 if closed is not None:
339 # `closed` and `extra_items` can't be used together:
340 return closed, typing_extensions.NoExtraItems, False
341
342 readonly = typing_objects.is_readonly(get_origin(extra_items))
343 if readonly:
344 extra_items = get_args(extra_items)[0]
345 # TODO: `Never` wrapped in a type alias (e.g. `type NoExtras = Never`) or in `Annotated` isn't detected here,
346 # and fails during schema generation. Unwrapping should only apply to this check (to preserve alias handling).
347 if typing_objects.is_never(extra_items):
348 return True, typing_extensions.NoExtraItems, False
349 return False, extra_items, readonly
350
351
352class InvalidSchemaError(Exception):
353 """The core schema is invalid."""
354
355
356class GenerateSchema:
357 """Generate core schema for a Pydantic model, dataclass and types like `str`, `datetime`, ... ."""
358
359 __slots__ = (
360 '_config_wrapper_stack',
361 '_ns_resolver',
362 '_typevars_map',
363 'field_name_stack',
364 'model_type_stack',
365 'defs',
366 )
367
368 def __init__(
369 self,
370 config_wrapper: ConfigWrapper,
371 ns_resolver: NsResolver | None = None,
372 typevars_map: Mapping[TypeVar, Any] | None = None,
373 ) -> None:
374 # we need a stack for recursing into nested models
375 self._config_wrapper_stack = ConfigWrapperStack(config_wrapper)
376 self._ns_resolver = ns_resolver or NsResolver()
377 self._typevars_map = typevars_map
378 self.field_name_stack = _FieldNameStack()
379 self.model_type_stack = _ModelTypeStack()
380 self.defs = _Definitions()
381
382 # The handler lambdas take the `GenerateSchema` instance as their first argument, so that
383 # the dicts can be built once at class creation time and shared by all instances:
384 _handlers: ClassVar[dict[Any, Callable[[GenerateSchema, Any], core_schema.CoreSchema]]] = {
385 str: lambda self, obj: core_schema.str_schema(),
386 bytes: lambda self, obj: core_schema.bytes_schema(),
387 int: lambda self, obj: core_schema.int_schema(),
388 float: lambda self, obj: core_schema.float_schema(),
389 bool: lambda self, obj: core_schema.bool_schema(),
390 complex: lambda self, obj: core_schema.complex_schema(),
391 object: lambda self, obj: core_schema.any_schema(),
392 datetime.date: lambda self, obj: core_schema.date_schema(),
393 datetime.datetime: lambda self, obj: core_schema.datetime_schema(),
394 datetime.time: lambda self, obj: core_schema.time_schema(),
395 datetime.timedelta: lambda self, obj: core_schema.timedelta_schema(),
396 Decimal: lambda self, obj: core_schema.decimal_schema(),
397 UUID: lambda self, obj: core_schema.uuid_schema(),
398 Url: lambda self, obj: core_schema.url_schema(),
399 Fraction: lambda self, obj: core_schema.fraction_schema(),
400 MultiHostUrl: lambda self, obj: core_schema.multi_host_url_schema(),
401 None: lambda self, obj: core_schema.none_schema(),
402 NoneType: lambda self, obj: core_schema.none_schema(),
403 MISSING: lambda self, obj: core_schema.missing_sentinel_schema(),
404 EllipsisType: lambda self, obj: core_schema.ellipsis_schema(),
405 type: lambda self, obj: self._type_schema(),
406 dict: lambda self, obj: self._dict_schema(Any, Any),
407 tuple: lambda self, obj: self._tuple_schema(obj),
408 list: lambda self, obj: self._list_schema(Any),
409 set: lambda self, obj: self._set_schema(Any),
410 collections.abc.MutableSet: lambda self, obj: self._set_schema(Any),
411 frozenset: lambda self, obj: self._frozenset_schema(Any),
412 collections.abc.Set: lambda self, obj: self._frozenset_schema(Any),
413 collections.abc.MutableSequence: lambda self, obj: self._list_schema(Any),
414 collections.abc.Sequence: lambda self, obj: self._sequence_schema(Any),
415 collections.deque: lambda self, obj: self._deque_schema(Any),
416 collections.abc.Iterable: lambda self, obj: self._iterable_schema(obj),
417 collections.abc.Generator: lambda self, obj: self._iterable_schema(obj),
418 collections.abc.Mapping: lambda self, obj: self._mapping_schema(obj, Any, Any),
419 collections.abc.MutableMapping: lambda self, obj: self._mapping_schema(obj, Any, Any),
420 collections.OrderedDict: lambda self, obj: self._ordered_dict_schema(Any, Any),
421 collections.defaultdict: lambda self, obj: self._mapping_schema(obj, Any, Any),
422 collections.Counter: lambda self, obj: self._counter_schema(Any),
423 collections.abc.Callable: lambda self, obj: core_schema.callable_schema(),
424 collections.abc.Hashable: lambda self, obj: self._hashable_schema(),
425 IPv4Address: lambda self, obj: self._ip_schema(obj),
426 IPv4Interface: lambda self, obj: self._ip_schema(obj),
427 IPv4Network: lambda self, obj: self._ip_schema(obj),
428 IPv6Address: lambda self, obj: self._ip_schema(obj),
429 IPv6Interface: lambda self, obj: self._ip_schema(obj),
430 IPv6Network: lambda self, obj: self._ip_schema(obj),
431 os.PathLike: lambda self, obj: self._path_schema(obj, Any),
432 pathlib.Path: lambda self, obj: self._path_schema(obj, Any),
433 pathlib.PurePath: lambda self, obj: self._path_schema(obj, Any),
434 pathlib.PosixPath: lambda self, obj: self._path_schema(obj, Any),
435 pathlib.WindowsPath: lambda self, obj: self._path_schema(obj, Any),
436 pathlib.PurePosixPath: lambda self, obj: self._path_schema(obj, Any),
437 pathlib.PureWindowsPath: lambda self, obj: self._path_schema(obj, Any),
438 re.Pattern: lambda self, obj: self._pattern_schema(obj),
439 ZoneInfo: lambda self, obj: self._zoneinfo_schema(),
440 }
441
442 _generic_handlers: ClassVar[dict[Any, Callable[[GenerateSchema, Any], core_schema.CoreSchema]]] = {
443 tuple: lambda self, obj: self._tuple_schema(obj),
444 list: lambda self, obj: self._list_schema(self._get_first_arg_or_any(obj)),
445 dict: lambda self, obj: self._dict_schema(*self._get_first_two_args_or_any(obj)),
446 set: lambda self, obj: self._set_schema(self._get_first_arg_or_any(obj)),
447 frozenset: lambda self, obj: self._frozenset_schema(self._get_first_arg_or_any(obj)),
448 type: lambda self, obj: self._subclass_schema(obj),
449 collections.abc.MutableSequence: lambda self, obj: self._list_schema(self._get_first_arg_or_any(obj)),
450 collections.abc.MutableSet: lambda self, obj: self._set_schema(self._get_first_arg_or_any(obj)),
451 collections.abc.Set: lambda self, obj: self._frozenset_schema(self._get_first_arg_or_any(obj)),
452 collections.deque: lambda self, obj: self._deque_schema(self._get_first_arg_or_any(obj)),
453 collections.abc.Mapping: lambda self, obj: self._mapping_schema(
454 collections.abc.Mapping, *self._get_first_two_args_or_any(obj)
455 ),
456 collections.abc.MutableMapping: lambda self, obj: self._mapping_schema(
457 collections.abc.MutableMapping, *self._get_first_two_args_or_any(obj)
458 ),
459 collections.OrderedDict: lambda self, obj: self._ordered_dict_schema(*self._get_first_two_args_or_any(obj)),
460 collections.defaultdict: lambda self, obj: self._mapping_schema(
461 collections.defaultdict, *self._get_first_two_args_or_any(obj)
462 ),
463 collections.Counter: lambda self, obj: self._counter_schema(self._get_first_arg_or_any(obj)),
464 os.PathLike: lambda self, obj: self._path_schema(os.PathLike, self._get_first_arg_or_any(obj)),
465 pathlib.Path: lambda self, obj: self._path_schema(pathlib.Path, self._get_first_arg_or_any(obj)),
466 pathlib.PurePath: lambda self, obj: self._path_schema(pathlib.PurePath, self._get_first_arg_or_any(obj)),
467 pathlib.PosixPath: lambda self, obj: self._path_schema(pathlib.PosixPath, self._get_first_arg_or_any(obj)),
468 pathlib.WindowsPath: lambda self, obj: self._path_schema(pathlib.WindowsPath, self._get_first_arg_or_any(obj)),
469 pathlib.PurePosixPath: lambda self, obj: self._path_schema(
470 pathlib.PurePosixPath, self._get_first_arg_or_any(obj)
471 ),
472 pathlib.PureWindowsPath: lambda self, obj: self._path_schema(
473 pathlib.PureWindowsPath, self._get_first_arg_or_any(obj)
474 ),
475 collections.abc.Sequence: lambda self, obj: self._sequence_schema(self._get_first_arg_or_any(obj)),
476 collections.abc.Iterable: lambda self, obj: self._iterable_schema(obj),
477 collections.abc.Generator: lambda self, obj: self._iterable_schema(obj),
478 re.Pattern: lambda self, obj: self._pattern_schema(obj),
479 collections.abc.Callable: lambda self, obj: core_schema.callable_schema(),
480 }
481
482 if sys.version_info >= (3, 15):
483 _handlers[frozendict] = lambda self, obj: self._frozendict_schema(Any, Any)
484 _generic_handlers[frozendict] = lambda self, obj: self._frozendict_schema(*self._get_first_two_args_or_any(obj))
485
486 def __init_subclass__(cls) -> None:
487 super().__init_subclass__()
488 warnings.warn(
489 'Subclassing `GenerateSchema` is not supported. The API is highly subject to change in minor versions.',
490 UserWarning,
491 stacklevel=2,
492 )
493
494 @property
495 def _config_wrapper(self) -> ConfigWrapper:
496 return self._config_wrapper_stack.tail
497
498 @property
499 def _types_namespace(self) -> NamespacesTuple:
500 return self._ns_resolver.types_namespace
501
502 @property
503 def _arbitrary_types(self) -> bool:
504 return self._config_wrapper.arbitrary_types_allowed
505
506 # the following methods can be overridden but should be considered
507 # unstable / private APIs
508 def _list_schema(self, items_type: Any) -> CoreSchema:
509 return core_schema.list_schema(self.generate_schema(items_type))
510
511 def _dict_schema(self, keys_type: Any, values_type: Any) -> CoreSchema:
512 return core_schema.dict_schema(self.generate_schema(keys_type), self.generate_schema(values_type))
513
514 def _frozendict_schema(self, keys_type: Any, values_type: Any) -> CoreSchema:
515 return core_schema.frozendict_schema(self.generate_schema(keys_type), self.generate_schema(values_type))
516
517 def _ordered_dict_schema(self, keys_type: Any, values_type: Any) -> CoreSchema:
518 return core_schema.ordered_dict_schema(self.generate_schema(keys_type), self.generate_schema(values_type))
519
520 def _counter_schema(self, keys_type: Any) -> CoreSchema:
521 return core_schema.counter_schema(self.generate_schema(keys_type), core_schema.int_schema())
522
523 def _set_schema(self, items_type: Any) -> CoreSchema:
524 return core_schema.set_schema(self.generate_schema(items_type))
525
526 def _frozenset_schema(self, items_type: Any) -> CoreSchema:
527 return core_schema.frozenset_schema(self.generate_schema(items_type))
528
529 def _enum_schema(self, enum_type: type[Enum]) -> CoreSchema:
530 cases: list[Any] = list(enum_type.__members__.values())
531
532 enum_ref = _type_refs.enum_type_ref(enum_type)
533 description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__)
534 if (
535 description == 'An enumeration.'
536 ): # This is the default value provided by enum.EnumMeta.__new__; don't use it
537 description = None
538 js_updates = {'title': enum_type.__name__, 'description': description}
539 js_updates = {k: v for k, v in js_updates.items() if v is not None}
540
541 sub_type: Literal['str', 'int', 'float'] | None = None
542 if issubclass(enum_type, int):
543 sub_type = 'int'
544 value_ser_type: core_schema.SerSchema = core_schema.simple_ser_schema('int')
545 elif issubclass(enum_type, str):
546 # this handles `StrEnum` (3.11 only), and also `Foobar(str, Enum)`
547 sub_type = 'str'
548 value_ser_type = core_schema.simple_ser_schema('str')
549 elif issubclass(enum_type, float):
550 sub_type = 'float'
551 value_ser_type = core_schema.simple_ser_schema('float')
552 else:
553 # TODO this is an ugly hack, how do we trigger an Any schema for serialization?
554 value_ser_type = core_schema.plain_serializer_function_ser_schema(lambda x: x)
555
556 if cases:
557
558 def get_json_schema(schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue:
559 json_schema = handler(schema)
560 original_schema = handler.resolve_ref_schema(json_schema)
561 original_schema.update(js_updates)
562 return json_schema
563
564 enum_schema = core_schema.enum_schema(
565 enum_type,
566 cases,
567 sub_type=sub_type,
568 ref=enum_ref,
569 metadata={'pydantic_js_functions': [get_json_schema]},
570 )
571
572 if self._config_wrapper.use_enum_values:
573 enum_schema = core_schema.no_info_after_validator_function(
574 attrgetter('value'), enum_schema, serialization=value_ser_type
575 )
576
577 return enum_schema
578
579 else:
580
581 def get_json_schema_no_cases(_, handler: GetJsonSchemaHandler) -> JsonSchemaValue:
582 json_schema = handler(core_schema.enum_schema(enum_type, cases, sub_type=sub_type, ref=enum_ref))
583 original_schema = handler.resolve_ref_schema(json_schema)
584 original_schema.update(js_updates)
585 return json_schema
586
587 # Use an isinstance check for enums with no cases.
588 # The most important use case for this is creating TypeVar bounds for generics that should
589 # be restricted to enums. This is more consistent than it might seem at first, since you can only
590 # subclass enum.Enum (or subclasses of enum.Enum) if all parent classes have no cases.
591 # We use the get_json_schema function when an Enum subclass has been declared with no cases
592 # so that we can still generate a valid json schema.
593 return core_schema.is_instance_schema(
594 enum_type,
595 metadata={'pydantic_js_functions': [get_json_schema_no_cases]},
596 )
597
598 def _ip_schema(self, tp: Any) -> CoreSchema:
599 from ._validators import IP_VALIDATOR_LOOKUP, IpType
600
601 ip_type_json_schema_format: dict[type[IpType], str] = {
602 IPv4Address: 'ipv4',
603 IPv4Network: 'ipv4network',
604 IPv4Interface: 'ipv4interface',
605 IPv6Address: 'ipv6',
606 IPv6Network: 'ipv6network',
607 IPv6Interface: 'ipv6interface',
608 }
609
610 def ser_ip(ip: Any, info: core_schema.SerializationInfo) -> str | IpType:
611 if not isinstance(ip, (tp, str)):
612 raise PydanticSerializationUnexpectedValue(
613 f"Expected `{tp}` but got `{type(ip)}` with value `'{ip}'` - serialized value may not be as expected."
614 )
615 if info.mode == 'python':
616 return ip
617 return str(ip)
618
619 return core_schema.lax_or_strict_schema(
620 lax_schema=core_schema.no_info_plain_validator_function(IP_VALIDATOR_LOOKUP[tp]),
621 strict_schema=core_schema.json_or_python_schema(
622 json_schema=core_schema.no_info_after_validator_function(tp, core_schema.str_schema()),
623 python_schema=core_schema.is_instance_schema(tp),
624 ),
625 serialization=core_schema.plain_serializer_function_ser_schema(ser_ip, info_arg=True, when_used='always'),
626 metadata={
627 'pydantic_js_functions': [lambda _1, _2: {'type': 'string', 'format': ip_type_json_schema_format[tp]}]
628 },
629 )
630
631 def _path_schema(self, tp: Any, path_type: Any) -> CoreSchema:
632 if tp is os.PathLike and (path_type not in {str, bytes} and not typing_objects.is_any(path_type)):
633 raise PydanticUserError(
634 '`os.PathLike` can only be used with `str`, `bytes` or `Any`', code='schema-for-unknown-type'
635 )
636
637 path_constructor = pathlib.PurePath if tp is os.PathLike else tp
638 strict_inner_schema = (
639 core_schema.bytes_schema(strict=True) if (path_type is bytes) else core_schema.str_schema(strict=True)
640 )
641 lax_inner_schema = core_schema.bytes_schema() if (path_type is bytes) else core_schema.str_schema()
642
643 def path_validator(input_value: str | bytes) -> os.PathLike[Any]: # type: ignore
644 try:
645 if path_type is bytes:
646 if isinstance(input_value, bytes):
647 try:
648 input_value = input_value.decode()
649 except UnicodeDecodeError as e:
650 raise PydanticCustomError('bytes_type', 'Input must be valid bytes') from e
651 else:
652 raise PydanticCustomError('bytes_type', 'Input must be bytes')
653 elif not isinstance(input_value, str):
654 raise PydanticCustomError('path_type', 'Input is not a valid path')
655
656 return path_constructor(input_value) # type: ignore
657 except TypeError as e:
658 raise PydanticCustomError('path_type', 'Input is not a valid path') from e
659
660 def ser_path(path: Any, info: core_schema.SerializationInfo) -> str | os.PathLike[Any]:
661 if not isinstance(path, (tp, str)):
662 raise PydanticSerializationUnexpectedValue(
663 f"Expected `{tp}` but got `{type(path)}` with value `'{path}'` - serialized value may not be as expected."
664 )
665 if info.mode == 'python':
666 return path
667 return str(path)
668
669 instance_schema = core_schema.json_or_python_schema(
670 json_schema=core_schema.no_info_after_validator_function(path_validator, lax_inner_schema),
671 python_schema=core_schema.is_instance_schema(tp),
672 )
673
674 schema = core_schema.lax_or_strict_schema(
675 lax_schema=core_schema.union_schema(
676 [
677 instance_schema,
678 core_schema.no_info_after_validator_function(path_validator, strict_inner_schema),
679 ],
680 custom_error_type='path_type',
681 custom_error_message=f'Input is not a valid path for {tp}',
682 ),
683 strict_schema=instance_schema,
684 serialization=core_schema.plain_serializer_function_ser_schema(ser_path, info_arg=True, when_used='always'),
685 metadata={'pydantic_js_functions': [lambda source, handler: {**handler(source), 'format': 'path'}]},
686 )
687 return schema
688
689 def _deque_schema(self, items_type: Any) -> CoreSchema:
690 return core_schema.deque_schema(self.generate_schema(items_type))
691
692 def _mapping_schema(self, tp: Any, keys_type: Any, values_type: Any) -> CoreSchema:
693 from ._validators import MAPPING_ORIGIN_MAP, defaultdict_validator, get_defaultdict_default_default_factory
694
695 mapped_origin = MAPPING_ORIGIN_MAP[tp]
696 keys_schema = self.generate_schema(keys_type)
697 with warnings.catch_warnings():
698 # We kind of abused `Field()` default factories to be able to specify
699 # the `defaultdict`'s `default_factory`. As a consequence, we get warnings
700 # as normally `FieldInfo.default_factory` is unsupported in the context where
701 # `Field()` is used and our only solution is to ignore them (note that this might
702 # wrongfully ignore valid warnings, e.g. if the `value_type` is a PEP 695 type alias
703 # with unsupported metadata).
704 warnings.simplefilter('ignore', category=UnsupportedFieldAttributeWarning)
705 values_schema = self.generate_schema(values_type)
706 dict_schema = core_schema.dict_schema(keys_schema, values_schema, strict=False)
707
708 if mapped_origin is dict:
709 schema = dict_schema
710 else:
711 check_instance = core_schema.json_or_python_schema(
712 json_schema=dict_schema,
713 python_schema=core_schema.is_instance_schema(mapped_origin),
714 )
715
716 if tp is collections.defaultdict:
717 default_default_factory = get_defaultdict_default_default_factory(values_type)
718 coerce_instance_wrap = partial(
719 core_schema.no_info_wrap_validator_function,
720 partial(defaultdict_validator, default_default_factory=default_default_factory),
721 )
722 else:
723 coerce_instance_wrap = partial(core_schema.no_info_after_validator_function, mapped_origin)
724
725 lax_schema = coerce_instance_wrap(dict_schema)
726 strict_schema = core_schema.chain_schema([check_instance, lax_schema])
727
728 schema = core_schema.lax_or_strict_schema(
729 lax_schema=lax_schema,
730 strict_schema=strict_schema,
731 serialization=core_schema.wrap_serializer_function_ser_schema(
732 lambda v, h: h(v), schema=dict_schema, info_arg=False
733 ),
734 )
735
736 return schema
737
738 def _arbitrary_type_schema(self, tp: Any) -> CoreSchema:
739 if not isinstance(tp, type):
740 warnings.warn(
741 f'{tp!r} is not a Python type (it may be an instance of an object),'
742 ' Pydantic will allow any object with no validation since we cannot even'
743 ' enforce that the input is an instance of the given type.'
744 ' To get rid of this error wrap the type with `pydantic.SkipValidation`.',
745 ArbitraryTypeWarning,
746 )
747 return core_schema.any_schema()
748 return core_schema.is_instance_schema(tp)
749
750 def _unknown_type_schema(self, obj: Any) -> CoreSchema:
751 raise PydanticSchemaGenerationError(
752 f'Unable to generate pydantic-core schema for {obj!r}. '
753 'Set `arbitrary_types_allowed=True` in the model_config to ignore this error'
754 ' or implement `__get_pydantic_core_schema__` on your type to fully support it.'
755 '\n\nIf you got this error by calling handler(<some type>) within'
756 ' `__get_pydantic_core_schema__` then you likely need to call'
757 ' `handler.generate_schema(<some type>)` since we do not call'
758 ' `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.'
759 )
760
761 def _apply_discriminator_to_union(
762 self, schema: CoreSchema, discriminator: str | Discriminator | None
763 ) -> CoreSchema:
764 if discriminator is None:
765 return schema
766 try:
767 return _discriminated_union.apply_discriminator(
768 schema,
769 discriminator,
770 self.defs._definitions,
771 )
772 except _discriminated_union.MissingDefinitionForUnionRef:
773 # defer until defs are resolved
774 _discriminated_union.set_discriminator_in_metadata(
775 schema,
776 discriminator,
777 )
778 return schema
779
780 def clean_schema(self, schema: CoreSchema) -> CoreSchema:
781 return self.defs.finalize_schema(schema)
782
783 def _add_js_function(self, metadata_schema: CoreSchema, js_function: Callable[..., Any]) -> None:
784 metadata = metadata_schema.get('metadata', {})
785 pydantic_js_functions = metadata.setdefault('pydantic_js_functions', [])
786 # because of how we generate core schemas for nested generic models
787 # we can end up adding `BaseModel.__get_pydantic_json_schema__` multiple times
788 # this check may fail to catch duplicates if the function is a `functools.partial`
789 # or something like that, but if it does it'll fail by inserting the duplicate
790 if js_function not in pydantic_js_functions:
791 pydantic_js_functions.append(js_function)
792 metadata_schema['metadata'] = metadata
793
794 def generate_schema(
795 self,
796 obj: Any,
797 ) -> core_schema.CoreSchema:
798 """Generate core schema.
799
800 Args:
801 obj: The object to generate core schema for.
802
803 Returns:
804 The generated core schema.
805
806 Raises:
807 PydanticUndefinedAnnotation:
808 If it is not possible to evaluate forward reference.
809 PydanticSchemaGenerationError:
810 If it is not possible to generate pydantic-core schema.
811 TypeError:
812 - If `alias_generator` returns a disallowed type (must be str, AliasPath or AliasChoices).
813 - If V1 style validator with `each_item=True` applied on a wrong field.
814 PydanticUserError:
815 - If `typing.TypedDict` is used instead of `typing_extensions.TypedDict` on Python < 3.12.
816 - If `__modify_schema__` method is used instead of `__get_pydantic_json_schema__`.
817 """
818 origin = get_origin(obj)
819 schema: CoreSchema | None = None
820 if origin is None:
821 # If the type has an origin, it is guaranteed to *not* be an ordinary class that could have
822 # a `__get_pydantic_core_schema__()` method:
823 schema = self._generate_schema_from_get_schema_method(obj, obj)
824
825 if schema is None:
826 schema = self._generate_schema_inner(obj, origin)
827
828 # `__get_pydantic_json_schema__()` is checked on the origin if it exists:
829 metadata_js_function = _extract_get_pydantic_json_schema(origin if origin is not None else obj)
830 if metadata_js_function is not None:
831 metadata_schema = resolve_original_schema(schema, self.defs)
832 if metadata_schema:
833 self._add_js_function(metadata_schema, metadata_js_function)
834
835 schema = _add_custom_serialization_from_json_encoders(self._config_wrapper.json_encoders, obj, schema)
836
837 return schema
838
839 def _model_schema(self, cls: type[BaseModel]) -> core_schema.CoreSchema:
840 """Generate schema for a Pydantic model."""
841 BaseModel_ = import_cached_base_model()
842
843 model_ref = _type_refs.model_type_ref(cls)
844 with self.defs.get_definition_ref_schema(ref=model_ref) as maybe_schema:
845 if maybe_schema is not None:
846 return maybe_schema
847
848 schema = cls.__dict__.get('__pydantic_core_schema__')
849 if schema is not None and not isinstance(schema, MockCoreSchema):
850 if schema['type'] == 'definitions':
851 schema = self.defs.unpack_definitions(schema)
852 ref = get_ref(schema)
853 if ref:
854 return self.defs.create_definition_reference_schema(schema)
855 else:
856 return schema
857
858 config_wrapper = ConfigWrapper(cls.model_config, check=False)
859
860 with self._config_wrapper_stack.push(config_wrapper), self._ns_resolver.push(cls):
861 core_config = self._config_wrapper.core_config(title=cls.__name__)
862
863 if cls.__pydantic_fields_complete__ or cls is BaseModel_:
864 fields = getattr(cls, '__pydantic_fields__', {})
865 extra_info = getattr(cls, '__pydantic_extra_info__', None)
866 else:
867 if '__pydantic_fields__' not in cls.__dict__:
868 # This happens when we have a loop in the schema generation:
869 # class Base[T](BaseModel):
870 # t: T
871 #
872 # class Other(BaseModel):
873 # b: 'Base[Other]'
874 # When we build fields for `Other`, we evaluate the forward annotation.
875 # At this point, `Other` doesn't have the model fields set. We create
876 # `Base[Other]`; model fields are successfully built, and we try to generate
877 # a schema for `t: Other`. As `Other.__pydantic_fields__` aren't set, we abort.
878 raise PydanticUndefinedAnnotation(
879 name=cls.__name__,
880 message=f'Class {cls.__name__!r} is not defined',
881 )
882 try:
883 fields, extra_info = rebuild_model_fields(
884 cls,
885 config_wrapper=self._config_wrapper,
886 ns_resolver=self._ns_resolver,
887 typevars_map=get_model_typevars_map(cls),
888 )
889 except NameError as e:
890 raise PydanticUndefinedAnnotation.from_name_error(e) from e
891
892 decorators = cls.__pydantic_decorators__
893 computed_fields = decorators.computed_fields
894 if decorators.field_validators or decorators.field_serializers or decorators.validators:
895 check_decorator_fields_exist(
896 chain(
897 decorators.field_validators.values(),
898 decorators.field_serializers.values(),
899 decorators.validators.values(),
900 ),
901 {*fields.keys(), *computed_fields.keys()},
902 )
903
904 model_validators = decorators.model_validators.values()
905
906 extras_schema = None
907 extras_keys_schema = None
908 if core_config.get('extra_fields_behavior') == 'allow' and extra_info is not None:
909 tp = get_origin(extra_info.annotation)
910 if tp is not dict:
911 raise PydanticSchemaGenerationError(
912 'The type annotation for `__pydantic_extra__` must be `dict[str, ...]`'
913 )
914 # See the comments in `_get_args_resolving_forward_refs()` for why we need
915 # to re-evaluate the annotation:
916 extra_keys_type, extra_items_type = self._get_args_resolving_forward_refs(
917 extra_info.annotation,
918 required=True,
919 )
920 if extra_keys_type is not str:
921 extras_keys_schema = self.generate_schema(extra_keys_type)
922 if not typing_objects.is_any(extra_items_type):
923 extras_schema = self.generate_schema(extra_items_type)
924
925 generic_origin: type[BaseModel] | None = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin')
926
927 if cls.__pydantic_root_model__:
928 inner_schema, metadata = self._common_field_schema('root', fields['root'], decorators)
929 if cls.__doc__ and metadata.get('pydantic_js_updates', {}).get('description'):
930 # This is a bit of a leaky abstraction, but as the model docstring takes priority
931 # over the root field's description, we need to override it here. This can't be done
932 # in the JSON Schema generation logic because the metadata's `pydantic_js_updates` are
933 # applied last, and overrides any value previously set (so the description set from the
934 # docstring in `GenerateJsonSchema._update_class_schema()` is overridden):
935 update_core_metadata(
936 metadata, pydantic_js_updates={'description': inspect.cleandoc(cls.__doc__)}
937 )
938
939 inner_schema = apply_model_validators(inner_schema, model_validators, 'inner')
940 model_schema = core_schema.model_schema(
941 cls,
942 inner_schema,
943 generic_origin=generic_origin,
944 custom_init=getattr(cls, '__pydantic_custom_init__', None),
945 root_model=True,
946 post_init=getattr(cls, '__pydantic_post_init__', None),
947 config=core_config,
948 ref=model_ref,
949 metadata=metadata,
950 )
951 else:
952 fields_schema: core_schema.CoreSchema = core_schema.model_fields_schema(
953 {k: self._generate_md_field_schema(k, v, decorators) for k, v in fields.items()},
954 computed_fields=[
955 self._computed_field_schema(d, decorators.field_serializers)
956 for d in computed_fields.values()
957 ],
958 extras_schema=extras_schema,
959 extras_keys_schema=extras_keys_schema,
960 model_name=cls.__name__,
961 )
962 inner_schema = apply_validators(fields_schema, decorators.root_validators.values())
963 inner_schema = apply_model_validators(inner_schema, model_validators, 'inner')
964
965 model_schema = core_schema.model_schema(
966 cls,
967 inner_schema,
968 generic_origin=generic_origin,
969 custom_init=getattr(cls, '__pydantic_custom_init__', None),
970 root_model=False,
971 post_init=getattr(cls, '__pydantic_post_init__', None),
972 config=core_config,
973 ref=model_ref,
974 )
975
976 schema = self._apply_model_serializers(model_schema, decorators.model_serializers.values())
977 schema = apply_model_validators(schema, model_validators, 'outer')
978 return self.defs.create_definition_reference_schema(schema)
979
980 def _resolve_self_type(self, obj: Any) -> Any:
981 obj = self.model_type_stack.get()
982 if obj is None:
983 raise PydanticUserError('`typing.Self` is invalid in this context', code='invalid-self-type')
984 return obj
985
986 def _generate_schema_from_get_schema_method(self, obj: Any, source: Any) -> core_schema.CoreSchema | None:
987 BaseModel_ = import_cached_base_model()
988
989 get_schema = getattr(obj, '__get_pydantic_core_schema__', None)
990
991 if (
992 get_schema is not None
993 # BaseModel.__get_pydantic_core_schema__ is defined for backwards compatibility,
994 # to allow existing code to call `super().__get_pydantic_core_schema__` in Pydantic
995 # model that overrides `__get_pydantic_core_schema__`. However, it raises a deprecation
996 # warning stating that the method will be removed, and during the core schema gen we actually
997 # don't call the method:
998 and getattr(get_schema, '__func__', None) is not BaseModel_.__get_pydantic_core_schema__.__func__ # pyright: ignore[reportFunctionMemberAccess]
999 ):
1000 # Some referenceable types might have a `__get_pydantic_core_schema__` method
1001 # defined on it by users (e.g. on a dataclass). This generally doesn't play well
1002 # as these types are already recognized by the `GenerateSchema` class and isn't ideal
1003 # as we might end up calling `any_type_ref()` (relatively expensive) on types that are actually
1004 # not referenceable:
1005 with self.defs.get_definition_ref_schema(ref=_type_refs.any_type_ref(obj, get_origin(obj))) as maybe_schema:
1006 if maybe_schema is not None:
1007 return maybe_schema
1008
1009 if obj is source:
1010 ref_mode = 'unpack'
1011 else:
1012 ref_mode = 'to-def'
1013 schema = get_schema(
1014 source, CallbackGetCoreSchemaHandler(self._generate_schema_inner, self, ref_mode=ref_mode)
1015 )
1016 if schema['type'] == 'definitions':
1017 schema = self.defs.unpack_definitions(schema)
1018
1019 ref = get_ref(schema)
1020 if ref:
1021 return self.defs.create_definition_reference_schema(schema)
1022
1023 # Note: if schema is of type `'definition-ref'`, we might want to copy it as a
1024 # safety measure (because these are inlined in place -- i.e. mutated directly)
1025 return schema
1026
1027 if get_schema is None and (validators := getattr(obj, '__get_validators__', None)) is not None:
1028 from pydantic.v1 import BaseModel as BaseModelV1
1029
1030 if issubclass(obj, BaseModelV1):
1031 warnings.warn(
1032 f'Mixing V1 models and V2 models (or constructs, like `TypeAdapter`) is not supported. Please upgrade `{obj.__name__}` to V2.',
1033 UserWarning,
1034 )
1035 else:
1036 warnings.warn(
1037 '`__get_validators__` is deprecated and will be removed, use `__get_pydantic_core_schema__` instead.',
1038 PydanticDeprecatedSince20,
1039 )
1040 return core_schema.chain_schema([core_schema.with_info_plain_validator_function(v) for v in validators()])
1041
1042 def _resolve_forward_ref(self, obj: Any) -> Any:
1043 # we assume that types_namespace has the target of forward references in its scope,
1044 # but this could fail, for example, if calling Validator on an imported type which contains
1045 # forward references to other types only defined in the module from which it was imported
1046 # `Validator(SomeImportedTypeAliasWithAForwardReference)`
1047 # or the equivalent for BaseModel
1048 # class Model(BaseModel):
1049 # x: SomeImportedTypeAliasWithAForwardReference
1050 try:
1051 obj = _typing_extra.eval_type(obj, *self._types_namespace)
1052 except NameError as e:
1053 raise PydanticUndefinedAnnotation.from_name_error(e) from e
1054
1055 # if obj is still a ForwardRef, it means we can't evaluate it, raise PydanticUndefinedAnnotation
1056 if isinstance(obj, ForwardRef):
1057 raise PydanticUndefinedAnnotation(obj.__forward_arg__, f'Unable to evaluate forward reference {obj}')
1058
1059 if self._typevars_map:
1060 obj = replace_types(obj, self._typevars_map)
1061
1062 return obj
1063
1064 @overload
1065 def _get_args_resolving_forward_refs(self, obj: Any, required: Literal[True]) -> tuple[Any, ...]: ...
1066
1067 @overload
1068 def _get_args_resolving_forward_refs(self, obj: Any) -> tuple[Any, ...] | None: ...
1069
1070 def _get_args_resolving_forward_refs(self, obj: Any, required: bool = False) -> tuple[Any, ...] | None:
1071 args = get_args(obj)
1072 if args:
1073 if isinstance(obj, GenericAlias):
1074 # PEP 585 generic aliases don't convert args to ForwardRefs, unlike `typing.List/Dict` etc.
1075 # This was fixed in https://github.com/python/cpython/pull/30900 (Python 3.11).
1076 # TODO: this shouldn't be necessary (probably even this `_get_args_resolving_forward_refs()` function)
1077 # once we drop support for Python 3.10 *or* if we implement our own `typing._eval_type()` implementation.
1078 args = (ForwardRef(a) if isinstance(a, str) else a for a in args)
1079 args = tuple(self._resolve_forward_ref(a) if isinstance(a, ForwardRef) else a for a in args)
1080 elif required: # pragma: no cover
1081 raise TypeError(f'Expected {obj} to have generic parameters but it had none')
1082 return args
1083
1084 def _get_first_arg_or_any(self, obj: Any) -> Any:
1085 args = self._get_args_resolving_forward_refs(obj)
1086 if not args:
1087 return Any
1088 return args[0]
1089
1090 def _get_first_two_args_or_any(self, obj: Any) -> tuple[Any, Any]:
1091 args = self._get_args_resolving_forward_refs(obj)
1092 if not args:
1093 return (Any, Any)
1094 if len(args) < 2:
1095 origin = get_origin(obj)
1096 raise TypeError(f'Expected two type arguments for {origin}, got 1')
1097 return args[0], args[1]
1098
1099 def _generate_schema_inner(self, obj: Any, origin: Any | None = PydanticUndefined) -> core_schema.CoreSchema:
1100 if typing_objects.is_self(obj):
1101 obj = self._resolve_self_type(obj)
1102 # The resolved type can be a parametrized generic (e.g. `GenericDataclass[int]`),
1103 # so the origin provided by the caller (computed on `Self`) is stale:
1104 origin = get_origin(obj)
1105
1106 origin = origin if origin is not PydanticUndefined else get_origin(obj)
1107
1108 if is_union_origin(origin):
1109 return self._union_schema(obj)
1110
1111 if typing_objects.is_annotated(origin):
1112 return self._annotated_schema(obj)
1113
1114 if typing_objects.is_literal(origin):
1115 return self._literal_schema(obj)
1116
1117 if isinstance(obj, dict):
1118 # we assume this is already a valid schema
1119 return obj # type: ignore[return-value]
1120
1121 if isinstance(obj, str):
1122 obj = ForwardRef(obj)
1123
1124 if isinstance(obj, ForwardRef):
1125 return self.generate_schema(self._resolve_forward_ref(obj))
1126
1127 BaseModel = import_cached_base_model()
1128
1129 if lenient_issubclass(obj, BaseModel):
1130 with self.model_type_stack.push(obj):
1131 return self._model_schema(obj)
1132
1133 if isinstance(obj, PydanticRecursiveRef):
1134 return core_schema.definition_reference_schema(schema_ref=obj.type_ref)
1135
1136 return self.match_type(obj, origin)
1137
1138 def match_type(self, obj: Any, origin: Any) -> core_schema.CoreSchema: # noqa: C901
1139 """Main mapping of types to schemas.
1140
1141 The general structure is a series of if statements starting with the simple cases
1142 (non-generic primitive types) and then handling generics and other more complex cases.
1143
1144 Each case either generates a schema directly, calls into a public user-overridable method
1145 (like `GenerateSchema.tuple_variable_schema`) or calls into a private method that handles some
1146 boilerplate before calling into the user-facing method (e.g. `GenerateSchema._tuple_schema`).
1147
1148 The idea is that we'll evolve this into adding more and more user facing methods over time
1149 as they get requested and we figure out what the right API for them is.
1150 """
1151 if typing_objects.is_any(obj) or typing_objects.is_final(obj):
1152 # TODO: I'm not sure obj can be `Final` here, we call `typing_inspection.introspection.inspect_annotation()`
1153 # early for model-like fields, which handles it already.
1154 return core_schema.any_schema()
1155
1156 if origin is not None and (aliased_obj := typing_objects.DEPRECATED_ALIASES_IDS.get(id(obj))):
1157 # See https://typing-inspection.pydantic.dev/dev/usage/#inspecting-the-type-expression:
1158 obj = aliased_obj
1159 origin = None
1160
1161 if origin is None:
1162 # Thanks to the checks before this point, no origin means `obj` is a
1163 # simple type (not a generic alias, a union, an `Annotated` form).
1164 # examples: int, str, list, dict, collections.abc.Mapping, a `TypeAliasType` instance.
1165 try:
1166 handler = self._handlers.get(obj)
1167 except TypeError:
1168 pass
1169 else:
1170 if handler is not None:
1171 return handler(self, obj)
1172
1173 if typing_objects.is_typealiastype(obj):
1174 return self._type_alias_type_schema(obj)
1175 elif is_typeddict(obj):
1176 return self._typed_dict_schema(obj, None)
1177 elif inspect.isclass(obj) and issubclass(obj, Enum):
1178 # NOTE: this must come before the `is_namedtuple()` check as enums values
1179 # can be namedtuples:
1180 return self._enum_schema(obj)
1181 elif _typing_extra.is_namedtuple(obj):
1182 return self._namedtuple_schema(obj, None)
1183 elif typing_objects.is_newtype(obj):
1184 return self.generate_schema(obj.__supertype__)
1185 elif isinstance(obj, typing.TypeVar):
1186 return self._unsubstituted_typevar_schema(obj)
1187 elif isinstance(obj, VALIDATE_CALL_SUPPORTED_TYPES):
1188 return self._call_schema(obj) # pyright: ignore[reportArgumentType]
1189 # dataclasses.is_dataclass coerces dc instances to types, but we only handle
1190 # the case of a dc type here
1191 elif dataclasses.is_dataclass(obj):
1192 return self._dataclass_schema(obj, None) # pyright: ignore[reportArgumentType]
1193
1194 if origin is not None:
1195 return self._match_generic_type(obj, origin)
1196
1197 if self._arbitrary_types:
1198 return self._arbitrary_type_schema(obj)
1199 return self._unknown_type_schema(obj)
1200
1201 def _match_generic_type(self, obj: Any, origin: Any) -> CoreSchema: # noqa: C901
1202 # Need to handle generic dataclasses before looking for the schema properties because attribute accesses
1203 # on _GenericAlias delegate to the origin type, so lose the information about the concrete parametrization
1204 # As a result, currently, there is no way to cache the schema for generic dataclasses. This may be possible
1205 # to resolve by modifying the value returned by `Generic.__class_getitem__`, but that is a dangerous game.
1206 if dataclasses.is_dataclass(origin):
1207 return self._dataclass_schema(obj, origin) # pyright: ignore[reportArgumentType]
1208 elif _typing_extra.is_namedtuple(origin):
1209 return self._namedtuple_schema(obj, origin)
1210 elif typing_objects.is_final(origin):
1211 # TODO: I'm not sure obj can be `Final` here, we call `typing_inspection.introspection.inspect_annotation()`
1212 # early for model-like fields, which handles it already.
1213 return self.generate_schema(self._get_first_arg_or_any(obj))
1214
1215 schema = self._generate_schema_from_get_schema_method(origin, obj)
1216 if schema is not None:
1217 return schema
1218
1219 try:
1220 handler = self._generic_handlers.get(origin)
1221 except TypeError:
1222 pass
1223 else:
1224 if handler is not None:
1225 return handler(self, obj)
1226
1227 if typing_objects.is_typealiastype(origin):
1228 return self._type_alias_type_schema(obj)
1229 elif is_typeddict(origin):
1230 return self._typed_dict_schema(obj, origin)
1231
1232 if self._arbitrary_types:
1233 return self._arbitrary_type_schema(origin)
1234 return self._unknown_type_schema(obj)
1235
1236 def _generate_td_field_schema(
1237 self,
1238 name: str,
1239 field_info: FieldInfo,
1240 decorators: DecoratorInfos,
1241 *,
1242 required: bool = True,
1243 ) -> core_schema.TypedDictField:
1244 """Prepare a TypedDictField to represent a model or typeddict field."""
1245 schema, metadata = self._common_field_schema(name, field_info, decorators)
1246 return core_schema.typed_dict_field(
1247 schema,
1248 required=False if not field_info.is_required() else required,
1249 serialization_exclude=field_info.exclude,
1250 validation_alias=_convert_to_aliases(field_info.validation_alias),
1251 serialization_alias=field_info.serialization_alias,
1252 serialization_exclude_if=field_info.exclude_if,
1253 metadata=metadata,
1254 )
1255
1256 def _generate_md_field_schema(
1257 self,
1258 name: str,
1259 field_info: FieldInfo,
1260 decorators: DecoratorInfos,
1261 ) -> core_schema.ModelField:
1262 """Prepare a ModelField to represent a model field."""
1263 schema, metadata = self._common_field_schema(name, field_info, decorators)
1264 return core_schema.model_field(
1265 schema,
1266 serialization_exclude=field_info.exclude,
1267 validation_alias=_convert_to_aliases(field_info.validation_alias),
1268 serialization_alias=field_info.serialization_alias,
1269 serialization_exclude_if=field_info.exclude_if,
1270 frozen=field_info.frozen,
1271 metadata=metadata,
1272 )
1273
1274 def _generate_dc_field_schema(
1275 self,
1276 name: str,
1277 field_info: FieldInfo,
1278 decorators: DecoratorInfos,
1279 ) -> core_schema.DataclassField:
1280 """Prepare a DataclassField to represent the parameter/field, of a dataclass."""
1281 schema, metadata = self._common_field_schema(name, field_info, decorators)
1282 return core_schema.dataclass_field(
1283 name,
1284 schema,
1285 init=field_info.init,
1286 init_only=field_info.init_var or None,
1287 kw_only=None if field_info.kw_only else False,
1288 serialization_exclude=field_info.exclude,
1289 validation_alias=_convert_to_aliases(field_info.validation_alias),
1290 serialization_alias=field_info.serialization_alias,
1291 serialization_exclude_if=field_info.exclude_if,
1292 frozen=field_info.frozen,
1293 metadata=metadata,
1294 )
1295
1296 def _common_field_schema( # C901
1297 self, name: str, field_info: FieldInfo, decorators: DecoratorInfos
1298 ) -> tuple[CoreSchema, dict[str, Any]]:
1299 source_type, annotations = field_info.annotation, field_info.metadata
1300
1301 def set_discriminator(schema: CoreSchema) -> CoreSchema:
1302 schema = self._apply_discriminator_to_union(schema, field_info.discriminator)
1303 return schema
1304
1305 # Convert `@field_validator` decorators to `Before/After/Plain/WrapValidator` instances:
1306 if decorators.field_validators:
1307 validators_from_decorators = [
1308 _mode_to_validator[decorator.info.mode]._from_decorator(decorator)
1309 for decorator in filter_field_decorator_info_by_field(decorators.field_validators.values(), name)
1310 ]
1311 else:
1312 validators_from_decorators = []
1313
1314 with self.field_name_stack.push(name):
1315 if field_info.discriminator is not None:
1316 schema = self._apply_annotations(
1317 source_type, annotations + validators_from_decorators, transform_inner_schema=set_discriminator
1318 )
1319 else:
1320 schema = self._apply_annotations(
1321 source_type,
1322 annotations + validators_from_decorators,
1323 )
1324
1325 if decorators.validators:
1326 # This V1 compatibility shim should eventually be removed
1327 # push down any `each_item=True` validators
1328 # note that this won't work for any Annotated types that get wrapped by a function validator
1329 # but that's okay because that didn't exist in V1
1330 this_field_validators = filter_field_decorator_info_by_field(decorators.validators.values(), name)
1331 if _validators_require_validate_default(this_field_validators):
1332 field_info.validate_default = True
1333 each_item_validators = [v for v in this_field_validators if v.info.each_item is True]
1334 this_field_validators = [v for v in this_field_validators if v not in each_item_validators]
1335 schema = apply_each_item_validators(schema, each_item_validators)
1336
1337 schema = apply_validators(schema, this_field_validators)
1338
1339 # the default validator needs to go outside of any other validators
1340 # so that it is the topmost validator for the field validator
1341 # which uses it to check if the field has a default value or not
1342 if not field_info.is_required():
1343 schema = wrap_default(field_info, schema)
1344
1345 if decorators.field_serializers:
1346 schema = self._apply_field_serializers(
1347 schema, filter_field_decorator_info_by_field(decorators.field_serializers.values(), name)
1348 )
1349
1350 pydantic_js_updates, pydantic_js_extra = _extract_json_schema_info_from_field_info(field_info)
1351 core_metadata: dict[str, Any] = {}
1352 update_core_metadata(
1353 core_metadata, pydantic_js_updates=pydantic_js_updates, pydantic_js_extra=pydantic_js_extra
1354 )
1355
1356 return schema, core_metadata
1357
1358 def _union_schema(self, union_type: Any) -> core_schema.CoreSchema:
1359 """Generate schema for a Union."""
1360 args = self._get_args_resolving_forward_refs(union_type, required=True)
1361 choices: list[CoreSchema] = []
1362 nullable = False
1363 allow_missing = False
1364 for arg in args:
1365 if arg is None or arg is NoneType:
1366 nullable = True
1367 elif arg is MISSING:
1368 allow_missing = True
1369 else:
1370 choices.append(self.generate_schema(arg))
1371
1372 if not choices:
1373 # Only `None` and `MISSING` were present in the union (e.g. `None | MISSING`):
1374 s = core_schema.none_schema()
1375 nullable = False
1376 elif len(choices) == 1:
1377 s = choices[0]
1378 else:
1379 choices_with_tags: list[CoreSchema | tuple[CoreSchema, str]] = []
1380 for choice in choices:
1381 tag = cast(CoreMetadata, choice.get('metadata', {})).get('pydantic_internal_union_tag_key')
1382 if tag is not None:
1383 choices_with_tags.append((choice, tag))
1384 else:
1385 choices_with_tags.append(choice)
1386 s = core_schema.union_schema(choices_with_tags)
1387
1388 if nullable:
1389 s = core_schema.nullable_schema(s)
1390 if allow_missing:
1391 s = core_schema.missing_sentinel_schema(s)
1392 return s
1393
1394 def _type_alias_type_schema(self, obj: TypeAliasType) -> CoreSchema:
1395 ref = _type_refs.type_alias_type_ref(obj)
1396 with self.defs.get_definition_ref_schema(ref=ref) as maybe_schema:
1397 if maybe_schema is not None:
1398 return maybe_schema
1399
1400 origin: TypeAliasType = get_origin(obj) or obj
1401 typevars_map = get_standard_typevars_map(obj)
1402
1403 with self._ns_resolver.push(origin):
1404 try:
1405 annotation = _typing_extra.eval_type(origin.__value__, *self._types_namespace)
1406 except NameError as e:
1407 raise PydanticUndefinedAnnotation.from_name_error(e) from e
1408 annotation = replace_types(annotation, typevars_map)
1409 schema = self.generate_schema(annotation)
1410 assert schema['type'] != 'definitions'
1411 schema['ref'] = ref # type: ignore
1412 return self.defs.create_definition_reference_schema(schema)
1413
1414 def _literal_schema(self, literal_type: Any) -> CoreSchema:
1415 """Generate schema for a Literal."""
1416 expected = list(get_literal_values(literal_type, type_check=False, unpack_type_aliases='eager'))
1417 assert expected, f'literal "expected" cannot be empty, obj={literal_type}'
1418 schema = core_schema.literal_schema(expected)
1419
1420 if self._config_wrapper.use_enum_values and any(isinstance(v, Enum) for v in expected):
1421 schema = core_schema.no_info_after_validator_function(
1422 lambda v: v.value if isinstance(v, Enum) else v, schema
1423 )
1424
1425 return schema
1426
1427 def _typed_dict_schema(self, typed_dict_cls: Any, origin: Any) -> core_schema.CoreSchema:
1428 """Generate a core schema for a `TypedDict` class.
1429
1430 To be able to build a `DecoratorInfos` instance for the `TypedDict` class (which will include
1431 validators, serializers, etc.), we need to have access to the original bases of the class
1432 (see https://docs.python.org/3/library/types.html#types.get_original_bases).
1433 However, the `__orig_bases__` attribute was only added in 3.12 (https://github.com/python/cpython/pull/103698).
1434
1435 For this reason, we require Python 3.12 (or using the `typing_extensions` backport).
1436 """
1437 FieldInfo = import_cached_field_info()
1438
1439 typed_dict_ref = _type_refs.class_type_ref(typed_dict_cls, origin)
1440 with (
1441 self.model_type_stack.push(typed_dict_cls),
1442 self.defs.get_definition_ref_schema(ref=typed_dict_ref) as maybe_schema,
1443 ):
1444 if maybe_schema is not None:
1445 return maybe_schema
1446
1447 typevars_map = get_standard_typevars_map(typed_dict_cls)
1448 if origin is not None:
1449 typed_dict_cls = origin
1450
1451 if not _SUPPORTS_TYPEDDICT and type(typed_dict_cls).__module__ == 'typing':
1452 raise PydanticUserError(
1453 'Please use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12.',
1454 code='typed-dict-version',
1455 )
1456
1457 try:
1458 # if a typed dictionary class doesn't have config, we use the parent's config, hence a default of `None`
1459 # see https://github.com/pydantic/pydantic/issues/10917
1460 config: ConfigDict | None = get_attribute_from_bases(typed_dict_cls, '__pydantic_config__')
1461 except AttributeError:
1462 config = None
1463
1464 with self._config_wrapper_stack.push(config):
1465 core_config = self._config_wrapper.core_config(title=typed_dict_cls.__name__)
1466
1467 required_keys: frozenset[str] = typed_dict_cls.__required_keys__
1468
1469 fields: dict[str, core_schema.TypedDictField] = {}
1470
1471 decorators = DecoratorInfos.build(typed_dict_cls, replace_wrapped_methods=False)
1472 decorators.update_from_config(self._config_wrapper)
1473
1474 if self._config_wrapper.use_attribute_docstrings:
1475 field_docstrings = extract_docstrings_from_cls(typed_dict_cls, use_inspect=True)
1476 else:
1477 field_docstrings = None
1478
1479 try:
1480 annotations = _typing_extra.get_cls_type_hints(typed_dict_cls, ns_resolver=self._ns_resolver)
1481 except NameError as e:
1482 raise PydanticUndefinedAnnotation.from_name_error(e) from e
1483
1484 readonly_fields: list[str] = []
1485
1486 for field_name, annotation in annotations.items():
1487 field_info = FieldInfo.from_annotation(annotation, _source=AnnotationSource.TYPED_DICT)
1488 field_info.annotation = replace_types(field_info.annotation, typevars_map)
1489
1490 required = (
1491 field_name in required_keys or 'required' in field_info._qualifiers
1492 ) and 'not_required' not in field_info._qualifiers
1493 if 'read_only' in field_info._qualifiers:
1494 readonly_fields.append(field_name)
1495
1496 if (
1497 field_docstrings is not None
1498 and field_info.description is None
1499 and field_name in field_docstrings
1500 ):
1501 field_info.description = field_docstrings[field_name]
1502 update_field_from_config(self._config_wrapper, field_name, field_info)
1503
1504 fields[field_name] = self._generate_td_field_schema(
1505 field_name, field_info, decorators, required=required
1506 )
1507
1508 if readonly_fields:
1509 fields_repr = ', '.join(repr(f) for f in readonly_fields)
1510 plural = len(readonly_fields) >= 2
1511 warnings.warn(
1512 f'Item{"s" if plural else ""} {fields_repr} on TypedDict class {typed_dict_cls.__name__!r} '
1513 f'{"are" if plural else "is"} using the `ReadOnly` qualifier. Pydantic will not protect items '
1514 'from any mutation on dictionary instances.',
1515 UserWarning,
1516 )
1517
1518 extra_behavior: core_schema.ExtraBehavior = 'ignore'
1519 extras_schema: CoreSchema | None = None # For 'allow', equivalent to `Any` - no validation performed.
1520
1521 is_closed, extra_items, extra_items_readonly = _get_typed_dict_extra_items(typed_dict_cls)
1522 if is_closed:
1523 extra_behavior = 'forbid'
1524 extras_schema = None
1525 elif not typing_objects.is_noextraitems(extra_items):
1526 extra_behavior = 'allow'
1527 extras_schema = self.generate_schema(replace_types(extra_items, typevars_map))
1528
1529 if extra_items_readonly:
1530 warnings.warn(
1531 f'Extra items on TypedDict class {typed_dict_cls.__name__!r} are using the `ReadOnly` qualifier. '
1532 'Pydantic will not protect items from any mutation on dictionary instances.',
1533 UserWarning,
1534 )
1535
1536 if (config_extra := self._config_wrapper.extra) in ('allow', 'forbid'):
1537 if is_closed and config_extra == 'allow':
1538 warnings.warn(
1539 f"TypedDict class {typed_dict_cls.__qualname__!r} is closed, but 'extra' configuration "
1540 "is set to `'allow'`. The 'extra' configuration value will be ignored.",
1541 category=TypedDictExtraConfigWarning,
1542 )
1543 elif not typing_objects.is_noextraitems(extra_items) and config_extra == 'forbid':
1544 warnings.warn(
1545 f"TypedDict class {typed_dict_cls.__qualname__!r} allows extra items, but 'extra' configuration "
1546 "is set to `'forbid'`. The 'extra' configuration value will be ignored.",
1547 category=TypedDictExtraConfigWarning,
1548 )
1549 else:
1550 extra_behavior = config_extra
1551
1552 td_schema = core_schema.typed_dict_schema(
1553 fields,
1554 cls=typed_dict_cls,
1555 computed_fields=[
1556 self._computed_field_schema(d, decorators.field_serializers)
1557 for d in decorators.computed_fields.values()
1558 ],
1559 extra_behavior=extra_behavior,
1560 extras_schema=extras_schema,
1561 ref=typed_dict_ref,
1562 config=core_config,
1563 )
1564
1565 schema = self._apply_model_serializers(td_schema, decorators.model_serializers.values())
1566 schema = apply_model_validators(schema, decorators.model_validators.values(), 'all')
1567 return self.defs.create_definition_reference_schema(schema)
1568
1569 def _namedtuple_schema(self, namedtuple_cls: Any, origin: Any) -> core_schema.CoreSchema:
1570 """Generate schema for a NamedTuple."""
1571 namedtuple_ref = _type_refs.class_type_ref(namedtuple_cls, origin)
1572 with (
1573 self.model_type_stack.push(namedtuple_cls),
1574 self.defs.get_definition_ref_schema(ref=namedtuple_ref) as maybe_schema,
1575 ):
1576 if maybe_schema is not None:
1577 return maybe_schema
1578 typevars_map = get_standard_typevars_map(namedtuple_cls)
1579 if origin is not None:
1580 namedtuple_cls = origin
1581
1582 try:
1583 annotations = _typing_extra.get_cls_type_hints(namedtuple_cls, ns_resolver=self._ns_resolver)
1584 except NameError as e:
1585 raise PydanticUndefinedAnnotation.from_name_error(e) from e
1586
1587 # Filter annotations to only include fields that are actually in the NamedTuple
1588 # (as subclassing an existing NamedTuple is not supported yet - see https://github.com/python/typing/issues/427)
1589 # and use `Any` if no annotation exist (i.e. when using `collections.namedtuple()`).
1590 annotations = {field_name: annotations.get(field_name, Any) for field_name in namedtuple_cls._fields}
1591
1592 if typevars_map:
1593 annotations = {
1594 field_name: replace_types(annotation, typevars_map)
1595 for field_name, annotation in annotations.items()
1596 }
1597
1598 schema = core_schema.named_tuple_schema(
1599 namedtuple_cls,
1600 [
1601 self._generate_namedtuple_field_schema(
1602 field_name,
1603 annotation,
1604 default=namedtuple_cls._field_defaults.get(field_name, Parameter.empty),
1605 )
1606 for field_name, annotation in annotations.items()
1607 ],
1608 ref=namedtuple_ref,
1609 )
1610 return self.defs.create_definition_reference_schema(schema)
1611
1612 def _generate_namedtuple_field_schema(
1613 self,
1614 name: str,
1615 annotation: Any,
1616 default: Any = Parameter.empty,
1617 ) -> core_schema.NamedTupleField:
1618 """Generate the definition of a field in a named tuple."""
1619 FieldInfo = import_cached_field_info()
1620
1621 if default is Parameter.empty:
1622 field = FieldInfo.from_annotation(annotation, _source=AnnotationSource.NAMED_TUPLE)
1623 else:
1624 field = FieldInfo.from_annotated_attribute(annotation, default, _source=AnnotationSource.NAMED_TUPLE)
1625
1626 assert field.annotation is not None, 'field.annotation should not be None when generating a schema'
1627 update_field_from_config(self._config_wrapper, name, field)
1628
1629 with self.field_name_stack.push(name):
1630 schema = self._apply_annotations(
1631 field.annotation,
1632 [field],
1633 # Because we pass `field` as metadata above (required for attributes relevant for
1634 # JSON Scheme generation), we need to ignore the potential warnings about `FieldInfo`
1635 # attributes that will not be used:
1636 check_unsupported_field_info_attributes=False,
1637 )
1638
1639 if not field.is_required():
1640 schema = wrap_default(field, schema)
1641
1642 return core_schema.named_tuple_field(
1643 name,
1644 schema,
1645 validation_alias=_convert_to_aliases(field.validation_alias),
1646 )
1647
1648 def _generate_parameter_schema(
1649 self,
1650 name: str,
1651 annotation: type[Any],
1652 source: AnnotationSource,
1653 default: Any = Parameter.empty,
1654 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None,
1655 ) -> core_schema.ArgumentsParameter:
1656 """Generate the definition of a parameter in a function signature.
1657
1658 This definition is meant to be used for the `'arguments'` core schema, which will be replaced
1659 in V3 by the `'arguments-v3`'.
1660 """
1661 FieldInfo = import_cached_field_info()
1662
1663 if default is Parameter.empty:
1664 field = FieldInfo.from_annotation(annotation, _source=source)
1665 else:
1666 field = FieldInfo.from_annotated_attribute(annotation, default, _source=source)
1667
1668 assert field.annotation is not None, 'field.annotation should not be None when generating a schema'
1669 update_field_from_config(self._config_wrapper, name, field)
1670
1671 with self.field_name_stack.push(name):
1672 schema = self._apply_annotations(
1673 field.annotation,
1674 [field],
1675 # Because we pass `field` as metadata above (required for attributes relevant for
1676 # JSON Scheme generation), we need to ignore the potential warnings about `FieldInfo`
1677 # attributes that will not be used:
1678 check_unsupported_field_info_attributes=False,
1679 )
1680
1681 if not field.is_required():
1682 schema = wrap_default(field, schema)
1683
1684 parameter_schema = core_schema.arguments_parameter(
1685 name,
1686 schema,
1687 mode=mode,
1688 alias=_convert_to_aliases(field.validation_alias),
1689 )
1690
1691 return parameter_schema
1692
1693 def _generate_parameter_v3_schema(
1694 self,
1695 name: str,
1696 annotation: Any,
1697 source: AnnotationSource,
1698 mode: Literal[
1699 'positional_only',
1700 'positional_or_keyword',
1701 'keyword_only',
1702 'var_args',
1703 'var_kwargs_uniform',
1704 'var_kwargs_unpacked_typed_dict',
1705 ],
1706 default: Any = Parameter.empty,
1707 ) -> core_schema.ArgumentsV3Parameter:
1708 """Generate the definition of a parameter in a function signature.
1709
1710 This definition is meant to be used for the `'arguments-v3'` core schema, which will replace
1711 the `'arguments`' schema in V3.
1712 """
1713 FieldInfo = import_cached_field_info()
1714
1715 if default is Parameter.empty:
1716 field = FieldInfo.from_annotation(annotation, _source=source)
1717 else:
1718 field = FieldInfo.from_annotated_attribute(annotation, default, _source=source)
1719 update_field_from_config(self._config_wrapper, name, field)
1720
1721 with self.field_name_stack.push(name):
1722 schema = self._apply_annotations(
1723 field.annotation,
1724 [field],
1725 # Because we pass `field` as metadata above (required for attributes relevant for
1726 # JSON Scheme generation), we need to ignore the potential warnings about `FieldInfo`
1727 # attributes that will not be used:
1728 check_unsupported_field_info_attributes=False,
1729 )
1730
1731 if not field.is_required():
1732 schema = wrap_default(field, schema)
1733
1734 parameter_schema = core_schema.arguments_v3_parameter(
1735 name=name,
1736 schema=schema,
1737 mode=mode,
1738 alias=_convert_to_aliases(field.validation_alias),
1739 )
1740
1741 return parameter_schema
1742
1743 def _tuple_schema(self, tuple_type: Any) -> core_schema.CoreSchema:
1744 """Generate schema for a Tuple, e.g. `tuple[int, str]` or `tuple[int, ...]`."""
1745 # TODO: do we really need to resolve type vars here?
1746 typevars_map = get_standard_typevars_map(tuple_type)
1747 params = self._get_args_resolving_forward_refs(tuple_type)
1748
1749 if typevars_map and params:
1750 params = tuple(replace_types(param, typevars_map) for param in params)
1751
1752 # NOTE: subtle difference: `tuple[()]` gives `params=()`, whereas `typing.Tuple[()]` gives `params=((),)`
1753 # This is only true for <3.11, on Python 3.11+ `typing.Tuple[()]` gives `params=()`
1754 if not params:
1755 if tuple_type in TUPLE_TYPES:
1756 return core_schema.tuple_schema([core_schema.any_schema()], variadic_item_index=0)
1757 else:
1758 # special case for `tuple[()]` which means `tuple[]` - an empty tuple
1759 return core_schema.tuple_schema([])
1760 elif params[-1] is Ellipsis:
1761 if len(params) == 2:
1762 return core_schema.tuple_schema([self.generate_schema(params[0])], variadic_item_index=0)
1763 else:
1764 # TODO: something like https://github.com/pydantic/pydantic/issues/5952
1765 raise ValueError('Variable tuples can only have one type')
1766 elif len(params) == 1 and params[0] == ():
1767 # special case for `tuple[()]` which means `tuple[]` - an empty tuple
1768 # NOTE: This conditional can be removed when we drop support for Python 3.10.
1769 return core_schema.tuple_schema([])
1770 else:
1771 return core_schema.tuple_schema([self.generate_schema(param) for param in params])
1772
1773 def _type_schema(self) -> core_schema.CoreSchema:
1774 return core_schema.custom_error_schema(
1775 core_schema.is_instance_schema(type),
1776 custom_error_type='is_type',
1777 custom_error_message='Input should be a type',
1778 )
1779
1780 def _zoneinfo_schema(self) -> core_schema.CoreSchema:
1781 """Generate schema for a zone_info.ZoneInfo object"""
1782 from ._validators import validate_str_is_valid_iana_tz
1783
1784 metadata = {'pydantic_js_functions': [lambda _1, _2: {'type': 'string', 'format': 'zoneinfo'}]}
1785 return core_schema.no_info_plain_validator_function(
1786 validate_str_is_valid_iana_tz,
1787 serialization=core_schema.to_string_ser_schema(),
1788 metadata=metadata,
1789 )
1790
1791 def _union_is_subclass_schema(self, union_type: Any) -> core_schema.CoreSchema:
1792 """Generate schema for `type[Union[X, ...]]`."""
1793 args = self._get_args_resolving_forward_refs(union_type, required=True)
1794 return core_schema.union_schema([self.generate_schema(type[args]) for args in args])
1795
1796 def _subclass_schema(self, type_: Any) -> core_schema.CoreSchema:
1797 """Generate schema for a type, e.g. `type[int]`."""
1798 type_param = self._get_first_arg_or_any(type_)
1799
1800 # Assume `type[Annotated[<typ>, ...]]` is equivalent to `type[<typ>]`:
1801 type_param = _typing_extra.annotated_type(type_param) or type_param
1802
1803 if typing_objects.is_any(type_param):
1804 return self._type_schema()
1805 elif typing_objects.is_typealiastype(type_param):
1806 return self.generate_schema(type[type_param.__value__])
1807 elif typing_objects.is_typevar(type_param):
1808 if type_param.__bound__:
1809 if is_union_origin(get_origin(type_param.__bound__)):
1810 return self._union_is_subclass_schema(type_param.__bound__)
1811 return core_schema.is_subclass_schema(type_param.__bound__)
1812 elif type_param.__constraints__:
1813 return core_schema.union_schema([self.generate_schema(type[c]) for c in type_param.__constraints__])
1814 else:
1815 return self._type_schema()
1816 elif is_union_origin(get_origin(type_param)):
1817 return self._union_is_subclass_schema(type_param)
1818 else:
1819 if typing_objects.is_self(type_param):
1820 type_param = self._resolve_self_type(type_param)
1821 if _typing_extra.is_generic_alias(type_param):
1822 raise PydanticUserError(
1823 'Subscripting `type[]` with an already parametrized type is not supported. '
1824 f'Instead of using type[{type_param!r}], use type[{_repr.display_as_type(get_origin(type_param))}].',
1825 code=None,
1826 )
1827 if not inspect.isclass(type_param):
1828 # when using type[None], this doesn't type convert to type[NoneType], and None isn't a class
1829 # so we handle it manually here
1830 if type_param is None:
1831 return core_schema.is_subclass_schema(NoneType)
1832 raise TypeError(f'Expected a class, got {type_param!r}')
1833 return core_schema.is_subclass_schema(type_param)
1834
1835 def _sequence_schema(self, items_type: Any) -> core_schema.CoreSchema:
1836 """Generate schema for a Sequence, e.g. `Sequence[int]`."""
1837 from ._serializers import serialize_sequence_via_list
1838
1839 item_type_schema = self.generate_schema(items_type)
1840 list_schema = core_schema.list_schema(item_type_schema)
1841
1842 json_schema = smart_deepcopy(list_schema)
1843 python_schema = core_schema.is_instance_schema(typing.Sequence, cls_repr='Sequence')
1844 if not typing_objects.is_any(items_type):
1845 from ._validators import sequence_validator
1846
1847 python_schema = core_schema.chain_schema(
1848 [python_schema, core_schema.no_info_wrap_validator_function(sequence_validator, list_schema)],
1849 )
1850
1851 serialization = core_schema.wrap_serializer_function_ser_schema(
1852 serialize_sequence_via_list, schema=item_type_schema, info_arg=True
1853 )
1854 return core_schema.json_or_python_schema(
1855 json_schema=json_schema, python_schema=python_schema, serialization=serialization
1856 )
1857
1858 def _iterable_schema(self, type_: Any) -> core_schema.GeneratorSchema:
1859 """Generate a schema for an `Iterable`."""
1860 item_type = self._get_first_arg_or_any(type_)
1861
1862 return core_schema.generator_schema(self.generate_schema(item_type))
1863
1864 def _pattern_schema(self, pattern_type: Any) -> core_schema.CoreSchema:
1865 from . import _validators
1866
1867 metadata = {'pydantic_js_functions': [lambda _1, _2: {'type': 'string', 'format': 'regex'}]}
1868 ser = core_schema.plain_serializer_function_ser_schema(
1869 attrgetter('pattern'), when_used='json', return_schema=core_schema.str_schema()
1870 )
1871 if pattern_type is typing.Pattern or pattern_type is re.Pattern:
1872 # bare type
1873 return core_schema.no_info_plain_validator_function(
1874 _validators.pattern_either_validator, serialization=ser, metadata=metadata
1875 )
1876
1877 param = self._get_args_resolving_forward_refs(
1878 pattern_type,
1879 required=True,
1880 )[0]
1881 if param is str:
1882 return core_schema.no_info_plain_validator_function(
1883 _validators.pattern_str_validator, serialization=ser, metadata=metadata
1884 )
1885 elif param is bytes:
1886 return core_schema.no_info_plain_validator_function(
1887 _validators.pattern_bytes_validator, serialization=ser, metadata=metadata
1888 )
1889 else:
1890 raise PydanticSchemaGenerationError(f'Unable to generate pydantic-core schema for {pattern_type!r}.')
1891
1892 def _hashable_schema(self) -> core_schema.CoreSchema:
1893 return core_schema.custom_error_schema(
1894 schema=core_schema.json_or_python_schema(
1895 json_schema=core_schema.chain_schema(
1896 [core_schema.any_schema(), core_schema.is_instance_schema(collections.abc.Hashable)]
1897 ),
1898 python_schema=core_schema.is_instance_schema(collections.abc.Hashable),
1899 ),
1900 custom_error_type='is_hashable',
1901 custom_error_message='Input should be hashable',
1902 )
1903
1904 def _dataclass_schema(
1905 self, dataclass: type[StandardDataclass], origin: type[StandardDataclass] | None
1906 ) -> core_schema.CoreSchema:
1907 """Generate schema for a dataclass."""
1908 dataclass_ref = _type_refs.class_type_ref(dataclass, origin)
1909 with (
1910 self.model_type_stack.push(dataclass),
1911 self.defs.get_definition_ref_schema(ref=dataclass_ref) as maybe_schema,
1912 ):
1913 if maybe_schema is not None:
1914 return maybe_schema
1915
1916 schema = dataclass.__dict__.get('__pydantic_core_schema__')
1917 if schema is not None and not isinstance(schema, MockCoreSchema):
1918 if schema['type'] == 'definitions':
1919 schema = self.defs.unpack_definitions(schema)
1920 ref = get_ref(schema)
1921 if ref:
1922 return self.defs.create_definition_reference_schema(schema)
1923 else:
1924 return schema
1925
1926 typevars_map = get_standard_typevars_map(dataclass)
1927 if origin is not None:
1928 dataclass = origin
1929
1930 # if (plain) dataclass doesn't have config, we use the parent's config, hence a default of `None`
1931 # (Pydantic dataclasses have an empty dict config by default).
1932 # see https://github.com/pydantic/pydantic/issues/10917
1933 config = getattr(dataclass, '__pydantic_config__', None)
1934
1935 from ..dataclasses import is_pydantic_dataclass
1936
1937 with self._ns_resolver.push(dataclass), self._config_wrapper_stack.push(config):
1938 if is_pydantic_dataclass(dataclass):
1939 if dataclass.__pydantic_fields_complete__():
1940 # Copy the field info instances to avoid mutating the `FieldInfo` instances
1941 # of the generic dataclass generic origin (e.g. `apply_typevars_map` below).
1942 # Note that we don't apply `deepcopy` on `__pydantic_fields__` because we
1943 # don't want to copy the `FieldInfo` attributes:
1944 fields = {
1945 f_name: copy(field_info) for f_name, field_info in dataclass.__pydantic_fields__.items()
1946 }
1947 if typevars_map:
1948 for field in fields.values():
1949 field.apply_typevars_map(typevars_map, *self._types_namespace)
1950 else:
1951 try:
1952 fields = rebuild_dataclass_fields(
1953 dataclass,
1954 config_wrapper=self._config_wrapper,
1955 ns_resolver=self._ns_resolver,
1956 typevars_map=typevars_map or {},
1957 )
1958 except NameError as e:
1959 raise PydanticUndefinedAnnotation.from_name_error(e) from e
1960 else:
1961 fields = collect_dataclass_fields(
1962 dataclass,
1963 typevars_map=typevars_map,
1964 config_wrapper=self._config_wrapper,
1965 )
1966
1967 if self._config_wrapper.extra == 'allow':
1968 # disallow combination of init=False on a dataclass field and extra='allow' on a dataclass
1969 for field_name, field in fields.items():
1970 if field.init is False:
1971 raise PydanticUserError(
1972 f'Field {field_name} has `init=False` and dataclass has config setting `extra="allow"`. '
1973 f'This combination is not allowed.',
1974 code='dataclass-init-false-extra-allow',
1975 )
1976
1977 decorators = dataclass.__dict__.get('__pydantic_decorators__')
1978 if decorators is None:
1979 decorators = DecoratorInfos.build(dataclass, replace_wrapped_methods=False)
1980 decorators.update_from_config(self._config_wrapper)
1981 # Move kw_only=False args to the start of the list, as this is how vanilla dataclasses work.
1982 # Note that when kw_only is missing or None, it is treated as equivalent to kw_only=True
1983 args = sorted(
1984 (self._generate_dc_field_schema(k, v, decorators) for k, v in fields.items()),
1985 key=lambda a: a.get('kw_only') is not False,
1986 )
1987 has_post_init = hasattr(dataclass, '__post_init__')
1988 has_slots = hasattr(dataclass, '__slots__')
1989
1990 args_schema = core_schema.dataclass_args_schema(
1991 dataclass.__name__,
1992 args,
1993 computed_fields=[
1994 self._computed_field_schema(d, decorators.field_serializers)
1995 for d in decorators.computed_fields.values()
1996 ],
1997 collect_init_only=has_post_init,
1998 )
1999
2000 inner_schema = apply_validators(args_schema, decorators.root_validators.values())
2001
2002 model_validators = decorators.model_validators.values()
2003 inner_schema = apply_model_validators(inner_schema, model_validators, 'inner')
2004
2005 core_config = self._config_wrapper.core_config(title=dataclass.__name__)
2006
2007 dc_schema = core_schema.dataclass_schema(
2008 dataclass,
2009 inner_schema,
2010 generic_origin=origin,
2011 post_init=has_post_init,
2012 ref=dataclass_ref,
2013 fields=[field.name for field in dataclasses.fields(dataclass)],
2014 slots=has_slots,
2015 config=core_config,
2016 # we don't use a custom __setattr__ for dataclasses, so we must
2017 # pass along the frozen config setting to the pydantic-core schema
2018 frozen=self._config_wrapper_stack.tail.frozen,
2019 )
2020 schema = self._apply_model_serializers(dc_schema, decorators.model_serializers.values())
2021 schema = apply_model_validators(schema, model_validators, 'outer')
2022 return self.defs.create_definition_reference_schema(schema)
2023
2024 def _call_schema(self, function: ValidateCallSupportedTypes) -> core_schema.CallSchema:
2025 """Generate schema for a Callable.
2026
2027 TODO support functional validators once we support them in Config
2028 """
2029 arguments_schema = self._arguments_schema(function)
2030
2031 return_schema: core_schema.CoreSchema | None = None
2032 config_wrapper = self._config_wrapper
2033 if config_wrapper.validate_return:
2034 sig = _typing_extra.signature_no_eval(function)
2035 return_hint = sig.return_annotation
2036 if return_hint is not sig.empty:
2037 globalns, localns = self._types_namespace
2038 type_hints = _typing_extra.get_function_type_hints(
2039 function, globalns=globalns, localns=localns, include_keys={'return'}
2040 )
2041 return_schema = self.generate_schema(type_hints['return'])
2042
2043 return core_schema.call_schema(
2044 arguments_schema,
2045 function,
2046 return_schema=return_schema,
2047 )
2048
2049 def _arguments_schema(
2050 self, function: ValidateCallSupportedTypes, parameters_callback: ParametersCallback | None = None
2051 ) -> core_schema.ArgumentsSchema:
2052 """Generate schema for a Signature."""
2053 mode_lookup: dict[_ParameterKind, Literal['positional_only', 'positional_or_keyword', 'keyword_only']] = {
2054 Parameter.POSITIONAL_ONLY: 'positional_only',
2055 Parameter.POSITIONAL_OR_KEYWORD: 'positional_or_keyword',
2056 Parameter.KEYWORD_ONLY: 'keyword_only',
2057 }
2058
2059 sig = _typing_extra.signature_no_eval(function)
2060 globalns, localns = self._types_namespace
2061 type_hints = _typing_extra.get_function_type_hints(function, globalns=globalns, localns=localns)
2062
2063 arguments_list: list[core_schema.ArgumentsParameter] = []
2064 var_args_schema: core_schema.CoreSchema | None = None
2065 var_kwargs_schema: core_schema.CoreSchema | None = None
2066 var_kwargs_mode: core_schema.VarKwargsMode | None = None
2067
2068 core_config = self._config_wrapper.core_config(title=None)
2069
2070 for i, (name, p) in enumerate(sig.parameters.items()):
2071 if p.annotation is sig.empty:
2072 annotation = typing.cast(Any, Any)
2073 else:
2074 annotation = type_hints[name]
2075
2076 if parameters_callback is not None:
2077 result = parameters_callback(i, name, annotation)
2078 if result == 'skip':
2079 continue
2080
2081 parameter_mode = mode_lookup.get(p.kind)
2082 if parameter_mode is not None:
2083 arg_schema = self._generate_parameter_schema(
2084 name, annotation, AnnotationSource.FUNCTION, p.default, parameter_mode
2085 )
2086 arguments_list.append(arg_schema)
2087 elif p.kind == Parameter.VAR_POSITIONAL:
2088 var_args_schema = self.generate_schema(annotation)
2089 else:
2090 assert p.kind == Parameter.VAR_KEYWORD, p.kind
2091
2092 unpack_type = _typing_extra.unpack_type(annotation)
2093 if unpack_type is not None:
2094 origin = get_origin(unpack_type) or unpack_type
2095 if not is_typeddict(origin):
2096 raise PydanticUserError(
2097 f'Expected a `TypedDict` class inside `Unpack[...]`, got {unpack_type!r}',
2098 code='unpack-typed-dict',
2099 )
2100 non_pos_only_param_names = {
2101 name for name, p in sig.parameters.items() if p.kind != Parameter.POSITIONAL_ONLY
2102 }
2103 overlapping_params = non_pos_only_param_names.intersection(origin.__annotations__)
2104 if overlapping_params:
2105 raise PydanticUserError(
2106 f'Typed dictionary {origin.__name__!r} overlaps with parameter'
2107 f'{"s" if len(overlapping_params) >= 2 else ""} '
2108 f'{", ".join(repr(p) for p in sorted(overlapping_params))}',
2109 code='overlapping-unpack-typed-dict',
2110 )
2111
2112 var_kwargs_mode = 'unpacked-typed-dict'
2113 var_kwargs_schema = self._typed_dict_schema(unpack_type, get_origin(unpack_type))
2114 else:
2115 var_kwargs_mode = 'uniform'
2116 var_kwargs_schema = self.generate_schema(annotation)
2117
2118 return core_schema.arguments_schema(
2119 arguments_list,
2120 var_args_schema=var_args_schema,
2121 var_kwargs_mode=var_kwargs_mode,
2122 var_kwargs_schema=var_kwargs_schema,
2123 validate_by_name=core_config.get('validate_by_name'),
2124 )
2125
2126 def _arguments_v3_schema(
2127 self, function: ValidateCallSupportedTypes, parameters_callback: ParametersCallback | None = None
2128 ) -> core_schema.ArgumentsV3Schema:
2129 mode_lookup: dict[
2130 _ParameterKind, Literal['positional_only', 'positional_or_keyword', 'var_args', 'keyword_only']
2131 ] = {
2132 Parameter.POSITIONAL_ONLY: 'positional_only',
2133 Parameter.POSITIONAL_OR_KEYWORD: 'positional_or_keyword',
2134 Parameter.VAR_POSITIONAL: 'var_args',
2135 Parameter.KEYWORD_ONLY: 'keyword_only',
2136 }
2137
2138 sig = _typing_extra.signature_no_eval(function)
2139 globalns, localns = self._types_namespace
2140 type_hints = _typing_extra.get_function_type_hints(function, globalns=globalns, localns=localns)
2141
2142 parameters_list: list[core_schema.ArgumentsV3Parameter] = []
2143 core_config = self._config_wrapper.core_config(title=None)
2144
2145 for i, (name, p) in enumerate(sig.parameters.items()):
2146 if parameters_callback is not None:
2147 result = parameters_callback(i, name, p.annotation)
2148 if result == 'skip':
2149 continue
2150
2151 if p.annotation is Parameter.empty:
2152 annotation = typing.cast(Any, Any)
2153 else:
2154 annotation = type_hints[name]
2155
2156 parameter_mode = mode_lookup.get(p.kind)
2157 if parameter_mode is None:
2158 assert p.kind == Parameter.VAR_KEYWORD, p.kind
2159
2160 unpack_type = _typing_extra.unpack_type(annotation)
2161 if unpack_type is not None:
2162 origin = get_origin(unpack_type) or unpack_type
2163 if not is_typeddict(origin):
2164 raise PydanticUserError(
2165 f'Expected a `TypedDict` class inside `Unpack[...]`, got {unpack_type!r}',
2166 code='unpack-typed-dict',
2167 )
2168 non_pos_only_param_names = {
2169 name for name, p in sig.parameters.items() if p.kind != Parameter.POSITIONAL_ONLY
2170 }
2171 overlapping_params = non_pos_only_param_names.intersection(origin.__annotations__)
2172 if overlapping_params:
2173 raise PydanticUserError(
2174 f'Typed dictionary {origin.__name__!r} overlaps with parameter'
2175 f'{"s" if len(overlapping_params) >= 2 else ""} '
2176 f'{", ".join(repr(p) for p in sorted(overlapping_params))}',
2177 code='overlapping-unpack-typed-dict',
2178 )
2179 parameter_mode = 'var_kwargs_unpacked_typed_dict'
2180 annotation = unpack_type
2181 else:
2182 parameter_mode = 'var_kwargs_uniform'
2183
2184 parameters_list.append(
2185 self._generate_parameter_v3_schema(
2186 name, annotation, AnnotationSource.FUNCTION, parameter_mode, default=p.default
2187 )
2188 )
2189
2190 return core_schema.arguments_v3_schema(
2191 parameters_list,
2192 validate_by_name=core_config.get('validate_by_name'),
2193 )
2194
2195 def _unsubstituted_typevar_schema(self, typevar: typing.TypeVar) -> core_schema.CoreSchema:
2196 try:
2197 has_default = typevar.has_default() # pyright: ignore[reportAttributeAccessIssue]
2198 except AttributeError:
2199 # Happens if using `typing.TypeVar` (and not `typing_extensions`) on Python < 3.13
2200 pass
2201 else:
2202 if has_default:
2203 return self.generate_schema(typevar.__default__) # pyright: ignore[reportAttributeAccessIssue]
2204
2205 if constraints := typevar.__constraints__:
2206 return self._union_schema(typing.Union[constraints]) # noqa: UP007
2207
2208 if bound := typevar.__bound__:
2209 schema = self.generate_schema(bound)
2210 schema['serialization'] = core_schema.simple_ser_schema('any')
2211 return schema
2212
2213 return core_schema.any_schema()
2214
2215 def _computed_field_schema(
2216 self,
2217 d: Decorator[ComputedFieldInfo],
2218 field_serializers: dict[str, Decorator[FieldSerializerDecoratorInfo]],
2219 ) -> core_schema.ComputedField:
2220 if d.info.return_type is not PydanticUndefined:
2221 return_type = d.info.return_type
2222 else:
2223 try:
2224 # Do not pass in globals as the function could be defined in a different module.
2225 # Instead, let `get_callable_return_type` infer the globals to use, but still pass
2226 # in locals that may contain a parent/rebuild namespace:
2227 return_type = _decorators.get_callable_return_type(d.func, localns=self._types_namespace.locals)
2228 except NameError as e:
2229 raise PydanticUndefinedAnnotation.from_name_error(e) from e
2230 if return_type is PydanticUndefined:
2231 raise PydanticUserError(
2232 'Computed field is missing return type annotation or specifying `return_type`'
2233 ' to the `@computed_field` decorator (e.g. `@computed_field(return_type=int | str)`)',
2234 code='model-field-missing-annotation',
2235 )
2236
2237 return_type = replace_types(return_type, self._typevars_map)
2238 # Create a new ComputedFieldInfo so that different type parametrizations of the same
2239 # generic model's computed field can have different return types.
2240 d.info = dataclasses.replace(d.info, return_type=return_type)
2241 return_type_schema = self.generate_schema(return_type)
2242 # Apply serializers to computed field if there exist
2243 return_type_schema = self._apply_field_serializers(
2244 return_type_schema,
2245 filter_field_decorator_info_by_field(field_serializers.values(), d.cls_var_name),
2246 )
2247
2248 pydantic_js_updates, pydantic_js_extra = _extract_json_schema_info_from_field_info(d.info)
2249 core_metadata: dict[str, Any] = {}
2250 update_core_metadata(
2251 core_metadata,
2252 pydantic_js_updates={'readOnly': True, **(pydantic_js_updates if pydantic_js_updates else {})},
2253 pydantic_js_extra=pydantic_js_extra,
2254 )
2255 exclude_if = d.info.exclude_if
2256 # TODO: Should we support exclude_if from annotations?
2257 return core_schema.computed_field(
2258 d.cls_var_name,
2259 return_schema=return_type_schema,
2260 alias=d.info.alias,
2261 serialization_exclude_if=exclude_if,
2262 metadata=core_metadata,
2263 )
2264
2265 def _annotated_schema(self, annotated_type: Any) -> core_schema.CoreSchema:
2266 """Generate schema for an Annotated type, e.g. `Annotated[int, Field(...)]` or `Annotated[int, Gt(0)]`."""
2267 FieldInfo = import_cached_field_info()
2268 source_type, *annotations = self._get_args_resolving_forward_refs(
2269 annotated_type,
2270 required=True,
2271 )
2272 schema = self._apply_annotations(source_type, annotations)
2273 # put the default validator last so that TypeAdapter.get_default_value() works
2274 # even if there are function validators involved
2275 for annotation in annotations:
2276 if isinstance(annotation, FieldInfo):
2277 schema = wrap_default(annotation, schema)
2278 return schema
2279
2280 def _apply_annotations(
2281 self,
2282 source_type: Any,
2283 annotations: list[Any],
2284 transform_inner_schema: Callable[[CoreSchema], CoreSchema] = lambda x: x,
2285 check_unsupported_field_info_attributes: bool = True,
2286 ) -> CoreSchema:
2287 """Apply arguments from `Annotated` or from `FieldInfo` to a schema.
2288
2289 This gets called by `GenerateSchema._annotated_schema` but differs from it in that it does
2290 not expect `source_type` to be an `Annotated` object, it expects it to be the first argument of that
2291 (in other words, `GenerateSchema._annotated_schema` just unpacks `Annotated`, this process it).
2292 """
2293 annotations = list(_known_annotated_metadata.expand_grouped_metadata(annotations))
2294
2295 pydantic_js_annotation_functions: list[GetJsonSchemaFunction] = []
2296
2297 def inner_handler(obj: Any) -> CoreSchema:
2298 origin = get_origin(obj)
2299 schema: CoreSchema | None = None
2300 if origin is None:
2301 # If the type has an origin, it is guaranteed to *not* be an ordinary class that could have
2302 # a `__get_pydantic_core_schema__()` method:
2303 schema = self._generate_schema_from_get_schema_method(obj, source_type)
2304
2305 if schema is None:
2306 schema = self._generate_schema_inner(obj, origin)
2307
2308 # `__get_pydantic_json_schema__()` is checked on the origin if it exists:
2309 metadata_js_function = _extract_get_pydantic_json_schema(origin if origin is not None else obj)
2310 if metadata_js_function is not None:
2311 metadata_schema = resolve_original_schema(schema, self.defs)
2312 if metadata_schema is not None:
2313 self._add_js_function(metadata_schema, metadata_js_function)
2314 return transform_inner_schema(schema)
2315
2316 get_inner_schema = CallbackGetCoreSchemaHandler(inner_handler, self)
2317
2318 for annotation in annotations:
2319 if annotation is None:
2320 continue
2321 get_inner_schema = self._get_wrapped_inner_schema(
2322 get_inner_schema,
2323 annotation,
2324 pydantic_js_annotation_functions,
2325 check_unsupported_field_info_attributes=check_unsupported_field_info_attributes,
2326 )
2327
2328 schema = get_inner_schema(source_type)
2329 if pydantic_js_annotation_functions:
2330 core_metadata = schema.setdefault('metadata', {})
2331 update_core_metadata(core_metadata, pydantic_js_annotation_functions=pydantic_js_annotation_functions)
2332 return _add_custom_serialization_from_json_encoders(self._config_wrapper.json_encoders, source_type, schema)
2333
2334 def _apply_single_annotation(
2335 self,
2336 schema: core_schema.CoreSchema,
2337 metadata: Any,
2338 check_unsupported_field_info_attributes: bool = True,
2339 ) -> core_schema.CoreSchema:
2340 FieldInfo = import_cached_field_info()
2341
2342 if isinstance(metadata, FieldInfo):
2343 if (
2344 check_unsupported_field_info_attributes
2345 # HACK: we don't want to emit the warning for `FieldInfo` subclasses, because FastAPI does weird manipulations
2346 # with its subclasses and their annotations:
2347 and type(metadata) is FieldInfo
2348 ):
2349 for attr, value in (unsupported_attributes := self._get_unsupported_field_info_attributes(metadata)):
2350 warnings.warn(
2351 f'The {attr!r} attribute with value {value!r} was provided to the `Field()` function, '
2352 f'which has no effect in the context it was used. {attr!r} is field-specific metadata, '
2353 'and can only be attached to a model field using `Annotated` metadata or by assignment. '
2354 'This may have happened because an `Annotated` type alias using the `type` statement was '
2355 'used, or if the `Field()` function was attached to a single member of a union type.',
2356 category=UnsupportedFieldAttributeWarning,
2357 )
2358
2359 if (
2360 metadata.default_factory_takes_validated_data
2361 and self.model_type_stack.get() is None
2362 and 'defaut_factory' not in unsupported_attributes
2363 ):
2364 warnings.warn(
2365 "A 'default_factory' taking validated data as an argument was provided to the `Field()` function, "
2366 'but no validated data is available in the context it was used.',
2367 category=UnsupportedFieldAttributeWarning,
2368 )
2369
2370 for field_metadata in metadata.metadata:
2371 schema = self._apply_single_annotation(schema, field_metadata)
2372
2373 if metadata.discriminator is not None:
2374 schema = self._apply_discriminator_to_union(schema, metadata.discriminator)
2375 return schema
2376
2377 if schema['type'] == 'nullable':
2378 # for nullable schemas, metadata is automatically applied to the inner schema
2379 inner = schema.get('schema', core_schema.any_schema())
2380 inner = self._apply_single_annotation(inner, metadata)
2381 if inner:
2382 schema['schema'] = inner
2383 return schema
2384
2385 if schema['type'] == 'missing-sentinel' and (inner := schema.get('schema')) is not None:
2386 # Same behavior as for nullable schemas: metadata is automatically applied to the inner schema
2387 inner = self._apply_single_annotation(inner, metadata)
2388 if inner:
2389 schema['schema'] = inner
2390 return schema
2391
2392 original_schema = schema
2393 ref = schema.get('ref')
2394 if ref is not None:
2395 schema = schema.copy()
2396 new_ref = ref + f'_{repr(metadata)}'
2397 if (existing := self.defs.get_schema_from_ref(new_ref)) is not None:
2398 return existing
2399 schema['ref'] = new_ref # pyright: ignore[reportGeneralTypeIssues]
2400 elif schema['type'] == 'definition-ref':
2401 ref = schema['schema_ref']
2402 if (referenced_schema := self.defs.get_schema_from_ref(ref)) is not None:
2403 schema = referenced_schema.copy()
2404 new_ref = ref + f'_{repr(metadata)}'
2405 if (existing := self.defs.get_schema_from_ref(new_ref)) is not None:
2406 return existing
2407 schema['ref'] = new_ref # pyright: ignore[reportGeneralTypeIssues]
2408
2409 maybe_updated_schema = _known_annotated_metadata.apply_known_metadata(metadata, schema)
2410
2411 if maybe_updated_schema is not None:
2412 return maybe_updated_schema
2413 return original_schema
2414
2415 def _apply_single_annotation_json_schema(
2416 self, schema: core_schema.CoreSchema, metadata: Any
2417 ) -> core_schema.CoreSchema:
2418 FieldInfo = import_cached_field_info()
2419
2420 if isinstance(metadata, FieldInfo):
2421 for field_metadata in metadata.metadata:
2422 schema = self._apply_single_annotation_json_schema(schema, field_metadata)
2423
2424 pydantic_js_updates, pydantic_js_extra = _extract_json_schema_info_from_field_info(metadata)
2425 core_metadata = schema.setdefault('metadata', {})
2426 update_core_metadata(
2427 core_metadata, pydantic_js_updates=pydantic_js_updates, pydantic_js_extra=pydantic_js_extra
2428 )
2429 return schema
2430
2431 def _get_unsupported_field_info_attributes(self, field_info: FieldInfo) -> list[tuple[str, Any]]:
2432 """Get the list of unsupported `FieldInfo` attributes when not directly used in `Annotated` for field annotations."""
2433 unused_metadata: list[tuple[str, Any]] = []
2434 for unused_metadata_name, unset_value in UNSUPPORTED_STANDALONE_FIELDINFO_ATTRIBUTES:
2435 if (
2436 (unused_metadata_value := getattr(field_info, unused_metadata_name)) is not unset_value
2437 # `default` and `default_factory` can still be used with a type adapter, so only include them
2438 # if used with a model-like class:
2439 and (
2440 unused_metadata_name not in ('default', 'default_factory')
2441 or self.model_type_stack.get() is not None
2442 )
2443 # Setting `alias` will set `validation/serialization_alias` as well, so we want to avoid duplicate warnings:
2444 and (
2445 unused_metadata_name not in ('validation_alias', 'serialization_alias')
2446 or 'alias' not in field_info._attributes_set
2447 )
2448 ):
2449 unused_metadata.append((unused_metadata_name, unused_metadata_value))
2450
2451 return unused_metadata
2452
2453 def _get_wrapped_inner_schema(
2454 self,
2455 get_inner_schema: GetCoreSchemaHandler,
2456 annotation: Any,
2457 pydantic_js_annotation_functions: list[GetJsonSchemaFunction],
2458 check_unsupported_field_info_attributes: bool = False,
2459 ) -> CallbackGetCoreSchemaHandler:
2460 annotation_get_schema: GetCoreSchemaFunction | None = getattr(annotation, '__get_pydantic_core_schema__', None)
2461
2462 def new_handler(source: Any) -> core_schema.CoreSchema:
2463 if annotation_get_schema is not None:
2464 schema = annotation_get_schema(source, get_inner_schema)
2465 else:
2466 schema = get_inner_schema(source)
2467 schema = self._apply_single_annotation(
2468 schema,
2469 annotation,
2470 check_unsupported_field_info_attributes=check_unsupported_field_info_attributes,
2471 )
2472 schema = self._apply_single_annotation_json_schema(schema, annotation)
2473
2474 metadata_js_function = _extract_get_pydantic_json_schema(annotation)
2475 if metadata_js_function is not None:
2476 pydantic_js_annotation_functions.append(metadata_js_function)
2477 return schema
2478
2479 return CallbackGetCoreSchemaHandler(new_handler, self)
2480
2481 def _apply_field_serializers(
2482 self,
2483 schema: core_schema.CoreSchema,
2484 serializers: list[Decorator[FieldSerializerDecoratorInfo]],
2485 ) -> core_schema.CoreSchema:
2486 """Apply field serializers to a schema."""
2487 if serializers:
2488 schema = copy(schema)
2489 if schema['type'] == 'definitions':
2490 inner_schema = schema['schema']
2491 schema['schema'] = self._apply_field_serializers(inner_schema, serializers)
2492 return schema
2493 elif 'ref' in schema:
2494 schema = self.defs.create_definition_reference_schema(schema)
2495
2496 # use the last serializer to make it easy to override a serializer set on a parent model
2497 serializer = serializers[-1]
2498 is_field_serializer, info_arg = inspect_field_serializer(serializer.func, serializer.info.mode)
2499
2500 if serializer.info.return_type is not PydanticUndefined:
2501 return_type = serializer.info.return_type
2502 else:
2503 try:
2504 # Do not pass in globals as the function could be defined in a different module.
2505 # Instead, let `get_callable_return_type` infer the globals to use, but still pass
2506 # in locals that may contain a parent/rebuild namespace:
2507 return_type = _decorators.get_callable_return_type(
2508 serializer.func, localns=self._types_namespace.locals
2509 )
2510 except NameError as e:
2511 raise PydanticUndefinedAnnotation.from_name_error(e) from e
2512
2513 if return_type is PydanticUndefined:
2514 return_schema = None
2515 else:
2516 return_schema = self.generate_schema(return_type)
2517
2518 if serializer.info.mode == 'wrap':
2519 schema['serialization'] = core_schema.wrap_serializer_function_ser_schema(
2520 serializer.func,
2521 is_field_serializer=is_field_serializer,
2522 info_arg=info_arg,
2523 return_schema=return_schema,
2524 when_used=serializer.info.when_used,
2525 )
2526 else:
2527 assert serializer.info.mode == 'plain'
2528 schema['serialization'] = core_schema.plain_serializer_function_ser_schema(
2529 serializer.func,
2530 is_field_serializer=is_field_serializer,
2531 info_arg=info_arg,
2532 return_schema=return_schema,
2533 when_used=serializer.info.when_used,
2534 )
2535 return schema
2536
2537 def _apply_model_serializers(
2538 self, schema: core_schema.CoreSchema, serializers: Iterable[Decorator[ModelSerializerDecoratorInfo]]
2539 ) -> core_schema.CoreSchema:
2540 """Apply model serializers to a schema."""
2541 ref: str | None = schema.pop('ref', None) # type: ignore
2542 if serializers:
2543 serializer = list(serializers)[-1]
2544 info_arg = inspect_model_serializer(serializer.func, serializer.info.mode)
2545
2546 if serializer.info.return_type is not PydanticUndefined:
2547 return_type = serializer.info.return_type
2548 else:
2549 try:
2550 # Do not pass in globals as the function could be defined in a different module.
2551 # Instead, let `get_callable_return_type` infer the globals to use, but still pass
2552 # in locals that may contain a parent/rebuild namespace:
2553 return_type = _decorators.get_callable_return_type(
2554 serializer.func, localns=self._types_namespace.locals
2555 )
2556 except NameError as e:
2557 raise PydanticUndefinedAnnotation.from_name_error(e) from e
2558
2559 if return_type is PydanticUndefined:
2560 return_schema = None
2561 else:
2562 return_schema = self.generate_schema(return_type)
2563
2564 if serializer.info.mode == 'wrap':
2565 ser_schema: core_schema.SerSchema = core_schema.wrap_serializer_function_ser_schema(
2566 serializer.func,
2567 info_arg=info_arg,
2568 return_schema=return_schema,
2569 when_used=serializer.info.when_used,
2570 )
2571 else:
2572 # plain
2573 ser_schema = core_schema.plain_serializer_function_ser_schema(
2574 serializer.func,
2575 info_arg=info_arg,
2576 return_schema=return_schema,
2577 when_used=serializer.info.when_used,
2578 )
2579 schema['serialization'] = ser_schema
2580 if ref:
2581 schema['ref'] = ref # type: ignore
2582 return schema
2583
2584
2585_VALIDATOR_F_MATCH: Mapping[
2586 tuple[FieldValidatorModes, Literal['no-info', 'with-info']],
2587 Callable[[Callable[..., Any], core_schema.CoreSchema], core_schema.CoreSchema],
2588] = {
2589 ('before', 'no-info'): lambda f, schema: core_schema.no_info_before_validator_function(f, schema),
2590 ('after', 'no-info'): lambda f, schema: core_schema.no_info_after_validator_function(f, schema),
2591 ('plain', 'no-info'): lambda f, _: core_schema.no_info_plain_validator_function(f),
2592 ('wrap', 'no-info'): lambda f, schema: core_schema.no_info_wrap_validator_function(f, schema),
2593 ('before', 'with-info'): lambda f, schema: core_schema.with_info_before_validator_function(f, schema),
2594 ('after', 'with-info'): lambda f, schema: core_schema.with_info_after_validator_function(f, schema),
2595 ('plain', 'with-info'): lambda f, _: core_schema.with_info_plain_validator_function(f),
2596 ('wrap', 'with-info'): lambda f, schema: core_schema.with_info_wrap_validator_function(f, schema),
2597}
2598
2599
2600# TODO V3: this function is only used for deprecated decorators. It should
2601# be removed once we drop support for those.
2602def apply_validators(
2603 schema: core_schema.CoreSchema,
2604 validators: Iterable[Decorator[RootValidatorDecoratorInfo]]
2605 | Iterable[Decorator[ValidatorDecoratorInfo]]
2606 | Iterable[Decorator[FieldValidatorDecoratorInfo]],
2607) -> core_schema.CoreSchema:
2608 """Apply validators to a schema.
2609
2610 Args:
2611 schema: The schema to apply validators on.
2612 validators: An iterable of validators.
2613
2614 Returns:
2615 The updated schema.
2616 """
2617 for validator in validators:
2618 # Actually, type could be 'field' or 'model', but this is only used for deprecated
2619 # decorators, so let's not worry about it.
2620 info_arg = inspect_validator(validator.func, mode=validator.info.mode, type='field')
2621 val_type = 'with-info' if info_arg else 'no-info'
2622
2623 schema = _VALIDATOR_F_MATCH[(validator.info.mode, val_type)](validator.func, schema)
2624 return schema
2625
2626
2627def _validators_require_validate_default(validators: Iterable[Decorator[ValidatorDecoratorInfo]]) -> bool:
2628 """In v1, if any of the validators for a field had `always=True`, the default value would be validated.
2629
2630 This serves as an auxiliary function for re-implementing that logic, by looping over a provided
2631 collection of (v1-style) ValidatorDecoratorInfo's and checking if any of them have `always=True`.
2632
2633 We should be able to drop this function and the associated logic calling it once we drop support
2634 for v1-style validator decorators. (Or we can extend it and keep it if we add something equivalent
2635 to the v1-validator `always` kwarg to `field_validator`.)
2636 """
2637 for validator in validators:
2638 if validator.info.always:
2639 return True
2640 return False
2641
2642
2643def _convert_to_aliases(
2644 alias: str | AliasChoices | AliasPath | None,
2645) -> str | list[str | int] | list[list[str | int]] | None:
2646 if isinstance(alias, (AliasChoices, AliasPath)):
2647 return alias.convert_to_aliases()
2648 else:
2649 return alias
2650
2651
2652def apply_model_validators(
2653 schema: core_schema.CoreSchema,
2654 validators: Iterable[Decorator[ModelValidatorDecoratorInfo]],
2655 mode: Literal['inner', 'outer', 'all'],
2656) -> core_schema.CoreSchema:
2657 """Apply model validators to a schema.
2658
2659 If mode == 'inner', only "before" validators are applied
2660 If mode == 'outer', validators other than "before" are applied
2661 If mode == 'all', all validators are applied
2662
2663 Args:
2664 schema: The schema to apply validators on.
2665 validators: An iterable of validators.
2666 mode: The validator mode.
2667
2668 Returns:
2669 The updated schema.
2670 """
2671 ref: str | None = schema.pop('ref', None) # type: ignore
2672 for validator in validators:
2673 if mode == 'inner' and validator.info.mode != 'before':
2674 continue
2675 if mode == 'outer' and validator.info.mode == 'before':
2676 continue
2677 info_arg = inspect_validator(validator.func, mode=validator.info.mode, type='model')
2678 if validator.info.mode == 'wrap':
2679 if info_arg:
2680 schema = core_schema.with_info_wrap_validator_function(function=validator.func, schema=schema)
2681 else:
2682 schema = core_schema.no_info_wrap_validator_function(function=validator.func, schema=schema)
2683 elif validator.info.mode == 'before':
2684 if info_arg:
2685 schema = core_schema.with_info_before_validator_function(function=validator.func, schema=schema)
2686 else:
2687 schema = core_schema.no_info_before_validator_function(function=validator.func, schema=schema)
2688 else:
2689 assert validator.info.mode == 'after'
2690 if info_arg:
2691 schema = core_schema.with_info_after_validator_function(function=validator.func, schema=schema)
2692 else:
2693 schema = core_schema.no_info_after_validator_function(function=validator.func, schema=schema)
2694 if ref:
2695 schema['ref'] = ref # type: ignore
2696 return schema
2697
2698
2699def wrap_default(field_info: FieldInfo, schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
2700 """Wrap schema with default schema if default value or `default_factory` are available.
2701
2702 Args:
2703 field_info: The field info object.
2704 schema: The schema to apply default on.
2705
2706 Returns:
2707 Updated schema by default value or `default_factory`.
2708 """
2709 if field_info.default_factory:
2710 return core_schema.with_default_schema(
2711 schema,
2712 default_factory=field_info.default_factory,
2713 default_factory_takes_data=takes_validated_data_argument(field_info.default_factory),
2714 validate_default=field_info.validate_default,
2715 )
2716 elif field_info.default is not PydanticUndefined:
2717 return core_schema.with_default_schema(
2718 schema, default=field_info.default, validate_default=field_info.validate_default
2719 )
2720 else:
2721 return schema
2722
2723
2724def _extract_get_pydantic_json_schema(tp: Any) -> GetJsonSchemaFunction | None:
2725 """Extract `__get_pydantic_json_schema__` from a type, handling the deprecated `__modify_schema__`."""
2726 js_modify_function = getattr(tp, '__get_pydantic_json_schema__', None)
2727
2728 if hasattr(tp, '__modify_schema__'):
2729 BaseModel = import_cached_base_model()
2730
2731 has_custom_v2_modify_js_func = (
2732 js_modify_function is not None
2733 and BaseModel.__get_pydantic_json_schema__.__func__ # type: ignore
2734 not in (js_modify_function, getattr(js_modify_function, '__func__', None))
2735 )
2736
2737 if not has_custom_v2_modify_js_func:
2738 cls_name = getattr(tp, '__name__', None)
2739 raise PydanticUserError(
2740 f'The `__modify_schema__` method is not supported in Pydantic v2. '
2741 f'Use `__get_pydantic_json_schema__` instead{f" in class `{cls_name}`" if cls_name else ""}.',
2742 code='custom-json-schema',
2743 )
2744
2745 if js_modify_function is None:
2746 return None
2747
2748 return js_modify_function
2749
2750
2751def resolve_original_schema(schema: CoreSchema, definitions: _Definitions) -> CoreSchema | None:
2752 if schema['type'] == 'definition-ref':
2753 return definitions.get_schema_from_ref(schema['schema_ref'])
2754 elif schema['type'] == 'definitions':
2755 return schema['schema']
2756 else:
2757 return schema
2758
2759
2760def _inlining_behavior(
2761 def_ref: core_schema.DefinitionReferenceSchema,
2762) -> Literal['inline', 'keep', 'preserve_metadata']:
2763 """Determine the inlining behavior of the `'definition-ref'` schema.
2764
2765 - If no `'serialization'` schema and no metadata is attached, the schema can safely be inlined.
2766 - If it has metadata but only related to the deferred discriminator application, it can be inlined
2767 provided that such metadata is kept.
2768 - Otherwise, the schema should not be inlined. Doing so would remove the `'serialization'` schema or metadata.
2769 """
2770 if 'serialization' in def_ref:
2771 return 'keep'
2772 metadata = def_ref.get('metadata')
2773 if not metadata:
2774 return 'inline'
2775 if len(metadata) == 1 and 'pydantic_internal_union_discriminator' in metadata:
2776 return 'preserve_metadata'
2777 return 'keep'
2778
2779
2780class _Definitions:
2781 """Keeps track of references and definitions."""
2782
2783 _recursively_seen: set[str]
2784 """A set of recursively seen references.
2785
2786 When a referenceable type is encountered, the `get_schema_or_ref` context manager is
2787 entered to compute the reference. If the type references itself by some way (e.g. for
2788 a dataclass a Pydantic model, the class can be referenced as a field annotation),
2789 entering the context manager again will yield a `'definition-ref'` schema that should
2790 short-circuit the normal generation process, as the reference was already in this set.
2791 """
2792
2793 _definitions: dict[str, core_schema.CoreSchema]
2794 """A mapping of references to their corresponding schema.
2795
2796 When a schema for a referenceable type is generated, it is stored in this mapping. If the
2797 same type is encountered again, the reference is yielded by the `get_schema_or_ref` context
2798 manager.
2799 """
2800
2801 def __init__(self) -> None:
2802 self._recursively_seen = set()
2803 self._definitions = {}
2804
2805 @contextmanager
2806 def get_definition_ref_schema(self, *, ref: str) -> Generator[core_schema.DefinitionReferenceSchema | None]:
2807 """Get a `'definition-ref'` schema for `ref`, if the reference was already encountered (or if we are in a cycle).
2808 Get a definition for `tp` if one exists.
2809
2810 This should be called for any type that can be identified by reference.
2811 This includes any recursive types.
2812
2813 At present the following types can be named/recursive:
2814
2815 - Pydantic model
2816 - Pydantic and stdlib dataclasses
2817 - Typed dictionaries
2818 - Named tuples
2819 - `TypeAliasType` instances
2820 - Enums
2821 """
2822 # return the reference if we're either (1) in a cycle or (2) it the reference was already encountered:
2823 if ref in self._recursively_seen or ref in self._definitions:
2824 yield core_schema.definition_reference_schema(ref)
2825 else:
2826 self._recursively_seen.add(ref)
2827 try:
2828 yield None
2829 finally:
2830 self._recursively_seen.discard(ref)
2831
2832 def get_schema_from_ref(self, ref: str) -> CoreSchema | None:
2833 """Resolve the schema from the given reference."""
2834 return self._definitions.get(ref)
2835
2836 def create_definition_reference_schema(self, schema: CoreSchema) -> core_schema.DefinitionReferenceSchema:
2837 """Store the schema as a definition and return a `'definition-reference'` schema pointing to it.
2838
2839 The schema must have a reference attached to it.
2840 """
2841 ref = schema['ref'] # pyright: ignore
2842 self._definitions[ref] = schema
2843 return core_schema.definition_reference_schema(ref)
2844
2845 def unpack_definitions(self, schema: core_schema.DefinitionsSchema) -> CoreSchema:
2846 """Store the definitions of the `'definitions'` core schema and return the inner core schema."""
2847 for def_schema in schema['definitions']:
2848 self._definitions[def_schema['ref']] = def_schema # pyright: ignore
2849 return schema['schema']
2850
2851 def finalize_schema(self, schema: CoreSchema) -> CoreSchema:
2852 """Finalize the core schema.
2853
2854 This traverses the core schema and referenced definitions, replaces `'definition-ref'` schemas
2855 by the referenced definition if possible, and applies deferred discriminators.
2856 """
2857 definitions = self._definitions
2858 try:
2859 gather_result = gather_schemas_for_cleaning(
2860 schema,
2861 definitions=definitions,
2862 )
2863 except MissingDefinitionError as e:
2864 raise InvalidSchemaError from e
2865
2866 remaining_defs: dict[str, CoreSchema] = {}
2867
2868 # References that will be kept as actual definitions (i.e. not inlined). When resolving an
2869 # "intermediate" `'definition-ref'` schema (see `_resolve_definition()`), we must not follow
2870 # the reference chain through one of these definitions:
2871 kept_refs = {
2872 ref
2873 for ref, inlinable_def_ref in gather_result['collected_references'].items()
2874 if inlinable_def_ref is None or _inlining_behavior(inlinable_def_ref) == 'keep'
2875 }
2876
2877 # Note: this logic doesn't play well when core schemas with deferred discriminator metadata
2878 # and references are encountered. See the `test_deferred_discriminated_union_and_references()` test.
2879 for ref, inlinable_def_ref in gather_result['collected_references'].items():
2880 if inlinable_def_ref is not None and (inlining_behavior := _inlining_behavior(inlinable_def_ref)) != 'keep':
2881 if inlining_behavior == 'inline':
2882 # `ref` was encountered, and only once:
2883 # - `inlinable_def_ref` is a `'definition-ref'` schema and is guaranteed to be
2884 # the only one. Transform it into the definition it points to.
2885 # - Do not store the definition in the `remaining_defs`.
2886 inlinable_def_ref.clear() # pyright: ignore[reportAttributeAccessIssue]
2887 inlinable_def_ref.update(self._resolve_definition(ref, definitions, kept_refs)) # pyright: ignore
2888 elif inlining_behavior == 'preserve_metadata':
2889 # `ref` was encountered, and only once, but contains discriminator metadata.
2890 # We will do the same thing as if `inlining_behavior` was `'inline'`, but make
2891 # sure to keep the metadata for the deferred discriminator application logic below.
2892 meta = inlinable_def_ref.pop('metadata')
2893 inlinable_def_ref.clear() # pyright: ignore[reportAttributeAccessIssue]
2894 inlinable_def_ref.update(self._resolve_definition(ref, definitions, kept_refs)) # pyright: ignore
2895 inlinable_def_ref['metadata'] = meta
2896 else:
2897 # `ref` was encountered, at least two times (or only once, but with metadata or a serialization schema):
2898 # - Do not inline the `'definition-ref'` schemas (they are not provided in the gather result anyway).
2899 # - Store the definition in the `remaining_defs`
2900 remaining_defs[ref] = self._resolve_definition(ref, definitions, kept_refs)
2901
2902 for cs in gather_result['deferred_discriminator_schemas']:
2903 discriminator: str | None = cs['metadata'].pop('pydantic_internal_union_discriminator', None) # pyright: ignore[reportTypedDictNotRequiredAccess]
2904 if discriminator is None:
2905 # This can happen in rare scenarios, when a deferred schema is present multiple times in the
2906 # gather result (e.g. when using the `Sequence` type -- see `test_sequence_discriminated_union()`).
2907 # In this case, a previous loop iteration applied the discriminator and so we can just skip it here.
2908 continue
2909 applied = _discriminated_union.apply_discriminator(cs.copy(), discriminator, remaining_defs)
2910 # Mutate the schema directly to have the discriminator applied
2911 cs.clear() # pyright: ignore[reportAttributeAccessIssue]
2912 cs.update(applied) # pyright: ignore
2913
2914 if remaining_defs:
2915 schema = core_schema.definitions_schema(schema=schema, definitions=[*remaining_defs.values()])
2916 return schema
2917
2918 def _resolve_definition(self, ref: str, definitions: dict[str, CoreSchema], kept_refs: set[str]) -> CoreSchema:
2919 definition = definitions[ref]
2920 if definition['type'] != 'definition-ref':
2921 return definition
2922
2923 # Some `'definition-ref'` schemas might act as "intermediate" references (e.g. when using
2924 # a PEP 695 type alias (which is referenceable) that references another PEP 695 type alias):
2925 visited: set[str] = set()
2926 while definition['type'] == 'definition-ref' and _inlining_behavior(definition) == 'inline':
2927 schema_ref = definition['schema_ref']
2928 if schema_ref in kept_refs and schema_ref != ref:
2929 # The reference chain leads to a *different* definition that is kept on its own (e.g. a
2930 # recursive model referenced through a PEP 695 type alias). Resolve to a reference
2931 # pointing to it instead of following the chain and inlining a copy of that definition,
2932 # which could otherwise introduce a reference cycle in the resulting schema.
2933 # Note: when `schema_ref == ref`, the reference points back to itself, which is a genuine
2934 # circular reference and is reported as an error by the `visited` logic below.
2935 return {**definition, 'ref': ref}
2936 if schema_ref in visited:
2937 raise PydanticUserError(
2938 f'{ref} contains a circular reference to itself.', code='circular-reference-schema'
2939 )
2940 visited.add(schema_ref)
2941 definition = definitions[schema_ref]
2942 return {**definition, 'ref': ref} # pyright: ignore[reportReturnType]
2943
2944
2945class _FieldNameStack:
2946 __slots__ = ('_stack',)
2947
2948 def __init__(self) -> None:
2949 self._stack: list[str] = []
2950
2951 @contextmanager
2952 def push(self, field_name: str) -> Iterator[None]:
2953 self._stack.append(field_name)
2954 try:
2955 yield
2956 finally:
2957 self._stack.pop()
2958
2959 def get(self) -> str | None:
2960 if self._stack:
2961 return self._stack[-1]
2962 else:
2963 return None
2964
2965
2966class _ModelTypeStack:
2967 __slots__ = ('_stack',)
2968
2969 def __init__(self) -> None:
2970 self._stack: list[type] = []
2971
2972 @contextmanager
2973 def push(self, type_obj: type) -> Iterator[None]:
2974 self._stack.append(type_obj)
2975 try:
2976 yield
2977 finally:
2978 self._stack.pop()
2979
2980 def get(self) -> type | None:
2981 if self._stack:
2982 return self._stack[-1]
2983 else:
2984 return None