Coverage for pydantic / _internal / _generate_schema.py: 94.81%

1250 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""Convert python types to pydantic-core schema.""" 

2 

3from __future__ import annotations as _annotations 1jmpgabknqhcdslorief

4 

5import collections.abc 1jmpgabknqhcdslorief

6import dataclasses 1jmpgabknqhcdslorief

7import datetime 1jmpgabknqhcdslorief

8import inspect 1jmpgabknqhcdslorief

9import os 1jmpgabknqhcdslorief

10import pathlib 1jmpgabknqhcdslorief

11import re 1jmpgabknqhcdslorief

12import sys 1jmpgabknqhcdslorief

13import typing 1jmpgabknqhcdslorief

14import warnings 1jmpgabknqhcdslorief

15from collections.abc import Callable, Generator, Iterable, Iterator, Mapping 1jmpgabknqhcdslorief

16from copy import copy 1jmpgabknqhcdslorief

17from decimal import Decimal 1jmpgabknqhcdslorief

18from enum import Enum 1jmpgabknqhcdslorief

19from fractions import Fraction 1jmpgabknqhcdslorief

20from functools import partial 1jmpgabknqhcdslorief

21from inspect import Parameter, _ParameterKind 1jmpgabknqhcdslorief

22from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network 1jmpgabknqhcdslorief

23from itertools import chain 1jmpgabknqhcdslorief

24from operator import attrgetter 1jmpgabknqhcdslorief

25from types import EllipsisType, FunctionType, LambdaType, MethodType, NoneType 1jmpgabknqhcdslorief

26from typing import ( 1jmpgabknqhcdslorief

27 TYPE_CHECKING, 

28 Any, 

29 ClassVar, 

30 ForwardRef, 

31 Literal, 

32 TypeAlias, 

33 TypeVar, 

34 cast, 

35 overload, 

36) 

37from uuid import UUID 1jmpgabknqhcdslorief

38from zoneinfo import ZoneInfo 1jmpgabknqhcdslorief

39 

40import typing_extensions 1jmpgabknqhcdslorief

41from pydantic_core import ( 1jmpgabknqhcdslorief

42 MISSING, 

43 CoreSchema, 

44 MultiHostUrl, 

45 PydanticCustomError, 

46 PydanticSerializationUnexpectedValue, 

47 PydanticUndefined, 

48 Url, 

49 core_schema, 

50 to_jsonable_python, 

51) 

52from typing_extensions import ( # noqa: UP035 (for `get_args` and `get_origin`) 1jmpgabknqhcdslorief

53 TypeAliasType, 

54 get_args, 

55 get_origin, 

56 is_typeddict, 

57) 

58from typing_inspection import typing_objects 1jmpgabknqhcdslorief

59from typing_inspection.introspection import AnnotationSource, get_literal_values, is_union_origin 1jmpgabknqhcdslorief

60 

61from ..aliases import AliasChoices, AliasPath 1jmpgabknqhcdslorief

62from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler 1jmpgabknqhcdslorief

63from ..config import ConfigDict, JsonDict, JsonEncoder, JsonSchemaExtraCallable 1jmpgabknqhcdslorief

64from ..errors import ( 1jmpgabknqhcdslorief

65 PydanticForbiddenQualifier, 

66 PydanticInvalidForJsonSchema, 

67 PydanticSchemaGenerationError, 

68 PydanticUndefinedAnnotation, 

69 PydanticUserError, 

70) 

71from ..functional_validators import AfterValidator, BeforeValidator, FieldValidatorModes, PlainValidator, WrapValidator 1jmpgabknqhcdslorief

72from ..json_schema import JsonSchemaValue 1jmpgabknqhcdslorief

73from ..version import version_short 1jmpgabknqhcdslorief

74from ..warnings import ( 1jmpgabknqhcdslorief

75 ArbitraryTypeWarning, 

76 PydanticDeprecatedSince20, 

77 TypedDictExtraConfigWarning, 

78 UnsupportedFieldAttributeWarning, 

79) 

80from . import _decorators, _discriminated_union, _known_annotated_metadata, _repr, _type_refs, _typing_extra 1jmpgabknqhcdslorief

81from ._config import ConfigWrapper, ConfigWrapperStack 1jmpgabknqhcdslorief

82from ._contextlib import contextmanager 1jmpgabknqhcdslorief

83from ._core_metadata import CoreMetadata, update_core_metadata 1jmpgabknqhcdslorief

84from ._core_utils import get_ref 1jmpgabknqhcdslorief

85from ._decorators import ( 1jmpgabknqhcdslorief

86 Decorator, 

87 DecoratorInfos, 

88 FieldSerializerDecoratorInfo, 

89 FieldValidatorDecoratorInfo, 

90 ModelSerializerDecoratorInfo, 

91 ModelValidatorDecoratorInfo, 

92 get_attribute_from_bases, 

93 inspect_field_serializer, 

94 inspect_model_serializer, 

95 inspect_validator, 

96 mro, 

97) 

98from ._docs_extraction import extract_docstrings_from_cls 1jmpgabknqhcdslorief

99from ._fields import ( 1jmpgabknqhcdslorief

100 collect_dataclass_fields, 

101 rebuild_dataclass_fields, 

102 rebuild_model_fields, 

103 takes_validated_data_argument, 

104 update_field_from_config, 

105) 

106from ._forward_ref import PydanticRecursiveRef 1jmpgabknqhcdslorief

107from ._generics import get_model_typevars_map, get_standard_typevars_map, replace_types 1jmpgabknqhcdslorief

108from ._import_utils import import_cached_base_model, import_cached_field_info 1jmpgabknqhcdslorief

109from ._mock_val_ser import MockCoreSchema 1jmpgabknqhcdslorief

110from ._namespace_utils import NamespacesTuple, NsResolver 1jmpgabknqhcdslorief

111from ._schema_gather import MissingDefinitionError, gather_schemas_for_cleaning 1jmpgabknqhcdslorief

112from ._schema_generation_shared import CallbackGetCoreSchemaHandler 1jmpgabknqhcdslorief

113from ._utils import lenient_issubclass, smart_deepcopy 1jmpgabknqhcdslorief

114 

115if TYPE_CHECKING: 1jmpgabknqhcdslorief

116 from ..fields import ComputedFieldInfo, FieldInfo 

117 from ..main import BaseModel 

118 from ..types import Discriminator 

119 from ._dataclasses import StandardDataclass 

120 from ._schema_generation_shared import GetJsonSchemaFunction 

121 

122if sys.version_info >= (3, 15): 1jmpgabknqhcdslorief

123 from builtins import frozendict 1abcdef

124 

125_SUPPORTS_TYPEDDICT = sys.version_info >= (3, 12) 1jmpgabknqhcdslorief

126 

127FieldDecoratorInfo: TypeAlias = FieldValidatorDecoratorInfo | FieldSerializerDecoratorInfo 1jmpgabknqhcdslorief

128FieldDecoratorInfoType = TypeVar('FieldDecoratorInfoType', bound=FieldDecoratorInfo) 1jmpgabknqhcdslorief

129AnyFieldDecorator = Decorator[FieldValidatorDecoratorInfo] | Decorator[FieldSerializerDecoratorInfo] 1jmpgabknqhcdslorief

130 

131ModifyCoreSchemaWrapHandler: TypeAlias = GetCoreSchemaHandler 1jmpgabknqhcdslorief

132GetCoreSchemaFunction: TypeAlias = Callable[[Any, ModifyCoreSchemaWrapHandler], core_schema.CoreSchema] 1jmpgabknqhcdslorief

133ParametersCallback: TypeAlias = Callable[[int, str, Any], Literal['skip'] | None] 1jmpgabknqhcdslorief

134 

135TUPLE_TYPES: list[type] = [typing.Tuple, tuple] # noqa: UP006 1jmpgabknqhcdslorief

136_NONE_SCHEMA = core_schema.none_schema() 1jmpgabknqhcdslorief

137_CALLABLE_SCHEMA = core_schema.callable_schema() 1jmpgabknqhcdslorief

138 

139 

140_SIMPLE_SCHEMA_TYPES: frozenset[type[Any]] = frozenset( 1jmpgabknqhcdslorief

141 { 

142 str, 

143 int, 

144 bool, 

145 float, 

146 bytes, 

147 complex, 

148 NoneType, 

149 object, 

150 type, 

151 EllipsisType, 

152 re.Pattern, 

153 datetime.datetime, 

154 datetime.date, 

155 datetime.time, 

156 datetime.timedelta, 

157 Decimal, 

158 ZoneInfo, 

159 } 

160) 

161"""Exact types handled directly, without checking for `__get_pydantic_core_schema__()`/`__get_pydantic_json_schema__()` methods.""" 1jmpgabknqhcdslorief

162 

163 

164def _is_simple_schema_type(obj: Any) -> bool: 1jmpgabknqhcdslorief

165 return obj is None or (type(obj) is type and obj in _SIMPLE_SCHEMA_TYPES) 1jmpgabknqhcdslorief

166 

167 

168def _copy_schema_handler(schema: CoreSchema) -> Callable[[GenerateSchema, Any], CoreSchema]: 1jmpgabknqhcdslorief

169 """Return fresh copies of a fixed schema made only of immutable values.""" 

170 

171 def handler(self: GenerateSchema, obj: Any) -> CoreSchema: 1jmpgabknqhcdslorief

172 return schema.copy() 1jmpgabknqhcdslorief

173 

174 return handler 1jmpgabknqhcdslorief

175 

176 

177# Note: This does not play very well with type checkers. For example, 

178# `a: LambdaType = lambda x: x` will raise a type error by Pyright. 

179ValidateCallSupportedTypes: TypeAlias = LambdaType | FunctionType | MethodType | partial 1jmpgabknqhcdslorief

180 

181 

182VALIDATE_CALL_SUPPORTED_TYPES = get_args(ValidateCallSupportedTypes) 1jmpgabknqhcdslorief

183UNSUPPORTED_STANDALONE_FIELDINFO_ATTRIBUTES: list[tuple[str, Any]] = [ 1jmpgabknqhcdslorief

184 ('alias', None), 

185 ('validation_alias', None), 

186 ('serialization_alias', None), 

187 # will be set if any alias is set, so disable it to avoid double warnings: 

188 # 'alias_priority', 

189 ('default', PydanticUndefined), 

190 ('default_factory', None), 

191 ('exclude', None), 

192 ('deprecated', None), 

193 ('repr', True), 

194 ('validate_default', None), 

195 ('frozen', None), 

196 ('init', None), 

197 ('init_var', None), 

198 ('kw_only', None), 

199] 

200"""`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).""" 1jmpgabknqhcdslorief

201 

202_mode_to_validator: dict[ 1jmpgabknqhcdslorief

203 FieldValidatorModes, type[BeforeValidator | AfterValidator | PlainValidator | WrapValidator] 

204] = {'before': BeforeValidator, 'after': AfterValidator, 'plain': PlainValidator, 'wrap': WrapValidator} 

205 

206 

207def check_validator_fields_against_field_name( 1jmpgabknqhcdslorief

208 info: FieldDecoratorInfo, 

209 field: str, 

210) -> bool: 

211 """Check if field name is in validator fields. 

212 

213 Args: 

214 info: The field info. 

215 field: The field name to check. 

216 

217 Returns: 

218 `True` if field name is in validator fields, `False` otherwise. 

219 """ 

220 fields = info.fields 1jmpgabknqhcdslorief

221 return '*' in fields or field in fields 1jmpgabknqhcdslorief

222 

223 

224def check_decorator_fields_exist(decorators: Iterable[AnyFieldDecorator], fields: Iterable[str]) -> None: 1jmpgabknqhcdslorief

225 """Check if the defined fields in decorators exist in `fields` param. 

226 

227 It ignores the check for a decorator if the decorator has `*` as field or `check_fields=False`. 

228 

229 Args: 

230 decorators: An iterable of decorators. 

231 fields: An iterable of fields name. 

232 

233 Raises: 

234 PydanticUserError: If one of the field names does not exist in `fields` param. 

235 """ 

236 fields = set(fields) 1jmpgabknqhcdslorief

237 for dec in decorators: 1jmpgabknqhcdslorief

238 if '*' in dec.info.fields: 1jmpgabknqhcdslorief

239 continue 1jmpgabknqhcdlorief

240 if dec.info.check_fields is False: 1jmpgabknqhcdslorief

241 continue 1jmpgabknqhcdlorief

242 for field in dec.info.fields: 1jmpgabknqhcdslorief

243 if field not in fields: 1jmpgabknqhcdslorief

244 raise PydanticUserError( 1jmpgabknqhcdlorief

245 f'Decorators defined with incorrect fields: {dec.cls_ref}.{dec.cls_var_name}' 

246 " (use check_fields=False if you're inheriting from the model and intended this)", 

247 code='decorator-missing-field', 

248 ) 

249 

250 

251def filter_field_decorator_info_by_field( 1jmpgabknqhcdslorief

252 validator_functions: Iterable[Decorator[FieldDecoratorInfoType]], field: str 

253) -> list[Decorator[FieldDecoratorInfoType]]: 

254 return [dec for dec in validator_functions if check_validator_fields_against_field_name(dec.info, field)] 1jmpgabknqhcdslorief

255 

256 

257def _extract_json_schema_info_from_field_info( 1jmpgabknqhcdslorief

258 info: FieldInfo | ComputedFieldInfo, 

259) -> tuple[JsonDict | None, JsonDict | JsonSchemaExtraCallable | None]: 

260 json_schema_updates = { 1jmpgabknqhcdslorief

261 'title': info.title, 

262 'description': info.description, 

263 'deprecated': bool(info.deprecated) or info.deprecated == '' or None, 

264 'examples': to_jsonable_python(info.examples), 

265 } 

266 json_schema_updates = {k: v for k, v in json_schema_updates.items() if v is not None} 1jmpgabknqhcdslorief

267 return (json_schema_updates or None, info.json_schema_extra) 1jmpgabknqhcdslorief

268 

269 

270JsonEncoders = dict[type[Any], JsonEncoder] 1jmpgabknqhcdslorief

271 

272 

273def _add_custom_serialization_from_json_encoders( 1jmpgabknqhcdslorief

274 json_encoders: JsonEncoders | None, tp: Any, schema: CoreSchema 

275) -> CoreSchema: 

276 """Iterate over the json_encoders and add the first matching encoder to the schema. 

277 

278 Args: 

279 json_encoders: A dictionary of types and their encoder functions. 

280 tp: The type to check for a matching encoder. 

281 schema: The schema to add the encoder to. 

282 """ 

283 if not json_encoders: 1jmpgabknqhcdslorief

284 return schema 1jmpgabknqhcdslorief

285 if 'serialization' in schema: 1jmpgabknqhcdlorief

286 return schema 1jmpgabknqhcdlorief

287 # Check the class type and its superclasses for a matching encoder 

288 # Decimal.__class__.__mro__ (and probably other cases) doesn't include Decimal itself 

289 # if the type is a GenericAlias (e.g. from list[int]) we need to use __class__ instead of .__mro__ 

290 for base in (tp, *getattr(tp, '__mro__', tp.__class__.__mro__)[:-1]): 1jmpgabknqhcdlorief

291 encoder = json_encoders.get(base) 1jmpgabknqhcdlorief

292 if encoder is None: 1jmpgabknqhcdlorief

293 continue 1jmpgabknqhcdlorief

294 

295 warnings.warn( 1jmpgabknqhcdlorief

296 f'`json_encoders` is deprecated. See https://pydantic.dev/docs/validation/{version_short()}/concepts/serialization/#custom-serializers for alternatives', 

297 PydanticDeprecatedSince20, 

298 ) 

299 

300 # TODO: in theory we should check that the schema accepts a serialization key 

301 schema['serialization'] = core_schema.plain_serializer_function_ser_schema(encoder, when_used='json') 1jmpgabknqhcdlorief

302 return schema 1jmpgabknqhcdlorief

303 

304 return schema 1jmpgabknqhcdlorief

305 

306 

307GENERATE_SCHEMA_ERRORS = ( 1jmpgabknqhcdslorief

308 PydanticForbiddenQualifier, 

309 PydanticInvalidForJsonSchema, 

310 PydanticSchemaGenerationError, 

311 PydanticUndefinedAnnotation, 

312) 

313"""Errors raised during core schema generation. This does *not* include `InvalidSchemaError`, which is raised during schema cleaning.""" 1jmpgabknqhcdslorief

314 

315 

316def _get_typed_dict_extra_items(typed_dict_cls: type[Any]) -> tuple[bool, Any, bool]: 1jmpgabknqhcdslorief

317 """Return whether the TypedDict class is closed, the type of its extra items and whether 

318 they are read-only (as per PEP 728). 

319 

320 The `__closed__` and `__extra_items__` attributes only reflect the arguments passed to the class itself, 

321 so the first class in the (virtual) MRO explicitly specifying one of them is used. 

322 `extra_items=Never` is normalized to `closed=True`, and the `ReadOnly` qualifier is stripped. 

323 """ 

324 for base in mro(typed_dict_cls): 1jmpgabknqhcdlorief

325 # `__closed__` is `None` when not specified: 

326 closed = base.__dict__.get('__closed__') 1jmpgabknqhcdlorief

327 extra_items = base.__dict__.get('__extra_items__', typing_extensions.NoExtraItems) 1jmpgabknqhcdlorief

328 if closed is not None or not typing_objects.is_noextraitems(extra_items): 1jmpgabknqhcdlorief

329 break 1jmpgabknqhcdlorief

330 else: 

331 return False, typing_extensions.NoExtraItems, False 1jmpgabknqhcdlorief

332 

333 if closed is not None: 1jmpgabknqhcdlorief

334 # `closed` and `extra_items` can't be used together: 

335 return closed, typing_extensions.NoExtraItems, False 1jmpgabknqhcdlorief

336 

337 readonly = typing_objects.is_readonly(get_origin(extra_items)) 1jmpgabknqhcdlorief

338 if readonly: 1jmpgabknqhcdlorief

339 extra_items = get_args(extra_items)[0] 1jmpgabknqhcdlorief

340 # TODO: `Never` wrapped in a type alias (e.g. `type NoExtras = Never`) or in `Annotated` isn't detected here, 

341 # and fails during schema generation. Unwrapping should only apply to this check (to preserve alias handling). 

342 if typing_objects.is_never(extra_items): 1jmpgabknqhcdlorief

343 return True, typing_extensions.NoExtraItems, False 1jmpgabknqhcdlorief

344 return False, extra_items, readonly 1jmpgabknqhcdlorief

345 

346 

347class InvalidSchemaError(Exception): 1jmpgabknqhcdslorief

348 """The core schema is invalid.""" 

349 

350 

351class GenerateSchema: 1jmpgabknqhcdslorief

352 """Generate core schema for a Pydantic model, dataclass and types like `str`, `datetime`, ... .""" 

353 

354 __slots__ = ( 1jmpgabknqhcdslorief

355 '_config_wrapper_stack', 

356 '_ns_resolver', 

357 '_typevars_map', 

358 'field_name_stack', 

359 'model_type_stack', 

360 'defs', 

361 ) 

362 

363 def __init__( 1jmpgabknqhcdslorief

364 self, 

365 config_wrapper: ConfigWrapper, 

366 ns_resolver: NsResolver | None = None, 

367 typevars_map: Mapping[TypeVar, Any] | None = None, 

368 ) -> None: 

369 # we need a stack for recursing into nested models 

370 self._config_wrapper_stack = ConfigWrapperStack(config_wrapper) 1jmpgabknqhcdslorief

371 self._ns_resolver = ns_resolver or NsResolver() 1jmpgabknqhcdslorief

372 self._typevars_map = typevars_map 1jmpgabknqhcdslorief

373 self.field_name_stack = _FieldNameStack() 1jmpgabknqhcdslorief

374 self.model_type_stack = _ModelTypeStack() 1jmpgabknqhcdslorief

375 self.defs = _Definitions() 1jmpgabknqhcdslorief

376 

377 # The handler lambdas take the `GenerateSchema` instance as their first argument, so that 

378 # the dicts can be built once at class creation time and shared by all instances: 

379 _handlers: ClassVar[dict[Any, Callable[[GenerateSchema, Any], core_schema.CoreSchema]]] = { 1jmpgabknqhcdslorief

380 str: _copy_schema_handler(core_schema.str_schema()), 

381 bytes: _copy_schema_handler(core_schema.bytes_schema()), 

382 int: _copy_schema_handler(core_schema.int_schema()), 

383 float: _copy_schema_handler(core_schema.float_schema()), 

384 bool: _copy_schema_handler(core_schema.bool_schema()), 

385 complex: _copy_schema_handler(core_schema.complex_schema()), 

386 object: _copy_schema_handler(core_schema.any_schema()), 

387 datetime.date: _copy_schema_handler(core_schema.date_schema()), 

388 datetime.datetime: _copy_schema_handler(core_schema.datetime_schema()), 

389 datetime.time: _copy_schema_handler(core_schema.time_schema()), 

390 datetime.timedelta: _copy_schema_handler(core_schema.timedelta_schema()), 

391 Decimal: _copy_schema_handler(core_schema.decimal_schema()), 

392 UUID: _copy_schema_handler(core_schema.uuid_schema()), 

393 Url: _copy_schema_handler(core_schema.url_schema()), 

394 Fraction: _copy_schema_handler(core_schema.fraction_schema()), 

395 MultiHostUrl: _copy_schema_handler(core_schema.multi_host_url_schema()), 

396 None: _copy_schema_handler(_NONE_SCHEMA), 

397 NoneType: _copy_schema_handler(_NONE_SCHEMA), 

398 MISSING: _copy_schema_handler(core_schema.missing_sentinel_schema()), 

399 EllipsisType: _copy_schema_handler(core_schema.ellipsis_schema()), 

400 type: lambda self, obj: self._type_schema(), 

401 dict: lambda self, obj: self._dict_schema(Any, Any), 

402 tuple: lambda self, obj: self._tuple_schema(obj), 

403 list: lambda self, obj: self._list_schema(Any), 

404 set: lambda self, obj: self._set_schema(Any), 

405 collections.abc.MutableSet: lambda self, obj: self._set_schema(Any), 

406 frozenset: lambda self, obj: self._frozenset_schema(Any), 

407 collections.abc.Set: lambda self, obj: self._frozenset_schema(Any), 

408 collections.abc.MutableSequence: lambda self, obj: self._list_schema(Any), 

409 collections.abc.Sequence: lambda self, obj: self._sequence_schema(Any), 

410 collections.deque: lambda self, obj: self._deque_schema(Any), 

411 collections.abc.Iterable: lambda self, obj: self._iterable_schema(obj), 

412 collections.abc.Generator: lambda self, obj: self._iterable_schema(obj), 

413 collections.abc.Mapping: lambda self, obj: self._mapping_schema(obj, Any, Any), 

414 collections.abc.MutableMapping: lambda self, obj: self._mapping_schema(obj, Any, Any), 

415 collections.OrderedDict: lambda self, obj: self._ordered_dict_schema(Any, Any), 

416 collections.defaultdict: lambda self, obj: self._mapping_schema(obj, Any, Any), 

417 collections.Counter: lambda self, obj: self._counter_schema(Any), 

418 collections.abc.Callable: _copy_schema_handler(_CALLABLE_SCHEMA), 

419 collections.abc.Hashable: lambda self, obj: self._hashable_schema(), 

420 IPv4Address: lambda self, obj: self._ip_schema(obj), 

421 IPv4Interface: lambda self, obj: self._ip_schema(obj), 

422 IPv4Network: lambda self, obj: self._ip_schema(obj), 

423 IPv6Address: lambda self, obj: self._ip_schema(obj), 

424 IPv6Interface: lambda self, obj: self._ip_schema(obj), 

425 IPv6Network: lambda self, obj: self._ip_schema(obj), 

426 os.PathLike: lambda self, obj: self._path_schema(obj, Any), 

427 pathlib.Path: lambda self, obj: self._path_schema(obj, Any), 

428 pathlib.PurePath: lambda self, obj: self._path_schema(obj, Any), 

429 pathlib.PosixPath: lambda self, obj: self._path_schema(obj, Any), 

430 pathlib.WindowsPath: lambda self, obj: self._path_schema(obj, Any), 

431 pathlib.PurePosixPath: lambda self, obj: self._path_schema(obj, Any), 

432 pathlib.PureWindowsPath: lambda self, obj: self._path_schema(obj, Any), 

433 re.Pattern: lambda self, obj: self._pattern_schema(obj), 

434 ZoneInfo: lambda self, obj: self._zoneinfo_schema(), 

435 } 

436 

437 _generic_handlers: ClassVar[dict[Any, Callable[[GenerateSchema, Any], core_schema.CoreSchema]]] = { 1jmpgabknqhcdslorief

438 tuple: lambda self, obj: self._tuple_schema(obj), 

439 list: lambda self, obj: self._list_schema(self._get_first_arg_or_any(obj)), 

440 dict: lambda self, obj: self._dict_schema(*self._get_first_two_args_or_any(obj)), 

441 set: lambda self, obj: self._set_schema(self._get_first_arg_or_any(obj)), 

442 frozenset: lambda self, obj: self._frozenset_schema(self._get_first_arg_or_any(obj)), 

443 type: lambda self, obj: self._subclass_schema(obj), 

444 collections.abc.MutableSequence: lambda self, obj: self._list_schema(self._get_first_arg_or_any(obj)), 

445 collections.abc.MutableSet: lambda self, obj: self._set_schema(self._get_first_arg_or_any(obj)), 

446 collections.abc.Set: lambda self, obj: self._frozenset_schema(self._get_first_arg_or_any(obj)), 

447 collections.deque: lambda self, obj: self._deque_schema(self._get_first_arg_or_any(obj)), 

448 collections.abc.Mapping: lambda self, obj: self._mapping_schema( 

449 collections.abc.Mapping, *self._get_first_two_args_or_any(obj) 

450 ), 

451 collections.abc.MutableMapping: lambda self, obj: self._mapping_schema( 

452 collections.abc.MutableMapping, *self._get_first_two_args_or_any(obj) 

453 ), 

454 collections.OrderedDict: lambda self, obj: self._ordered_dict_schema(*self._get_first_two_args_or_any(obj)), 

455 collections.defaultdict: lambda self, obj: self._mapping_schema( 

456 collections.defaultdict, *self._get_first_two_args_or_any(obj) 

457 ), 

458 collections.Counter: lambda self, obj: self._counter_schema(self._get_first_arg_or_any(obj)), 

459 os.PathLike: lambda self, obj: self._path_schema(os.PathLike, self._get_first_arg_or_any(obj)), 

460 pathlib.Path: lambda self, obj: self._path_schema(pathlib.Path, self._get_first_arg_or_any(obj)), 

461 pathlib.PurePath: lambda self, obj: self._path_schema(pathlib.PurePath, self._get_first_arg_or_any(obj)), 

462 pathlib.PosixPath: lambda self, obj: self._path_schema(pathlib.PosixPath, self._get_first_arg_or_any(obj)), 

463 pathlib.WindowsPath: lambda self, obj: self._path_schema(pathlib.WindowsPath, self._get_first_arg_or_any(obj)), 

464 pathlib.PurePosixPath: lambda self, obj: self._path_schema( 

465 pathlib.PurePosixPath, self._get_first_arg_or_any(obj) 

466 ), 

467 pathlib.PureWindowsPath: lambda self, obj: self._path_schema( 

468 pathlib.PureWindowsPath, self._get_first_arg_or_any(obj) 

469 ), 

470 collections.abc.Sequence: lambda self, obj: self._sequence_schema(self._get_first_arg_or_any(obj)), 

471 collections.abc.Iterable: lambda self, obj: self._iterable_schema(obj), 

472 collections.abc.Generator: lambda self, obj: self._iterable_schema(obj), 

473 re.Pattern: lambda self, obj: self._pattern_schema(obj), 

474 collections.abc.Callable: _copy_schema_handler(_CALLABLE_SCHEMA), 

475 } 

476 

477 if sys.version_info >= (3, 15): 1jmpgabknqhcdslorief

478 _handlers[frozendict] = lambda self, obj: self._frozendict_schema(Any, Any) 1abcdef

479 _generic_handlers[frozendict] = lambda self, obj: self._frozendict_schema(*self._get_first_two_args_or_any(obj)) 1abcdef

480 

481 def __init_subclass__(cls) -> None: 1jmpgabknqhcdslorief

482 super().__init_subclass__() 1jmpgabknqhcdlorief

483 warnings.warn( 1jmpgabknqhcdlorief

484 'Subclassing `GenerateSchema` is not supported. The API is highly subject to change in minor versions.', 

485 UserWarning, 

486 stacklevel=2, 

487 ) 

488 

489 @property 1jmpgabknqhcdslorief

490 def _config_wrapper(self) -> ConfigWrapper: 1jmpgabknqhcdslorief

491 return self._config_wrapper_stack.tail 1jmpgabknqhcdslorief

492 

493 @property 1jmpgabknqhcdslorief

494 def _types_namespace(self) -> NamespacesTuple: 1jmpgabknqhcdslorief

495 return self._ns_resolver.types_namespace 1jmpgabknqhcdlorief

496 

497 @property 1jmpgabknqhcdslorief

498 def _arbitrary_types(self) -> bool: 1jmpgabknqhcdslorief

499 return self._config_wrapper.arbitrary_types_allowed 1jmpgabknqhcdlorief

500 

501 # the following methods can be overridden but should be considered 

502 # unstable / private APIs 

503 def _list_schema(self, items_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

504 return core_schema.list_schema(self.generate_schema(items_type)) 1jmpgabknqhcdslorief

505 

506 def _dict_schema(self, keys_type: Any, values_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

507 return core_schema.dict_schema(self.generate_schema(keys_type), self.generate_schema(values_type)) 1jmpgabknqhcdlorief

508 

509 def _frozendict_schema(self, keys_type: Any, values_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

510 return core_schema.frozendict_schema(self.generate_schema(keys_type), self.generate_schema(values_type)) 1abcdef

511 

512 def _ordered_dict_schema(self, keys_type: Any, values_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

513 return core_schema.ordered_dict_schema(self.generate_schema(keys_type), self.generate_schema(values_type)) 1jmpgabknqhcdlorief

514 

515 def _counter_schema(self, keys_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

516 return core_schema.counter_schema(self.generate_schema(keys_type), core_schema.int_schema()) 1jmpgabknqhcdlorief

517 

518 def _set_schema(self, items_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

519 return core_schema.set_schema(self.generate_schema(items_type)) 1jmpgabknqhcdlorief

520 

521 def _frozenset_schema(self, items_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

522 return core_schema.frozenset_schema(self.generate_schema(items_type)) 1jmpgabknqhcdlorief

523 

524 def _enum_schema(self, enum_type: type[Enum]) -> CoreSchema: 1jmpgabknqhcdslorief

525 cases: list[Any] = list(enum_type.__members__.values()) 1jmpgabknqhcdlorief

526 

527 enum_ref = _type_refs.enum_type_ref(enum_type) 1jmpgabknqhcdlorief

528 description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__) 1jmpgabknqhcdlorief

529 if ( 529 ↛ 532line 529 didn't jump to line 532 because the condition on line 529 was never true1gabhcdief

530 description == 'An enumeration.' 

531 ): # This is the default value provided by enum.EnumMeta.__new__; don't use it 

532 description = None 

533 js_updates = {'title': enum_type.__name__, 'description': description} 1jmpgabknqhcdlorief

534 js_updates = {k: v for k, v in js_updates.items() if v is not None} 1jmpgabknqhcdlorief

535 

536 sub_type: Literal['str', 'int', 'float'] | None = None 1jmpgabknqhcdlorief

537 if issubclass(enum_type, int): 1jmpgabknqhcdlorief

538 sub_type = 'int' 1jmpgabknqhcdlorief

539 value_ser_type: core_schema.SerSchema = core_schema.simple_ser_schema('int') 1jmpgabknqhcdlorief

540 elif issubclass(enum_type, str): 1jmpgabknqhcdlorief

541 # this handles `StrEnum`, and also `Foobar(str, Enum)` 

542 sub_type = 'str' 1jmpgabknqhcdlorief

543 value_ser_type = core_schema.simple_ser_schema('str') 1jmpgabknqhcdlorief

544 elif issubclass(enum_type, float): 1jmpgabknqhcdlorief

545 sub_type = 'float' 1jmpgabknqhcdlorief

546 value_ser_type = core_schema.simple_ser_schema('float') 1jmpgabknqhcdlorief

547 else: 

548 # TODO this is an ugly hack, how do we trigger an Any schema for serialization? 

549 value_ser_type = core_schema.plain_serializer_function_ser_schema(lambda x: x) 1jmpgabknqhcdlorief

550 

551 if cases: 1jmpgabknqhcdlorief

552 

553 def get_json_schema(schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue: 1jmpgabknqhcdlorief

554 json_schema = handler(schema) 1jmpgabknqhcdlorief

555 original_schema = handler.resolve_ref_schema(json_schema) 1jmpgabknqhcdlorief

556 original_schema.update(js_updates) 1jmpgabknqhcdlorief

557 return json_schema 1jmpgabknqhcdlorief

558 

559 enum_schema = core_schema.enum_schema( 1jmpgabknqhcdlorief

560 enum_type, 

561 cases, 

562 sub_type=sub_type, 

563 ref=enum_ref, 

564 metadata={'pydantic_js_functions': [get_json_schema]}, 

565 ) 

566 

567 if self._config_wrapper.use_enum_values: 1jmpgabknqhcdlorief

568 enum_schema = core_schema.no_info_after_validator_function( 1jmpgabknqhcdlorief

569 attrgetter('value'), enum_schema, serialization=value_ser_type 

570 ) 

571 

572 return enum_schema 1jmpgabknqhcdlorief

573 

574 else: 

575 

576 def get_json_schema_no_cases(_, handler: GetJsonSchemaHandler) -> JsonSchemaValue: 1jmpgabknqhcdlorief

577 json_schema = handler(core_schema.enum_schema(enum_type, cases, sub_type=sub_type, ref=enum_ref)) 1jmpgabknqhcdlorief

578 original_schema = handler.resolve_ref_schema(json_schema) 1jmpgabknqhcdlorief

579 original_schema.update(js_updates) 1jmpgabknqhcdlorief

580 return json_schema 1jmpgabknqhcdlorief

581 

582 # Use an isinstance check for enums with no cases. 

583 # The most important use case for this is creating TypeVar bounds for generics that should 

584 # be restricted to enums. This is more consistent than it might seem at first, since you can only 

585 # subclass enum.Enum (or subclasses of enum.Enum) if all parent classes have no cases. 

586 # We use the get_json_schema function when an Enum subclass has been declared with no cases 

587 # so that we can still generate a valid json schema. 

588 return core_schema.is_instance_schema( 1jmpgabknqhcdlorief

589 enum_type, 

590 metadata={'pydantic_js_functions': [get_json_schema_no_cases]}, 

591 ) 

592 

593 def _ip_schema(self, tp: Any) -> CoreSchema: 1jmpgabknqhcdslorief

594 from ._validators import IP_VALIDATOR_LOOKUP, IpType 1jmpgabknqhcdlorief

595 

596 ip_type_json_schema_format: dict[type[IpType], str] = { 1jmpgabknqhcdlorief

597 IPv4Address: 'ipv4', 

598 IPv4Network: 'ipv4network', 

599 IPv4Interface: 'ipv4interface', 

600 IPv6Address: 'ipv6', 

601 IPv6Network: 'ipv6network', 

602 IPv6Interface: 'ipv6interface', 

603 } 

604 

605 def ser_ip(ip: Any, info: core_schema.SerializationInfo) -> str | IpType: 1jmpgabknqhcdlorief

606 if not isinstance(ip, (tp, str)): 1jmpgabknqhcdlorief

607 raise PydanticSerializationUnexpectedValue( 1jmpgabknqhcdlorief

608 f"Expected `{tp}` but got `{type(ip)}` with value `'{ip}'` - serialized value may not be as expected." 

609 ) 

610 if info.mode == 'python': 1jmpgabknqhcdlorief

611 return ip 1jmpgabknqhcdlorief

612 return str(ip) 1jmpgabknqhcdlorief

613 

614 return core_schema.lax_or_strict_schema( 1jmpgabknqhcdlorief

615 lax_schema=core_schema.no_info_plain_validator_function(IP_VALIDATOR_LOOKUP[tp]), 

616 strict_schema=core_schema.json_or_python_schema( 

617 json_schema=core_schema.no_info_after_validator_function(tp, core_schema.str_schema()), 

618 python_schema=core_schema.is_instance_schema(tp), 

619 ), 

620 serialization=core_schema.plain_serializer_function_ser_schema(ser_ip, info_arg=True, when_used='always'), 

621 metadata={ 

622 'pydantic_js_functions': [lambda _1, _2: {'type': 'string', 'format': ip_type_json_schema_format[tp]}] 

623 }, 

624 ) 

625 

626 def _path_schema(self, tp: Any, path_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

627 if tp is os.PathLike and (path_type not in {str, bytes} and not typing_objects.is_any(path_type)): 627 ↛ 628line 627 didn't jump to line 628 because the condition on line 627 was never true1jmpgabknqhcdlorief

628 raise PydanticUserError( 

629 '`os.PathLike` can only be used with `str`, `bytes` or `Any`', code='schema-for-unknown-type' 

630 ) 

631 

632 path_constructor = pathlib.PurePath if tp is os.PathLike else tp 1jmpgabknqhcdlorief

633 strict_inner_schema = ( 1jmpgabknqhcdlorief

634 core_schema.bytes_schema(strict=True) if (path_type is bytes) else core_schema.str_schema(strict=True) 

635 ) 

636 lax_inner_schema = core_schema.bytes_schema() if (path_type is bytes) else core_schema.str_schema() 1jmpgabknqhcdlorief

637 

638 def path_validator(input_value: str | bytes) -> os.PathLike[Any]: # type: ignore 1jmpgabknqhcdlorief

639 try: 1jmpgabknqhcdlorief

640 if path_type is bytes: 1jmpgabknqhcdlorief

641 if isinstance(input_value, bytes): 641 ↛ 647line 641 didn't jump to line 647 because the condition on line 641 was always true1jmpgabknqhcdlorief

642 try: 1jmpgabknqhcdlorief

643 input_value = input_value.decode() 1jmpgabknqhcdlorief

644 except UnicodeDecodeError as e: 

645 raise PydanticCustomError('bytes_type', 'Input must be valid bytes') from e 

646 else: 

647 raise PydanticCustomError('bytes_type', 'Input must be bytes') 

648 elif not isinstance(input_value, str): 648 ↛ 649line 648 didn't jump to line 649 because the condition on line 648 was never true1jmpgabknqhcdlorief

649 raise PydanticCustomError('path_type', 'Input is not a valid path') 

650 

651 return path_constructor(input_value) # type: ignore 1jmpgabknqhcdlorief

652 except TypeError as e: 

653 raise PydanticCustomError('path_type', 'Input is not a valid path') from e 

654 

655 def ser_path(path: Any, info: core_schema.SerializationInfo) -> str | os.PathLike[Any]: 1jmpgabknqhcdlorief

656 if not isinstance(path, (tp, str)): 1jmpgabknqhcdlorief

657 raise PydanticSerializationUnexpectedValue( 1jmpgabknqhcdlorief

658 f"Expected `{tp}` but got `{type(path)}` with value `'{path}'` - serialized value may not be as expected." 

659 ) 

660 if info.mode == 'python': 1jmpgabknqhcdlorief

661 return path 1jmpgabknqhcdlorief

662 return str(path) 1jmpgabknqhcdlorief

663 

664 instance_schema = core_schema.json_or_python_schema( 1jmpgabknqhcdlorief

665 json_schema=core_schema.no_info_after_validator_function(path_validator, lax_inner_schema), 

666 python_schema=core_schema.is_instance_schema(tp), 

667 ) 

668 

669 schema = core_schema.lax_or_strict_schema( 1jmpgabknqhcdlorief

670 lax_schema=core_schema.union_schema( 

671 [ 

672 instance_schema, 

673 core_schema.no_info_after_validator_function(path_validator, strict_inner_schema), 

674 ], 

675 custom_error_type='path_type', 

676 custom_error_message=f'Input is not a valid path for {tp}', 

677 ), 

678 strict_schema=instance_schema, 

679 serialization=core_schema.plain_serializer_function_ser_schema(ser_path, info_arg=True, when_used='always'), 

680 metadata={'pydantic_js_functions': [lambda source, handler: {**handler(source), 'format': 'path'}]}, 

681 ) 

682 return schema 1jmpgabknqhcdlorief

683 

684 def _deque_schema(self, items_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

685 return core_schema.deque_schema(self.generate_schema(items_type)) 1jmpgabknqhcdlorief

686 

687 def _mapping_schema(self, tp: Any, keys_type: Any, values_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

688 from ._validators import MAPPING_ORIGIN_MAP, defaultdict_validator, get_defaultdict_default_default_factory 1jmpgabknqhcdlorief

689 

690 mapped_origin = MAPPING_ORIGIN_MAP[tp] 1jmpgabknqhcdlorief

691 keys_schema = self.generate_schema(keys_type) 1jmpgabknqhcdlorief

692 with warnings.catch_warnings(): 1jmpgabknqhcdlorief

693 # We kind of abused `Field()` default factories to be able to specify 

694 # the `defaultdict`'s `default_factory`. As a consequence, we get warnings 

695 # as normally `FieldInfo.default_factory` is unsupported in the context where 

696 # `Field()` is used and our only solution is to ignore them (note that this might 

697 # wrongfully ignore valid warnings, e.g. if the `value_type` is a PEP 695 type alias 

698 # with unsupported metadata). 

699 warnings.simplefilter('ignore', category=UnsupportedFieldAttributeWarning) 1jmpgabknqhcdlorief

700 values_schema = self.generate_schema(values_type) 1jmpgabknqhcdlorief

701 dict_schema = core_schema.dict_schema(keys_schema, values_schema, strict=False) 1jmpgabknqhcdlorief

702 

703 if mapped_origin is dict: 1jmpgabknqhcdlorief

704 schema = dict_schema 1jmpgabknqhcdlorief

705 else: 

706 check_instance = core_schema.json_or_python_schema( 1jmpgabknqhcdlorief

707 json_schema=dict_schema, 

708 python_schema=core_schema.is_instance_schema(mapped_origin), 

709 ) 

710 

711 if tp is collections.defaultdict: 711 ↛ 718line 711 didn't jump to line 718 because the condition on line 711 was always true1jmpgabknqhcdlorief

712 default_default_factory = get_defaultdict_default_default_factory(values_type) 1jmpgabknqhcdlorief

713 coerce_instance_wrap = partial( 1jmpgabknqhcdlorief

714 core_schema.no_info_wrap_validator_function, 

715 partial(defaultdict_validator, default_default_factory=default_default_factory), 

716 ) 

717 else: 

718 coerce_instance_wrap = partial(core_schema.no_info_after_validator_function, mapped_origin) 

719 

720 lax_schema = coerce_instance_wrap(dict_schema) 1jmpgabknqhcdlorief

721 strict_schema = core_schema.chain_schema([check_instance, lax_schema]) 1jmpgabknqhcdlorief

722 

723 schema = core_schema.lax_or_strict_schema( 1jmpgabknqhcdlorief

724 lax_schema=lax_schema, 

725 strict_schema=strict_schema, 

726 serialization=core_schema.wrap_serializer_function_ser_schema( 

727 lambda v, h: h(v), schema=dict_schema, info_arg=False 

728 ), 

729 ) 

730 

731 return schema 1jmpgabknqhcdlorief

732 

733 def _arbitrary_type_schema(self, tp: Any) -> CoreSchema: 1jmpgabknqhcdslorief

734 if not isinstance(tp, type): 1jmpgabknqhcdlorief

735 warnings.warn( 1jmpgabknqhcdlorief

736 f'{tp!r} is not a Python type (it may be an instance of an object),' 

737 ' Pydantic will allow any object with no validation since we cannot even' 

738 ' enforce that the input is an instance of the given type.' 

739 ' To get rid of this error wrap the type with `pydantic.SkipValidation`.', 

740 ArbitraryTypeWarning, 

741 ) 

742 return core_schema.any_schema() 1jmpgabknqhcdlorief

743 return core_schema.is_instance_schema(tp) 1jmpgabknqhcdlorief

744 

745 def _unknown_type_schema(self, obj: Any) -> CoreSchema: 1jmpgabknqhcdslorief

746 raise PydanticSchemaGenerationError( 1jmpgabknqhcdlorief

747 f'Unable to generate pydantic-core schema for {obj!r}. ' 

748 'Set `arbitrary_types_allowed=True` in the model_config to ignore this error' 

749 ' or implement `__get_pydantic_core_schema__` on your type to fully support it.' 

750 '\n\nIf you got this error by calling handler(<some type>) within' 

751 ' `__get_pydantic_core_schema__` then you likely need to call' 

752 ' `handler.generate_schema(<some type>)` since we do not call' 

753 ' `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.' 

754 ) 

755 

756 def _apply_discriminator_to_union( 1jmpgabknqhcdslorief

757 self, schema: CoreSchema, discriminator: str | Discriminator | None 

758 ) -> CoreSchema: 

759 if discriminator is None: 759 ↛ 760line 759 didn't jump to line 760 because the condition on line 759 was never true1jmpgabknqhcdlorief

760 return schema 

761 try: 1jmpgabknqhcdlorief

762 return _discriminated_union.apply_discriminator( 1jmpgabknqhcdlorief

763 schema, 

764 discriminator, 

765 self.defs._definitions, 

766 ) 

767 except _discriminated_union.MissingDefinitionForUnionRef: 1jmpgabknqhcdlorief

768 # defer until defs are resolved 

769 _discriminated_union.set_discriminator_in_metadata( 1jmpgabknqhcdlorief

770 schema, 

771 discriminator, 

772 ) 

773 return schema 1jmpgabknqhcdlorief

774 

775 def clean_schema(self, schema: CoreSchema) -> CoreSchema: 1jmpgabknqhcdslorief

776 return self.defs.finalize_schema(schema) 1jmpgabknqhcdslorief

777 

778 def _add_js_function(self, metadata_schema: CoreSchema, js_function: Callable[..., Any]) -> None: 1jmpgabknqhcdslorief

779 metadata = metadata_schema.get('metadata', {}) 1jmpgabknqhcdslorief

780 pydantic_js_functions = metadata.setdefault('pydantic_js_functions', []) 1jmpgabknqhcdslorief

781 # because of how we generate core schemas for nested generic models 

782 # we can end up adding `BaseModel.__get_pydantic_json_schema__` multiple times 

783 # this check may fail to catch duplicates if the function is a `functools.partial` 

784 # or something like that, but if it does it'll fail by inserting the duplicate 

785 if js_function not in pydantic_js_functions: 1jmpgabknqhcdslorief

786 pydantic_js_functions.append(js_function) 1jmpgabknqhcdslorief

787 metadata_schema['metadata'] = metadata 1jmpgabknqhcdslorief

788 

789 def generate_schema( 1jmpgabknqhcdslorief

790 self, 

791 obj: Any, 

792 ) -> core_schema.CoreSchema: 

793 """Generate core schema. 

794 

795 Args: 

796 obj: The object to generate core schema for. 

797 

798 Returns: 

799 The generated core schema. 

800 

801 Raises: 

802 PydanticUndefinedAnnotation: 

803 If it is not possible to evaluate forward reference. 

804 PydanticSchemaGenerationError: 

805 If it is not possible to generate pydantic-core schema. 

806 TypeError: 

807 - If `alias_generator` returns a disallowed type (must be str, AliasPath or AliasChoices). 

808 PydanticUserError: 

809 - If `typing.TypedDict` is used instead of `typing_extensions.TypedDict` on Python < 3.12. 

810 """ 

811 if _is_simple_schema_type(obj): 1jmpgabknqhcdslorief

812 return _add_custom_serialization_from_json_encoders( 1jmpgabknqhcdslorief

813 self._config_wrapper.json_encoders, obj, self._handlers[obj](self, obj) 

814 ) 

815 

816 origin = get_origin(obj) 1jmpgabknqhcdslorief

817 schema: CoreSchema | None = None 1jmpgabknqhcdslorief

818 if origin is None: 1jmpgabknqhcdslorief

819 # If the type has an origin, it is guaranteed to *not* be an ordinary class that could have 

820 # a `__get_pydantic_core_schema__()` method: 

821 schema = self._generate_schema_from_get_schema_method(obj, obj) 1jmpgabknqhcdslorief

822 

823 if schema is None: 1jmpgabknqhcdslorief

824 schema = self._generate_schema_inner(obj, origin) 1jmpgabknqhcdslorief

825 

826 # `__get_pydantic_json_schema__()` is checked on the origin if it exists: 

827 metadata_js_function = _extract_get_pydantic_json_schema(origin if origin is not None else obj) 1jmpgabknqhcdslorief

828 if metadata_js_function is not None: 1jmpgabknqhcdslorief

829 metadata_schema = resolve_original_schema(schema, self.defs) 1jmpgabknqhcdslorief

830 if metadata_schema: 1jmpgabknqhcdslorief

831 self._add_js_function(metadata_schema, metadata_js_function) 1jmpgabknqhcdslorief

832 

833 schema = _add_custom_serialization_from_json_encoders(self._config_wrapper.json_encoders, obj, schema) 1jmpgabknqhcdslorief

834 

835 return schema 1jmpgabknqhcdslorief

836 

837 def _model_schema(self, cls: type[BaseModel]) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

838 """Generate schema for a Pydantic model.""" 

839 BaseModel_ = import_cached_base_model() 1jmpgabknqhcdslorief

840 

841 model_ref = _type_refs.model_type_ref(cls) 1jmpgabknqhcdslorief

842 with self.defs.get_definition_ref_schema(ref=model_ref) as maybe_schema: 1jmpgabknqhcdslorief

843 if maybe_schema is not None: 1jmpgabknqhcdslorief

844 return maybe_schema 1jmpgabknqhcdslorief

845 

846 schema = cls.__dict__.get('__pydantic_core_schema__') 1jmpgabknqhcdslorief

847 if schema is not None and not isinstance(schema, MockCoreSchema): 1jmpgabknqhcdslorief

848 if schema['type'] == 'definitions': 1jmpgabknqhcdslorief

849 schema = self.defs.unpack_definitions(schema) 1jmpgabknqhcdlorief

850 ref = get_ref(schema) 1jmpgabknqhcdslorief

851 if ref: 1jmpgabknqhcdslorief

852 return self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdslorief

853 else: 

854 return schema 1jmpgabknqhcdlorief

855 

856 config_wrapper = ConfigWrapper(cls.model_config, check=False) 1jmpgabknqhcdslorief

857 

858 with self._config_wrapper_stack.push(config_wrapper), self._ns_resolver.push(cls): 1jmpgabknqhcdslorief

859 core_config = self._config_wrapper.core_config(title=cls.__name__) 1jmpgabknqhcdslorief

860 

861 if cls.__pydantic_fields_complete__ or cls is BaseModel_: 1jmpgabknqhcdslorief

862 fields = getattr(cls, '__pydantic_fields__', {}) 1jmpgabknqhcdslorief

863 extra_info = getattr(cls, '__pydantic_extra_info__', None) 1jmpgabknqhcdslorief

864 else: 

865 if '__pydantic_fields__' not in cls.__dict__: 1jmpgabknqhcdlorief

866 # This happens when we have a loop in the schema generation: 

867 # class Base[T](BaseModel): 

868 # t: T 

869 # 

870 # class Other(BaseModel): 

871 # b: 'Base[Other]' 

872 # When we build fields for `Other`, we evaluate the forward annotation. 

873 # At this point, `Other` doesn't have the model fields set. We create 

874 # `Base[Other]`; model fields are successfully built, and we try to generate 

875 # a schema for `t: Other`. As `Other.__pydantic_fields__` aren't set, we abort. 

876 raise PydanticUndefinedAnnotation( 1jmpgabknqhcdlorief

877 name=cls.__name__, 

878 message=f'Class {cls.__name__!r} is not defined', 

879 ) 

880 try: 1jmpgabknqhcdlorief

881 fields, extra_info = rebuild_model_fields( 1jmpgabknqhcdlorief

882 cls, 

883 config_wrapper=self._config_wrapper, 

884 ns_resolver=self._ns_resolver, 

885 typevars_map=get_model_typevars_map(cls), 

886 ) 

887 except NameError as e: 1jmpgabknqhcdlorief

888 raise PydanticUndefinedAnnotation.from_name_error(e) from e 1jmpgabknqhcdlorief

889 

890 decorators = cls.__pydantic_decorators__ 1jmpgabknqhcdslorief

891 computed_fields = decorators.computed_fields 1jmpgabknqhcdslorief

892 if decorators.field_validators or decorators.field_serializers: 1jmpgabknqhcdslorief

893 check_decorator_fields_exist( 1jmpgabknqhcdslorief

894 chain( 

895 decorators.field_validators.values(), 

896 decorators.field_serializers.values(), 

897 ), 

898 {*fields.keys(), *computed_fields.keys()}, 

899 ) 

900 

901 model_validators = decorators.model_validators.values() 1jmpgabknqhcdslorief

902 

903 extras_schema = None 1jmpgabknqhcdslorief

904 extras_keys_schema = None 1jmpgabknqhcdslorief

905 if core_config.get('extra_fields_behavior') == 'allow' and extra_info is not None: 1jmpgabknqhcdslorief

906 tp = get_origin(extra_info.annotation) 1jmpgabknqhcdlorief

907 if tp is not dict: 1jmpgabknqhcdlorief

908 raise PydanticSchemaGenerationError( 1jmpgabknqhcdlorief

909 'The type annotation for `__pydantic_extra__` must be `dict[str, ...]`' 

910 ) 

911 # See the comments in `_get_args_resolving_forward_refs()` for why we need 

912 # to re-evaluate the annotation: 

913 extra_keys_type, extra_items_type = self._get_args_resolving_forward_refs( 1jmpgabknqhcdlorief

914 extra_info.annotation, 

915 required=True, 

916 ) 

917 if extra_keys_type is not str: 1jmpgabknqhcdlorief

918 extras_keys_schema = self.generate_schema(extra_keys_type) 1jmpgabknqhcdlorief

919 if not typing_objects.is_any(extra_items_type): 1jmpgabknqhcdlorief

920 extras_schema = self.generate_schema(extra_items_type) 1jmpgabknqhcdlorief

921 

922 generic_origin: type[BaseModel] | None = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin') 1jmpgabknqhcdslorief

923 

924 if cls.__pydantic_root_model__: 1jmpgabknqhcdslorief

925 inner_schema, metadata = self._common_field_schema('root', fields['root'], decorators) 1jmpgabknqhcdslorief

926 if cls.__doc__ and metadata.get('pydantic_js_updates', {}).get('description'): 1jmpgabknqhcdslorief

927 # This is a bit of a leaky abstraction, but as the model docstring takes priority 

928 # over the root field's description, we need to override it here. This can't be done 

929 # in the JSON Schema generation logic because the metadata's `pydantic_js_updates` are 

930 # applied last, and overrides any value previously set (so the description set from the 

931 # docstring in `GenerateJsonSchema._update_class_schema()` is overridden): 

932 update_core_metadata( 1jmpgabknqhcdlorief

933 metadata, pydantic_js_updates={'description': inspect.cleandoc(cls.__doc__)} 

934 ) 

935 

936 inner_schema = apply_model_validators(inner_schema, model_validators, 'inner') 1jmpgabknqhcdslorief

937 model_schema = core_schema.model_schema( 1jmpgabknqhcdslorief

938 cls, 

939 inner_schema, 

940 generic_origin=generic_origin, 

941 custom_init=getattr(cls, '__pydantic_custom_init__', None), 

942 root_model=True, 

943 post_init=getattr(cls, '__pydantic_post_init__', None), 

944 config=core_config, 

945 ref=model_ref, 

946 metadata=metadata, 

947 ) 

948 else: 

949 fields_schema: core_schema.CoreSchema = core_schema.model_fields_schema( 1jmpgabknqhcdslorief

950 {k: self._generate_md_field_schema(k, v, decorators) for k, v in fields.items()}, 

951 computed_fields=[ 

952 self._computed_field_schema(d, decorators.field_serializers) 

953 for d in computed_fields.values() 

954 ], 

955 extras_schema=extras_schema, 

956 extras_keys_schema=extras_keys_schema, 

957 model_name=cls.__name__, 

958 ) 

959 inner_schema = apply_model_validators(fields_schema, model_validators, 'inner') 1jmpgabknqhcdslorief

960 

961 model_schema = core_schema.model_schema( 1jmpgabknqhcdslorief

962 cls, 

963 inner_schema, 

964 generic_origin=generic_origin, 

965 custom_init=getattr(cls, '__pydantic_custom_init__', None), 

966 root_model=False, 

967 post_init=getattr(cls, '__pydantic_post_init__', None), 

968 config=core_config, 

969 ref=model_ref, 

970 ) 

971 

972 schema = self._apply_model_serializers(model_schema, decorators.model_serializers.values()) 1jmpgabknqhcdslorief

973 schema = apply_model_validators(schema, model_validators, 'outer') 1jmpgabknqhcdslorief

974 return self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdslorief

975 

976 def _resolve_self_type(self, obj: Any) -> Any: 1jmpgabknqhcdslorief

977 obj = self.model_type_stack.get() 1jmpgabknqhcdlorief

978 if obj is None: 1jmpgabknqhcdlorief

979 raise PydanticUserError('`typing.Self` is invalid in this context', code='invalid-self-type') 1jmpgabknqhcdlorief

980 return obj 1jmpgabknqhcdlorief

981 

982 def _generate_schema_from_get_schema_method(self, obj: Any, source: Any) -> core_schema.CoreSchema | None: 1jmpgabknqhcdslorief

983 BaseModel_ = import_cached_base_model() 1jmpgabknqhcdslorief

984 

985 get_schema = getattr(obj, '__get_pydantic_core_schema__', None) 1jmpgabknqhcdslorief

986 

987 if ( 1gabhcdief

988 get_schema is not None 

989 # BaseModel.__get_pydantic_core_schema__ is defined for backwards compatibility, 

990 # to allow existing code to call `super().__get_pydantic_core_schema__` in Pydantic 

991 # model that overrides `__get_pydantic_core_schema__`. However, it raises a deprecation 

992 # warning stating that the method will be removed, and during the core schema gen we actually 

993 # don't call the method: 

994 and getattr(get_schema, '__func__', None) is not BaseModel_.__get_pydantic_core_schema__.__func__ # pyright: ignore[reportFunctionMemberAccess] 

995 ): 

996 # Some referenceable types might have a `__get_pydantic_core_schema__` method 

997 # defined on it by users (e.g. on a dataclass). This generally doesn't play well 

998 # as these types are already recognized by the `GenerateSchema` class and isn't ideal 

999 # as we might end up calling `any_type_ref()` (relatively expensive) on types that are actually 

1000 # not referenceable: 

1001 with self.defs.get_definition_ref_schema(ref=_type_refs.any_type_ref(obj, get_origin(obj))) as maybe_schema: 1jmpgabknqhcdlorief

1002 if maybe_schema is not None: 1jmpgabknqhcdlorief

1003 return maybe_schema 1jmpgabknqhcdlorief

1004 

1005 if obj is source: 1jmpgabknqhcdlorief

1006 ref_mode = 'unpack' 1jmpgabknqhcdlorief

1007 else: 

1008 ref_mode = 'to-def' 1jmpgabknqhcdlorief

1009 schema = get_schema( 1jmpgabknqhcdlorief

1010 source, CallbackGetCoreSchemaHandler(self._generate_schema_inner, self, ref_mode=ref_mode) 

1011 ) 

1012 if schema['type'] == 'definitions': 1012 ↛ 1013line 1012 didn't jump to line 1013 because the condition on line 1012 was never true1jmpgabknqhcdlorief

1013 schema = self.defs.unpack_definitions(schema) 

1014 

1015 ref = get_ref(schema) 1jmpgabknqhcdlorief

1016 if ref: 1jmpgabknqhcdlorief

1017 return self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdlorief

1018 

1019 # Note: if schema is of type `'definition-ref'`, we might want to copy it as a 

1020 # safety measure (because these are inlined in place -- i.e. mutated directly) 

1021 return schema 1jmpgabknqhcdlorief

1022 

1023 def _resolve_forward_ref(self, obj: Any) -> Any: 1jmpgabknqhcdslorief

1024 # we assume that types_namespace has the target of forward references in its scope, 

1025 # but this could fail, for example, if calling Validator on an imported type which contains 

1026 # forward references to other types only defined in the module from which it was imported 

1027 # `Validator(SomeImportedTypeAliasWithAForwardReference)` 

1028 # or the equivalent for BaseModel 

1029 # class Model(BaseModel): 

1030 # x: SomeImportedTypeAliasWithAForwardReference 

1031 try: 1jmpgabknqhcdlorief

1032 obj = _typing_extra.eval_type(obj, *self._types_namespace) 1jmpgabknqhcdlorief

1033 except NameError as e: 1jmpgabknqhcdlorief

1034 raise PydanticUndefinedAnnotation.from_name_error(e) from e 1jmpgabknqhcdlorief

1035 

1036 # if obj is still a ForwardRef, it means we can't evaluate it, raise PydanticUndefinedAnnotation 

1037 if isinstance(obj, ForwardRef): 1jmpgabknqhcdlorief

1038 raise PydanticUndefinedAnnotation(obj.__forward_arg__, f'Unable to evaluate forward reference {obj}') 1jmpgabknqhcdlorief

1039 

1040 if self._typevars_map: 1040 ↛ 1041line 1040 didn't jump to line 1041 because the condition on line 1040 was never true1jmpgabknqhcdlorief

1041 obj = replace_types(obj, self._typevars_map) 

1042 

1043 return obj 1jmpgabknqhcdlorief

1044 

1045 @overload 1jmpgabknqhcdslorief

1046 def _get_args_resolving_forward_refs(self, obj: Any, required: Literal[True]) -> tuple[Any, ...]: ... 1jmpgabknqhcdslorief

1047 

1048 @overload 1jmpgabknqhcdslorief

1049 def _get_args_resolving_forward_refs(self, obj: Any) -> tuple[Any, ...] | None: ... 1jmpgabknqhcdslorief

1050 

1051 def _get_args_resolving_forward_refs(self, obj: Any, required: bool = False) -> tuple[Any, ...] | None: 1jmpgabknqhcdslorief

1052 # TODO this `_get_args_resolving_forward_refs()` function is probably not necessary? 

1053 args = get_args(obj) 1jmpgabknqhcdslorief

1054 if args: 1jmpgabknqhcdslorief

1055 args = tuple(self._resolve_forward_ref(a) if isinstance(a, ForwardRef) else a for a in args) 1jmpgabknqhcdslorief

1056 elif required: # pragma: no cover 1jmpgabknqhcdlorief

1057 raise TypeError(f'Expected {obj} to have generic parameters but it had none') 

1058 return args 1jmpgabknqhcdslorief

1059 

1060 def _get_first_arg_or_any(self, obj: Any) -> Any: 1jmpgabknqhcdslorief

1061 args = self._get_args_resolving_forward_refs(obj) 1jmpgabknqhcdslorief

1062 if not args: 1jmpgabknqhcdslorief

1063 return Any 1jmpgabknqhcdlorief

1064 return args[0] 1jmpgabknqhcdslorief

1065 

1066 def _get_first_two_args_or_any(self, obj: Any) -> tuple[Any, Any]: 1jmpgabknqhcdslorief

1067 args = self._get_args_resolving_forward_refs(obj) 1jmpgabknqhcdlorief

1068 if not args: 1068 ↛ 1069line 1068 didn't jump to line 1069 because the condition on line 1068 was never true1jmpgabknqhcdlorief

1069 return (Any, Any) 

1070 if len(args) < 2: 1070 ↛ 1071line 1070 didn't jump to line 1071 because the condition on line 1070 was never true1jmpgabknqhcdlorief

1071 origin = get_origin(obj) 

1072 raise TypeError(f'Expected two type arguments for {origin}, got 1') 

1073 return args[0], args[1] 1jmpgabknqhcdlorief

1074 

1075 def _generate_schema_inner(self, obj: Any, origin: Any | None = PydanticUndefined) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1076 if typing_objects.is_self(obj): 1jmpgabknqhcdslorief

1077 obj = self._resolve_self_type(obj) 1jmpgabknqhcdlorief

1078 # The resolved type can be a parametrized generic (e.g. `GenericDataclass[int]`), 

1079 # so the origin provided by the caller (computed on `Self`) is stale: 

1080 origin = get_origin(obj) 1jmpgabknqhcdlorief

1081 

1082 origin = origin if origin is not PydanticUndefined else get_origin(obj) 1jmpgabknqhcdslorief

1083 

1084 if is_union_origin(origin): 1jmpgabknqhcdslorief

1085 return self._direct_union_schema(obj) 1jmpgabknqhcdslorief

1086 

1087 if typing_objects.is_annotated(origin): 1jmpgabknqhcdslorief

1088 return self._annotated_schema(obj) 1jmpgabknqhcdlorief

1089 

1090 if typing_objects.is_literal(origin): 1jmpgabknqhcdslorief

1091 return self._literal_schema(obj) 1jmpgabknqhcdlorief

1092 

1093 if isinstance(obj, dict): 1093 ↛ 1095line 1093 didn't jump to line 1095 because the condition on line 1093 was never true1jmpgabknqhcdslorief

1094 # we assume this is already a valid schema 

1095 return obj # type: ignore[return-value] 

1096 

1097 if isinstance(obj, str): 1jmpgabknqhcdslorief

1098 obj = ForwardRef(obj) 1jmpgabknqhcdlorief

1099 

1100 if isinstance(obj, ForwardRef): 1jmpgabknqhcdslorief

1101 return self.generate_schema(self._resolve_forward_ref(obj)) 1jmpgabknqhcdlorief

1102 

1103 BaseModel = import_cached_base_model() 1jmpgabknqhcdslorief

1104 

1105 if lenient_issubclass(obj, BaseModel): 1jmpgabknqhcdslorief

1106 with self.model_type_stack.push(obj): 1jmpgabknqhcdslorief

1107 return self._model_schema(obj) 1jmpgabknqhcdslorief

1108 

1109 if isinstance(obj, PydanticRecursiveRef): 1jmpgabknqhcdslorief

1110 return core_schema.definition_reference_schema(schema_ref=obj.type_ref) 1jmpgabknqhcdlorief

1111 

1112 return self.match_type(obj, origin) 1jmpgabknqhcdslorief

1113 

1114 def match_type(self, obj: Any, origin: Any) -> core_schema.CoreSchema: # noqa: C901 1jmpgabknqhcdslorief

1115 """Main mapping of types to schemas. 

1116 

1117 The general structure is a series of if statements starting with the simple cases 

1118 (non-generic primitive types) and then handling generics and other more complex cases. 

1119 

1120 Each case either generates a schema directly, calls into a public user-overridable method 

1121 (like `GenerateSchema.tuple_variable_schema`) or calls into a private method that handles some 

1122 boilerplate before calling into the user-facing method (e.g. `GenerateSchema._tuple_schema`). 

1123 

1124 The idea is that we'll evolve this into adding more and more user facing methods over time 

1125 as they get requested and we figure out what the right API for them is. 

1126 """ 

1127 if typing_objects.is_any(obj) or typing_objects.is_final(obj): 1jmpgabknqhcdslorief

1128 # TODO: I'm not sure obj can be `Final` here, we call `typing_inspection.introspection.inspect_annotation()` 

1129 # early for model-like fields, which handles it already. 

1130 return core_schema.any_schema() 1jmpgabknqhcdlorief

1131 

1132 if origin is not None and (aliased_obj := typing_objects.DEPRECATED_ALIASES_IDS.get(id(obj))): 1jmpgabknqhcdslorief

1133 # See https://typing-inspection.pydantic.dev/dev/usage/#inspecting-the-type-expression: 

1134 obj = aliased_obj 1jmpgabknqhcdlorief

1135 origin = None 1jmpgabknqhcdlorief

1136 

1137 if origin is None: 1jmpgabknqhcdslorief

1138 # Thanks to the checks before this point, no origin means `obj` is a 

1139 # simple type (not a generic alias, a union, an `Annotated` form). 

1140 # examples: int, str, list, dict, collections.abc.Mapping, a `TypeAliasType` instance. 

1141 try: 1jmpgabknqhcdslorief

1142 handler = self._handlers.get(obj) 1jmpgabknqhcdslorief

1143 except TypeError: 

1144 pass 

1145 else: 

1146 if handler is not None: 1jmpgabknqhcdslorief

1147 return handler(self, obj) 1jmpgabknqhcdlorief

1148 

1149 if typing_objects.is_typealiastype(obj): 1jmpgabknqhcdslorief

1150 return self._type_alias_type_schema(obj) 1jmpgabknqhcdlorief

1151 elif is_typeddict(obj): 1jmpgabknqhcdslorief

1152 return self._typed_dict_schema(obj, None) 1jmpgabknqhcdlorief

1153 elif inspect.isclass(obj) and issubclass(obj, Enum): 1jmpgabknqhcdslorief

1154 # NOTE: this must come before the `is_namedtuple()` check as enums values 

1155 # can be namedtuples: 

1156 return self._enum_schema(obj) 1jmpgabknqhcdlorief

1157 elif _typing_extra.is_namedtuple(obj): 1jmpgabknqhcdslorief

1158 return self._namedtuple_schema(obj, None) 1jmpgabknqhcdlorief

1159 elif typing_objects.is_newtype(obj): 1jmpgabknqhcdslorief

1160 return self.generate_schema(obj.__supertype__) 1jmpgabknqhcdlorief

1161 elif isinstance(obj, typing.TypeVar): 1jmpgabknqhcdslorief

1162 return self._unsubstituted_typevar_schema(obj) 1jmpgabknqhcdslorief

1163 elif isinstance(obj, VALIDATE_CALL_SUPPORTED_TYPES): 1jmpgabknqhcdslorief

1164 return self._call_schema(obj) # pyright: ignore[reportArgumentType] 1jmpgabknqhcdlorief

1165 # dataclasses.is_dataclass coerces dc instances to types, but we only handle 

1166 # the case of a dc type here 

1167 elif dataclasses.is_dataclass(obj): 1jmpgabknqhcdslorief

1168 return self._dataclass_schema(obj, None) # pyright: ignore[reportArgumentType] 1jmpgabknqhcdslorief

1169 

1170 if origin is not None: 1jmpgabknqhcdslorief

1171 return self._match_generic_type(obj, origin) 1jmpgabknqhcdslorief

1172 

1173 if self._arbitrary_types: 1jmpgabknqhcdlorief

1174 return self._arbitrary_type_schema(obj) 1jmpgabknqhcdlorief

1175 return self._unknown_type_schema(obj) 1jmpgabknqhcdlorief

1176 

1177 def _match_generic_type(self, obj: Any, origin: Any) -> CoreSchema: # noqa: C901 1jmpgabknqhcdslorief

1178 # Need to handle generic dataclasses before looking for the schema properties because attribute accesses 

1179 # on _GenericAlias delegate to the origin type, so lose the information about the concrete parametrization 

1180 # As a result, currently, there is no way to cache the schema for generic dataclasses. This may be possible 

1181 # to resolve by modifying the value returned by `Generic.__class_getitem__`, but that is a dangerous game. 

1182 if dataclasses.is_dataclass(origin): 1jmpgabknqhcdslorief

1183 return self._dataclass_schema(obj, origin) # pyright: ignore[reportArgumentType] 1jmpgabknqhcdlorief

1184 elif _typing_extra.is_namedtuple(origin): 1jmpgabknqhcdslorief

1185 return self._namedtuple_schema(obj, origin) 1jmpgabknqhcdlorief

1186 elif typing_objects.is_final(origin): 1186 ↛ 1189line 1186 didn't jump to line 1189 because the condition on line 1186 was never true1jmpgabknqhcdslorief

1187 # TODO: I'm not sure obj can be `Final` here, we call `typing_inspection.introspection.inspect_annotation()` 

1188 # early for model-like fields, which handles it already. 

1189 return self.generate_schema(self._get_first_arg_or_any(obj)) 

1190 

1191 schema = self._generate_schema_from_get_schema_method(origin, obj) 1jmpgabknqhcdslorief

1192 if schema is not None: 1jmpgabknqhcdslorief

1193 return schema 1jmpgabknqhcdlorief

1194 

1195 try: 1jmpgabknqhcdslorief

1196 handler = self._generic_handlers.get(origin) 1jmpgabknqhcdslorief

1197 except TypeError: 

1198 pass 

1199 else: 

1200 if handler is not None: 1jmpgabknqhcdslorief

1201 return handler(self, obj) 1jmpgabknqhcdslorief

1202 

1203 if typing_objects.is_typealiastype(origin): 1jmpgabknqhcdlorief

1204 return self._type_alias_type_schema(obj) 1jmpgabknqhcdlorief

1205 elif is_typeddict(origin): 1jmpgabknqhcdlorief

1206 return self._typed_dict_schema(obj, origin) 1jmpgabknqhcdlorief

1207 

1208 if self._arbitrary_types: 1jmpgabknqhcdlorief

1209 return self._arbitrary_type_schema(origin) 1jmpgabknqhcdlorief

1210 return self._unknown_type_schema(obj) 1jmpgabknqhcdlorief

1211 

1212 def _generate_td_field_schema( 1jmpgabknqhcdslorief

1213 self, 

1214 name: str, 

1215 field_info: FieldInfo, 

1216 decorators: DecoratorInfos, 

1217 *, 

1218 required: bool = True, 

1219 ) -> core_schema.TypedDictField: 

1220 """Prepare a TypedDictField to represent a model or typeddict field.""" 

1221 schema, metadata = self._common_field_schema(name, field_info, decorators) 1jmpgabknqhcdlorief

1222 return core_schema.typed_dict_field( 1jmpgabknqhcdlorief

1223 schema, 

1224 required=False if not field_info.is_required() else required, 

1225 serialization_exclude=field_info.exclude, 

1226 validation_alias=_convert_to_aliases(field_info.validation_alias), 

1227 serialization_alias=field_info.serialization_alias, 

1228 serialization_exclude_if=field_info.exclude_if, 

1229 metadata=metadata, 

1230 ) 

1231 

1232 def _generate_md_field_schema( 1jmpgabknqhcdslorief

1233 self, 

1234 name: str, 

1235 field_info: FieldInfo, 

1236 decorators: DecoratorInfos, 

1237 ) -> core_schema.ModelField: 

1238 """Prepare a ModelField to represent a model field.""" 

1239 schema, metadata = self._common_field_schema(name, field_info, decorators) 1jmpgabknqhcdslorief

1240 return core_schema.model_field( 1jmpgabknqhcdslorief

1241 schema, 

1242 serialization_exclude=field_info.exclude, 

1243 validation_alias=_convert_to_aliases(field_info.validation_alias), 

1244 serialization_alias=field_info.serialization_alias, 

1245 serialization_exclude_if=field_info.exclude_if, 

1246 frozen=field_info.frozen, 

1247 metadata=metadata, 

1248 ) 

1249 

1250 def _generate_dc_field_schema( 1jmpgabknqhcdslorief

1251 self, 

1252 name: str, 

1253 field_info: FieldInfo, 

1254 decorators: DecoratorInfos, 

1255 ) -> core_schema.DataclassField: 

1256 """Prepare a DataclassField to represent the parameter/field, of a dataclass.""" 

1257 schema, metadata = self._common_field_schema(name, field_info, decorators) 1jmpgabknqhcdslorief

1258 return core_schema.dataclass_field( 1jmpgabknqhcdslorief

1259 name, 

1260 schema, 

1261 init=field_info.init, 

1262 init_only=field_info.init_var or None, 

1263 kw_only=None if field_info.kw_only else False, 

1264 serialization_exclude=field_info.exclude, 

1265 validation_alias=_convert_to_aliases(field_info.validation_alias), 

1266 serialization_alias=field_info.serialization_alias, 

1267 serialization_exclude_if=field_info.exclude_if, 

1268 frozen=field_info.frozen, 

1269 metadata=metadata, 

1270 ) 

1271 

1272 def _common_field_schema( # C901 1jmpgabknqhcdslorief

1273 self, name: str, field_info: FieldInfo, decorators: DecoratorInfos 

1274 ) -> tuple[CoreSchema, dict[str, Any]]: 

1275 source_type, annotations = field_info.annotation, field_info.metadata 1jmpgabknqhcdslorief

1276 

1277 def set_discriminator(schema: CoreSchema) -> CoreSchema: 1jmpgabknqhcdslorief

1278 schema = self._apply_discriminator_to_union(schema, field_info.discriminator) 1jmpgabknqhcdlorief

1279 return schema 1jmpgabknqhcdlorief

1280 

1281 # Convert `@field_validator` decorators to `Before/After/Plain/WrapValidator` instances: 

1282 if decorators.field_validators: 1jmpgabknqhcdslorief

1283 validators_from_decorators = [ 1jmpgabknqhcdslorief

1284 _mode_to_validator[decorator.info.mode]._from_decorator(decorator) 

1285 for decorator in filter_field_decorator_info_by_field(decorators.field_validators.values(), name) 

1286 ] 

1287 else: 

1288 validators_from_decorators = [] 1jmpgabknqhcdslorief

1289 

1290 with self.field_name_stack.push(name): 1jmpgabknqhcdslorief

1291 if field_info.discriminator is not None: 1jmpgabknqhcdslorief

1292 schema = self._apply_annotations( 1jmpgabknqhcdlorief

1293 source_type, annotations + validators_from_decorators, transform_inner_schema=set_discriminator 

1294 ) 

1295 else: 

1296 schema = self._apply_annotations( 1jmpgabknqhcdslorief

1297 source_type, 

1298 annotations + validators_from_decorators, 

1299 ) 

1300 

1301 # the default validator needs to go outside of any other validators 

1302 # so that it is the topmost validator for the field validator 

1303 # which uses it to check if the field has a default value or not 

1304 if not field_info.is_required(): 1jmpgabknqhcdslorief

1305 schema = wrap_default(field_info, schema) 1jmpgabknqhcdslorief

1306 

1307 if decorators.field_serializers: 1jmpgabknqhcdslorief

1308 schema = self._apply_field_serializers( 1jmpgabknqhcdlorief

1309 schema, filter_field_decorator_info_by_field(decorators.field_serializers.values(), name) 

1310 ) 

1311 

1312 pydantic_js_updates, pydantic_js_extra = _extract_json_schema_info_from_field_info(field_info) 1jmpgabknqhcdslorief

1313 core_metadata: dict[str, Any] = {} 1jmpgabknqhcdslorief

1314 update_core_metadata( 1jmpgabknqhcdslorief

1315 core_metadata, pydantic_js_updates=pydantic_js_updates, pydantic_js_extra=pydantic_js_extra 

1316 ) 

1317 

1318 return schema, core_metadata 1jmpgabknqhcdslorief

1319 

1320 def _direct_union_schema(self, obj: Any) -> CoreSchema: 1jmpgabknqhcdslorief

1321 """Generate the optimized union schema without enlarging general dispatch frames.""" 

1322 if not self._config_wrapper.json_encoders: 1jmpgabknqhcdslorief

1323 args = get_args(obj) 1jmpgabknqhcdslorief

1324 # These exact simple types cannot attach hooks or union tags. Field-level 

1325 # metadata and validators still process the fresh schema normally. 

1326 if all(map(_is_simple_schema_type, args)): 1jmpgabknqhcdslorief

1327 choices = [self._handlers[arg](self, arg) for arg in args if arg is not NoneType] 1jmpgabknqhcdslorief

1328 if len(choices) == 1: 1jmpgabknqhcdslorief

1329 schema = choices[0] 1jmpgabknqhcdslorief

1330 else: 

1331 schema = cast(core_schema.UnionSchema, {'type': 'union', 'choices': choices}) 1jmpgabknqhcdlorief

1332 if len(choices) < len(args): # one of the args is NoneType, so we need to make the schema nullable 1jmpgabknqhcdslorief

1333 return {'type': 'nullable', 'schema': schema} 1jmpgabknqhcdslorief

1334 else: 

1335 return schema 1jmpgabknqhcdlorief

1336 return self._union_schema(obj) 1jmpgabknqhcdslorief

1337 

1338 def _union_schema(self, union_type: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1339 """Generate schema for a Union.""" 

1340 args = self._get_args_resolving_forward_refs(union_type, required=True) 1jmpgabknqhcdslorief

1341 choices: list[CoreSchema] = [] 1jmpgabknqhcdslorief

1342 nullable = False 1jmpgabknqhcdslorief

1343 allow_missing = False 1jmpgabknqhcdslorief

1344 for arg in args: 1jmpgabknqhcdslorief

1345 if arg is NoneType: 1jmpgabknqhcdslorief

1346 nullable = True 1jmpgabknqhcdslorief

1347 elif arg is MISSING: 1jmpgabknqhcdslorief

1348 allow_missing = True 1jmpgabknqhcdlorief

1349 else: 

1350 choices.append(self.generate_schema(arg)) 1jmpgabknqhcdslorief

1351 

1352 if not choices: 1jmpgabknqhcdslorief

1353 # Only `None` and `MISSING` were present in the union (e.g. `None | MISSING`): 

1354 s = core_schema.none_schema() 1jmpgabknqhcdlorief

1355 nullable = False 1jmpgabknqhcdlorief

1356 elif len(choices) == 1: 1jmpgabknqhcdslorief

1357 s = choices[0] 1jmpgabknqhcdslorief

1358 else: 

1359 choices_with_tags: list[CoreSchema | tuple[CoreSchema, str]] = [] 1jmpgabknqhcdlorief

1360 for choice in choices: 1jmpgabknqhcdlorief

1361 tag = cast(CoreMetadata, choice.get('metadata', {})).get('pydantic_internal_union_tag_key') 1jmpgabknqhcdlorief

1362 if tag is not None: 1jmpgabknqhcdlorief

1363 choices_with_tags.append((choice, tag)) 1jmpgabknqhcdlorief

1364 else: 

1365 choices_with_tags.append(choice) 1jmpgabknqhcdlorief

1366 s = core_schema.union_schema(choices_with_tags) 1jmpgabknqhcdlorief

1367 

1368 if nullable: 1jmpgabknqhcdslorief

1369 s = core_schema.nullable_schema(s) 1jmpgabknqhcdslorief

1370 if allow_missing: 1jmpgabknqhcdslorief

1371 s = core_schema.missing_sentinel_schema(s) 1jmpgabknqhcdlorief

1372 return s 1jmpgabknqhcdslorief

1373 

1374 def _type_alias_type_schema(self, obj: TypeAliasType) -> CoreSchema: 1jmpgabknqhcdslorief

1375 ref = _type_refs.type_alias_type_ref(obj) 1jmpgabknqhcdlorief

1376 with self.defs.get_definition_ref_schema(ref=ref) as maybe_schema: 1jmpgabknqhcdlorief

1377 if maybe_schema is not None: 1jmpgabknqhcdlorief

1378 return maybe_schema 1jmpgabknqhcdlorief

1379 

1380 origin: TypeAliasType = get_origin(obj) or obj 1jmpgabknqhcdlorief

1381 typevars_map = get_standard_typevars_map(obj) 1jmpgabknqhcdlorief

1382 

1383 with self._ns_resolver.push(origin): 1jmpgabknqhcdlorief

1384 try: 1jmpgabknqhcdlorief

1385 annotation = _typing_extra.eval_type(origin.__value__, *self._types_namespace) 1jmpgabknqhcdlorief

1386 except NameError as e: 

1387 raise PydanticUndefinedAnnotation.from_name_error(e) from e 

1388 annotation = replace_types(annotation, typevars_map) 1jmpgabknqhcdlorief

1389 schema = self.generate_schema(annotation) 1jmpgabknqhcdlorief

1390 assert schema['type'] != 'definitions' 1jmpgabknqhcdlorief

1391 schema['ref'] = ref # type: ignore 1jmpgabknqhcdlorief

1392 return self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdlorief

1393 

1394 def _literal_schema(self, literal_type: Any) -> CoreSchema: 1jmpgabknqhcdslorief

1395 """Generate schema for a Literal.""" 

1396 expected = list(get_literal_values(literal_type, type_check=False, unpack_type_aliases='eager')) 1jmpgabknqhcdlorief

1397 assert expected, f'literal "expected" cannot be empty, obj={literal_type}' 1jmpgabknqhcdlorief

1398 schema = core_schema.literal_schema(expected) 1jmpgabknqhcdlorief

1399 

1400 if self._config_wrapper.use_enum_values and any(isinstance(v, Enum) for v in expected): 1jmpgabknqhcdlorief

1401 schema = core_schema.no_info_after_validator_function( 1jmpgabknqhcdlorief

1402 lambda v: v.value if isinstance(v, Enum) else v, schema 

1403 ) 

1404 

1405 return schema 1jmpgabknqhcdlorief

1406 

1407 def _typed_dict_schema(self, typed_dict_cls: Any, origin: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1408 """Generate a core schema for a `TypedDict` class. 

1409 

1410 To be able to build a `DecoratorInfos` instance for the `TypedDict` class (which will include 

1411 validators, serializers, etc.), we need to have access to the original bases of the class 

1412 (see https://docs.python.org/3/library/types.html#types.get_original_bases). 

1413 However, the `__orig_bases__` attribute was only added in 3.12 (https://github.com/python/cpython/pull/103698). 

1414 

1415 For this reason, we require Python 3.12 (or using the `typing_extensions` backport). 

1416 """ 

1417 FieldInfo = import_cached_field_info() 1jmpgabknqhcdlorief

1418 

1419 typed_dict_ref = _type_refs.class_type_ref(typed_dict_cls, origin) 1jmpgabknqhcdlorief

1420 with ( 1jgabkhcdlief

1421 self.model_type_stack.push(typed_dict_cls), 

1422 self.defs.get_definition_ref_schema(ref=typed_dict_ref) as maybe_schema, 

1423 ): 

1424 if maybe_schema is not None: 1jmpgabknqhcdlorief

1425 return maybe_schema 1jmpgabknqhcdlorief

1426 

1427 typevars_map = get_standard_typevars_map(typed_dict_cls) 1jmpgabknqhcdlorief

1428 if origin is not None: 1jmpgabknqhcdlorief

1429 typed_dict_cls = origin 1jmpgabknqhcdlorief

1430 

1431 if not _SUPPORTS_TYPEDDICT and type(typed_dict_cls).__module__ == 'typing': 1jmpgabknqhcdlorief

1432 raise PydanticUserError( 1jkl

1433 'Please use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12.', 

1434 code='typed-dict-version', 

1435 ) 

1436 

1437 try: 1jmpgabknqhcdlorief

1438 # if a typed dictionary class doesn't have config, we use the parent's config, hence a default of `None` 

1439 # see https://github.com/pydantic/pydantic/issues/10917 

1440 config: ConfigDict | None = get_attribute_from_bases(typed_dict_cls, '__pydantic_config__') 1jmpgabknqhcdlorief

1441 except AttributeError: 1jmpgabknqhcdlorief

1442 config = None 1jmpgabknqhcdlorief

1443 

1444 with self._config_wrapper_stack.push(config): 1jmpgabknqhcdlorief

1445 core_config = self._config_wrapper.core_config(title=typed_dict_cls.__name__) 1jmpgabknqhcdlorief

1446 

1447 required_keys: frozenset[str] = typed_dict_cls.__required_keys__ 1jmpgabknqhcdlorief

1448 

1449 fields: dict[str, core_schema.TypedDictField] = {} 1jmpgabknqhcdlorief

1450 

1451 decorators = DecoratorInfos.build(typed_dict_cls, replace_wrapped_methods=False) 1jmpgabknqhcdlorief

1452 decorators.update_from_config(self._config_wrapper) 1jmpgabknqhcdlorief

1453 

1454 if self._config_wrapper.use_attribute_docstrings: 1jmpgabknqhcdlorief

1455 field_docstrings = extract_docstrings_from_cls(typed_dict_cls, use_inspect=True) 1jmpgabknqhcdlorief

1456 else: 

1457 field_docstrings = None 1jmpgabknqhcdlorief

1458 

1459 try: 1jmpgabknqhcdlorief

1460 annotations = _typing_extra.get_cls_type_hints(typed_dict_cls, ns_resolver=self._ns_resolver) 1jmpgabknqhcdlorief

1461 except NameError as e: 

1462 raise PydanticUndefinedAnnotation.from_name_error(e) from e 

1463 

1464 readonly_fields: list[str] = [] 1jmpgabknqhcdlorief

1465 

1466 for field_name, annotation in annotations.items(): 1jmpgabknqhcdlorief

1467 field_info = FieldInfo.from_annotation(annotation, _source=AnnotationSource.TYPED_DICT) 1jmpgabknqhcdlorief

1468 field_info.annotation = replace_types(field_info.annotation, typevars_map) 1jmpgabknqhcdlorief

1469 

1470 required = ( 1jmpgabknqhcdlorief

1471 field_name in required_keys or 'required' in field_info._qualifiers 

1472 ) and 'not_required' not in field_info._qualifiers 

1473 if 'read_only' in field_info._qualifiers: 1jmpgabknqhcdlorief

1474 readonly_fields.append(field_name) 1jmpgabknqhcdlorief

1475 

1476 if ( 1gabhcdief

1477 field_docstrings is not None 

1478 and field_info.description is None 

1479 and field_name in field_docstrings 

1480 ): 

1481 field_info.description = field_docstrings[field_name] 1jmpgabknqhcdlorief

1482 update_field_from_config(self._config_wrapper, field_name, field_info) 1jmpgabknqhcdlorief

1483 

1484 fields[field_name] = self._generate_td_field_schema( 1jmpgabknqhcdlorief

1485 field_name, field_info, decorators, required=required 

1486 ) 

1487 

1488 if readonly_fields: 1jmpgabknqhcdlorief

1489 fields_repr = ', '.join(repr(f) for f in readonly_fields) 1jmpgabknqhcdlorief

1490 plural = len(readonly_fields) >= 2 1jmpgabknqhcdlorief

1491 warnings.warn( 1jmpgabknqhcdlorief

1492 f'Item{"s" if plural else ""} {fields_repr} on TypedDict class {typed_dict_cls.__name__!r} ' 

1493 f'{"are" if plural else "is"} using the `ReadOnly` qualifier. Pydantic will not protect items ' 

1494 'from any mutation on dictionary instances.', 

1495 UserWarning, 

1496 ) 

1497 

1498 extra_behavior: core_schema.ExtraBehavior = 'ignore' 1jmpgabknqhcdlorief

1499 extras_schema: CoreSchema | None = None # For 'allow', equivalent to `Any` - no validation performed. 1jmpgabknqhcdlorief

1500 

1501 is_closed, extra_items, extra_items_readonly = _get_typed_dict_extra_items(typed_dict_cls) 1jmpgabknqhcdlorief

1502 if is_closed: 1jmpgabknqhcdlorief

1503 extra_behavior = 'forbid' 1jmpgabknqhcdlorief

1504 extras_schema = None 1jmpgabknqhcdlorief

1505 elif not typing_objects.is_noextraitems(extra_items): 1jmpgabknqhcdlorief

1506 extra_behavior = 'allow' 1jmpgabknqhcdlorief

1507 extras_schema = self.generate_schema(replace_types(extra_items, typevars_map)) 1jmpgabknqhcdlorief

1508 

1509 if extra_items_readonly: 1jmpgabknqhcdlorief

1510 warnings.warn( 1jmpgabknqhcdlorief

1511 f'Extra items on TypedDict class {typed_dict_cls.__name__!r} are using the `ReadOnly` qualifier. ' 

1512 'Pydantic will not protect items from any mutation on dictionary instances.', 

1513 UserWarning, 

1514 ) 

1515 

1516 if (config_extra := self._config_wrapper.extra) in ('allow', 'forbid'): 1jmpgabknqhcdlorief

1517 if is_closed and config_extra == 'allow': 1jmpgabknqhcdlorief

1518 warnings.warn( 1jmpgabknqhcdlorief

1519 f"TypedDict class {typed_dict_cls.__qualname__!r} is closed, but 'extra' configuration " 

1520 "is set to `'allow'`. The 'extra' configuration value will be ignored.", 

1521 category=TypedDictExtraConfigWarning, 

1522 ) 

1523 elif not typing_objects.is_noextraitems(extra_items) and config_extra == 'forbid': 1jmpgabknqhcdlorief

1524 warnings.warn( 1jmpgabknqhcdlorief

1525 f"TypedDict class {typed_dict_cls.__qualname__!r} allows extra items, but 'extra' configuration " 

1526 "is set to `'forbid'`. The 'extra' configuration value will be ignored.", 

1527 category=TypedDictExtraConfigWarning, 

1528 ) 

1529 else: 

1530 extra_behavior = config_extra 1jmpgabknqhcdlorief

1531 

1532 td_schema = core_schema.typed_dict_schema( 1jmpgabknqhcdlorief

1533 fields, 

1534 cls=typed_dict_cls, 

1535 computed_fields=[ 

1536 self._computed_field_schema(d, decorators.field_serializers) 

1537 for d in decorators.computed_fields.values() 

1538 ], 

1539 extra_behavior=extra_behavior, 

1540 extras_schema=extras_schema, 

1541 ref=typed_dict_ref, 

1542 config=core_config, 

1543 ) 

1544 

1545 schema = self._apply_model_serializers(td_schema, decorators.model_serializers.values()) 1jmpgabknqhcdlorief

1546 schema = apply_model_validators(schema, decorators.model_validators.values(), 'all') 1jmpgabknqhcdlorief

1547 return self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdlorief

1548 

1549 def _namedtuple_schema(self, namedtuple_cls: Any, origin: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1550 """Generate schema for a NamedTuple.""" 

1551 namedtuple_ref = _type_refs.class_type_ref(namedtuple_cls, origin) 1jmpgabknqhcdlorief

1552 with ( 1jgabkhcdlief

1553 self.model_type_stack.push(namedtuple_cls), 

1554 self.defs.get_definition_ref_schema(ref=namedtuple_ref) as maybe_schema, 

1555 ): 

1556 if maybe_schema is not None: 1jmpgabknqhcdlorief

1557 return maybe_schema 1jmpgabknqhcdlorief

1558 typevars_map = get_standard_typevars_map(namedtuple_cls) 1jmpgabknqhcdlorief

1559 if origin is not None: 1jmpgabknqhcdlorief

1560 namedtuple_cls = origin 1jmpgabknqhcdlorief

1561 

1562 try: 1jmpgabknqhcdlorief

1563 annotations = _typing_extra.get_cls_type_hints(namedtuple_cls, ns_resolver=self._ns_resolver) 1jmpgabknqhcdlorief

1564 except NameError as e: 

1565 raise PydanticUndefinedAnnotation.from_name_error(e) from e 

1566 

1567 # Filter annotations to only include fields that are actually in the NamedTuple 

1568 # (as subclassing an existing NamedTuple is not supported yet - see https://github.com/python/typing/issues/427) 

1569 # and use `Any` if no annotation exist (i.e. when using `collections.namedtuple()`). 

1570 annotations = {field_name: annotations.get(field_name, Any) for field_name in namedtuple_cls._fields} 1jmpgabknqhcdlorief

1571 

1572 if typevars_map: 1jmpgabknqhcdlorief

1573 annotations = { 1jmpgabknqhcdlorief

1574 field_name: replace_types(annotation, typevars_map) 

1575 for field_name, annotation in annotations.items() 

1576 } 

1577 

1578 schema = core_schema.named_tuple_schema( 1jmpgabknqhcdlorief

1579 namedtuple_cls, 

1580 [ 

1581 self._generate_namedtuple_field_schema( 

1582 field_name, 

1583 annotation, 

1584 default=namedtuple_cls._field_defaults.get(field_name, Parameter.empty), 

1585 ) 

1586 for field_name, annotation in annotations.items() 

1587 ], 

1588 ref=namedtuple_ref, 

1589 ) 

1590 return self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdlorief

1591 

1592 def _generate_namedtuple_field_schema( 1jmpgabknqhcdslorief

1593 self, 

1594 name: str, 

1595 annotation: Any, 

1596 default: Any = Parameter.empty, 

1597 ) -> core_schema.NamedTupleField: 

1598 """Generate the definition of a field in a named tuple.""" 

1599 FieldInfo = import_cached_field_info() 1jmpgabknqhcdlorief

1600 

1601 if default is Parameter.empty: 1jmpgabknqhcdlorief

1602 field = FieldInfo.from_annotation(annotation, _source=AnnotationSource.NAMED_TUPLE) 1jmpgabknqhcdlorief

1603 else: 

1604 field = FieldInfo.from_annotated_attribute(annotation, default, _source=AnnotationSource.NAMED_TUPLE) 1jmpgabknqhcdlorief

1605 

1606 assert field.annotation is not None, 'field.annotation should not be None when generating a schema' 1jmpgabknqhcdlorief

1607 update_field_from_config(self._config_wrapper, name, field) 1jmpgabknqhcdlorief

1608 

1609 with self.field_name_stack.push(name): 1jmpgabknqhcdlorief

1610 schema = self._apply_annotations( 1jmpgabknqhcdlorief

1611 field.annotation, 

1612 [field], 

1613 # Because we pass `field` as metadata above (required for attributes relevant for 

1614 # JSON Scheme generation), we need to ignore the potential warnings about `FieldInfo` 

1615 # attributes that will not be used: 

1616 check_unsupported_field_info_attributes=False, 

1617 ) 

1618 

1619 if not field.is_required(): 1jmpgabknqhcdlorief

1620 schema = wrap_default(field, schema) 1jmpgabknqhcdlorief

1621 

1622 return core_schema.named_tuple_field( 1jmpgabknqhcdlorief

1623 name, 

1624 schema, 

1625 validation_alias=_convert_to_aliases(field.validation_alias), 

1626 ) 

1627 

1628 def _generate_parameter_schema( 1jmpgabknqhcdslorief

1629 self, 

1630 name: str, 

1631 annotation: type[Any], 

1632 source: AnnotationSource, 

1633 default: Any = Parameter.empty, 

1634 mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None, 

1635 ) -> core_schema.ArgumentsParameter: 

1636 """Generate the definition of a parameter in a function signature. 

1637 

1638 This definition is meant to be used for the `'arguments'` core schema, which will be replaced 

1639 in V3 by the `'arguments-v3`'. 

1640 """ 

1641 FieldInfo = import_cached_field_info() 1jmpgabknqhcdlorief

1642 

1643 if default is Parameter.empty: 1643 ↛ 1644line 1643 didn't jump to line 1644 because the condition on line 1643 was never true1jmpgabknqhcdlorief

1644 field = FieldInfo.from_annotation(annotation, _source=source) 

1645 else: 

1646 field = FieldInfo.from_annotated_attribute(annotation, default, _source=source) 1jmpgabknqhcdlorief

1647 

1648 assert field.annotation is not None, 'field.annotation should not be None when generating a schema' 1jmpgabknqhcdlorief

1649 update_field_from_config(self._config_wrapper, name, field) 1jmpgabknqhcdlorief

1650 

1651 with self.field_name_stack.push(name): 1jmpgabknqhcdlorief

1652 schema = self._apply_annotations( 1jmpgabknqhcdlorief

1653 field.annotation, 

1654 [field], 

1655 # Because we pass `field` as metadata above (required for attributes relevant for 

1656 # JSON Scheme generation), we need to ignore the potential warnings about `FieldInfo` 

1657 # attributes that will not be used: 

1658 check_unsupported_field_info_attributes=False, 

1659 ) 

1660 

1661 if not field.is_required(): 1661 ↛ 1664line 1661 didn't jump to line 1664 because the condition on line 1661 was always true1jmpgabknqhcdlorief

1662 schema = wrap_default(field, schema) 1jmpgabknqhcdlorief

1663 

1664 parameter_schema = core_schema.arguments_parameter( 1jmpgabknqhcdlorief

1665 name, 

1666 schema, 

1667 mode=mode, 

1668 alias=_convert_to_aliases(field.validation_alias), 

1669 ) 

1670 

1671 return parameter_schema 1jmpgabknqhcdlorief

1672 

1673 def _generate_parameter_v3_schema( 1jmpgabknqhcdslorief

1674 self, 

1675 name: str, 

1676 annotation: Any, 

1677 source: AnnotationSource, 

1678 mode: Literal[ 

1679 'positional_only', 

1680 'positional_or_keyword', 

1681 'keyword_only', 

1682 'var_args', 

1683 'var_kwargs_uniform', 

1684 'var_kwargs_unpacked_typed_dict', 

1685 ], 

1686 default: Any = Parameter.empty, 

1687 ) -> core_schema.ArgumentsV3Parameter: 

1688 """Generate the definition of a parameter in a function signature. 

1689 

1690 This definition is meant to be used for the `'arguments-v3'` core schema, which will replace 

1691 the `'arguments`' schema in V3. 

1692 """ 

1693 FieldInfo = import_cached_field_info() 1jmpgabknqhcdlorief

1694 

1695 if default is Parameter.empty: 1jmpgabknqhcdlorief

1696 field = FieldInfo.from_annotation(annotation, _source=source) 1jmpgabknqhcdlorief

1697 else: 

1698 field = FieldInfo.from_annotated_attribute(annotation, default, _source=source) 1jmpgabknqhcdlorief

1699 update_field_from_config(self._config_wrapper, name, field) 1jmpgabknqhcdlorief

1700 

1701 with self.field_name_stack.push(name): 1jmpgabknqhcdlorief

1702 schema = self._apply_annotations( 1jmpgabknqhcdlorief

1703 field.annotation, 

1704 [field], 

1705 # Because we pass `field` as metadata above (required for attributes relevant for 

1706 # JSON Scheme generation), we need to ignore the potential warnings about `FieldInfo` 

1707 # attributes that will not be used: 

1708 check_unsupported_field_info_attributes=False, 

1709 ) 

1710 

1711 if not field.is_required(): 1jmpgabknqhcdlorief

1712 schema = wrap_default(field, schema) 1jmpgabknqhcdlorief

1713 

1714 parameter_schema = core_schema.arguments_v3_parameter( 1jmpgabknqhcdlorief

1715 name=name, 

1716 schema=schema, 

1717 mode=mode, 

1718 alias=_convert_to_aliases(field.validation_alias), 

1719 ) 

1720 

1721 return parameter_schema 1jmpgabknqhcdlorief

1722 

1723 def _tuple_schema(self, tuple_type: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1724 """Generate schema for a Tuple, e.g. `tuple[int, str]` or `tuple[int, ...]`.""" 

1725 # TODO: do we really need to resolve type vars here? 

1726 typevars_map = get_standard_typevars_map(tuple_type) 1jmpgabknqhcdlorief

1727 params = self._get_args_resolving_forward_refs(tuple_type) 1jmpgabknqhcdlorief

1728 

1729 if typevars_map and params: 1729 ↛ 1730line 1729 didn't jump to line 1730 because the condition on line 1729 was never true1jmpgabknqhcdlorief

1730 params = tuple(replace_types(param, typevars_map) for param in params) 

1731 

1732 if not params: 1jmpgabknqhcdlorief

1733 if tuple_type in TUPLE_TYPES: 1jmpgabknqhcdlorief

1734 return core_schema.tuple_schema([core_schema.any_schema()], variadic_item_index=0) 1jmpgabknqhcdlorief

1735 else: 

1736 # special case for `tuple[()]` which means `tuple[]` - an empty tuple 

1737 return core_schema.tuple_schema([]) 1jmpgabknqhcdlorief

1738 elif params[-1] is Ellipsis: 1jmpgabknqhcdlorief

1739 if len(params) == 2: 1739 ↛ 1743line 1739 didn't jump to line 1743 because the condition on line 1739 was always true1jmpgabknqhcdlorief

1740 return core_schema.tuple_schema([self.generate_schema(params[0])], variadic_item_index=0) 1jmpgabknqhcdlorief

1741 else: 

1742 # TODO: something like https://github.com/pydantic/pydantic/issues/5952 

1743 raise ValueError('Variable tuples can only have one type') 

1744 else: 

1745 return core_schema.tuple_schema([self.generate_schema(param) for param in params]) 1jmpgabknqhcdlorief

1746 

1747 def _type_schema(self) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1748 return core_schema.custom_error_schema( 1jmpgabknqhcdlorief

1749 core_schema.is_instance_schema(type), 

1750 custom_error_type='is_type', 

1751 custom_error_message='Input should be a type', 

1752 ) 

1753 

1754 def _zoneinfo_schema(self) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1755 """Generate schema for a zone_info.ZoneInfo object""" 

1756 from ._validators import validate_str_is_valid_iana_tz 1jmpgabknqhcdlorief

1757 

1758 metadata = {'pydantic_js_functions': [lambda _1, _2: {'type': 'string', 'format': 'zoneinfo'}]} 1jmpgabknqhcdlorief

1759 return core_schema.no_info_plain_validator_function( 1jmpgabknqhcdlorief

1760 validate_str_is_valid_iana_tz, 

1761 serialization=core_schema.to_string_ser_schema(), 

1762 metadata=metadata, 

1763 ) 

1764 

1765 def _union_is_subclass_schema(self, union_type: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1766 """Generate schema for `type[Union[X, ...]]`.""" 

1767 args = self._get_args_resolving_forward_refs(union_type, required=True) 1jmpgabknqhcdlorief

1768 return core_schema.union_schema([self.generate_schema(type[args]) for args in args]) 1jmpgabknqhcdlorief

1769 

1770 def _subclass_schema(self, type_: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1771 """Generate schema for a type, e.g. `type[int]`.""" 

1772 type_param = self._get_first_arg_or_any(type_) 1jmpgabknqhcdlorief

1773 

1774 # Assume `type[Annotated[<typ>, ...]]` is equivalent to `type[<typ>]`: 

1775 type_param = _typing_extra.annotated_type(type_param) or type_param 1jmpgabknqhcdlorief

1776 

1777 if typing_objects.is_any(type_param): 1jmpgabknqhcdlorief

1778 return self._type_schema() 1jmpgabknqhcdlorief

1779 elif typing_objects.is_typealiastype(type_param): 1jmpgabknqhcdlorief

1780 return self.generate_schema(type[type_param.__value__]) 1jmpgabknqhcdlorief

1781 elif typing_objects.is_typevar(type_param): 1jmpgabknqhcdlorief

1782 if type_param.__bound__: 1jmpgabknqhcdlorief

1783 if is_union_origin(get_origin(type_param.__bound__)): 1jmpgabknqhcdlorief

1784 return self._union_is_subclass_schema(type_param.__bound__) 1jmpgabknqhcdlorief

1785 return core_schema.is_subclass_schema(type_param.__bound__) 1jmpgabknqhcdlorief

1786 elif type_param.__constraints__: 1jmpgabknqhcdlorief

1787 return core_schema.union_schema([self.generate_schema(type[c]) for c in type_param.__constraints__]) 1jmpgabknqhcdlorief

1788 else: 

1789 return self._type_schema() 1jmpgabknqhcdlorief

1790 elif is_union_origin(get_origin(type_param)): 1jmpgabknqhcdlorief

1791 return self._union_is_subclass_schema(type_param) 1jmpgabknqhcdlorief

1792 else: 

1793 if typing_objects.is_self(type_param): 1jmpgabknqhcdlorief

1794 type_param = self._resolve_self_type(type_param) 1jmpgabknqhcdlorief

1795 if _typing_extra.is_generic_alias(type_param): 1jmpgabknqhcdlorief

1796 raise PydanticUserError( 1jmpgabknqhcdlorief

1797 'Subscripting `type[]` with an already parametrized type is not supported. ' 

1798 f'Instead of using type[{type_param!r}], use type[{_repr.display_as_type(get_origin(type_param))}].', 

1799 code=None, 

1800 ) 

1801 if not inspect.isclass(type_param): 1jmpgabknqhcdlorief

1802 # when using type[None], this doesn't type convert to type[NoneType], and None isn't a class 

1803 # so we handle it manually here 

1804 if type_param is None: 1804 ↛ 1806line 1804 didn't jump to line 1806 because the condition on line 1804 was always true1jmpgabknqhcdlorief

1805 return core_schema.is_subclass_schema(NoneType) 1jmpgabknqhcdlorief

1806 raise TypeError(f'Expected a class, got {type_param!r}') 

1807 return core_schema.is_subclass_schema(type_param) 1jmpgabknqhcdlorief

1808 

1809 def _sequence_schema(self, items_type: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1810 """Generate schema for a Sequence, e.g. `Sequence[int]`.""" 

1811 from ._serializers import serialize_sequence_via_list 1jmpgabknqhcdlorief

1812 

1813 item_type_schema = self.generate_schema(items_type) 1jmpgabknqhcdlorief

1814 list_schema = core_schema.list_schema(item_type_schema) 1jmpgabknqhcdlorief

1815 

1816 json_schema = smart_deepcopy(list_schema) 1jmpgabknqhcdlorief

1817 python_schema = core_schema.is_instance_schema(typing.Sequence, cls_repr='Sequence') 1jmpgabknqhcdlorief

1818 if not typing_objects.is_any(items_type): 1jmpgabknqhcdlorief

1819 from ._validators import sequence_validator 1jmpgabknqhcdlorief

1820 

1821 python_schema = core_schema.chain_schema( 1jmpgabknqhcdlorief

1822 [python_schema, core_schema.no_info_wrap_validator_function(sequence_validator, list_schema)], 

1823 ) 

1824 

1825 serialization = core_schema.wrap_serializer_function_ser_schema( 1jmpgabknqhcdlorief

1826 serialize_sequence_via_list, schema=item_type_schema, info_arg=True 

1827 ) 

1828 return core_schema.json_or_python_schema( 1jmpgabknqhcdlorief

1829 json_schema=json_schema, python_schema=python_schema, serialization=serialization 

1830 ) 

1831 

1832 def _iterable_schema(self, type_: Any) -> core_schema.GeneratorSchema: 1jmpgabknqhcdslorief

1833 """Generate a schema for an `Iterable`.""" 

1834 item_type = self._get_first_arg_or_any(type_) 1jmpgabknqhcdlorief

1835 

1836 return core_schema.generator_schema(self.generate_schema(item_type)) 1jmpgabknqhcdlorief

1837 

1838 def _pattern_schema(self, pattern_type: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1839 from . import _validators 1jmpgabknqhcdlorief

1840 

1841 metadata = {'pydantic_js_functions': [lambda _1, _2: {'type': 'string', 'format': 'regex'}]} 1jmpgabknqhcdlorief

1842 ser = core_schema.plain_serializer_function_ser_schema( 1jmpgabknqhcdlorief

1843 attrgetter('pattern'), when_used='json', return_schema=core_schema.str_schema() 

1844 ) 

1845 if pattern_type is typing.Pattern or pattern_type is re.Pattern: 1jmpgabknqhcdlorief

1846 # bare type 

1847 return core_schema.no_info_plain_validator_function( 1jmpgabknqhcdlorief

1848 _validators.pattern_either_validator, serialization=ser, metadata=metadata 

1849 ) 

1850 

1851 param = self._get_args_resolving_forward_refs( 1jmpgabknqhcdlorief

1852 pattern_type, 

1853 required=True, 

1854 )[0] 

1855 if param is str: 1jmpgabknqhcdlorief

1856 return core_schema.no_info_plain_validator_function( 1jmpgabknqhcdlorief

1857 _validators.pattern_str_validator, serialization=ser, metadata=metadata 

1858 ) 

1859 elif param is bytes: 1jmpgabknqhcdlorief

1860 return core_schema.no_info_plain_validator_function( 1jmpgabknqhcdlorief

1861 _validators.pattern_bytes_validator, serialization=ser, metadata=metadata 

1862 ) 

1863 else: 

1864 raise PydanticSchemaGenerationError(f'Unable to generate pydantic-core schema for {pattern_type!r}.') 1jmpgabknqhcdlorief

1865 

1866 def _hashable_schema(self) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

1867 return core_schema.custom_error_schema( 1jmpgabknqhcdlorief

1868 schema=core_schema.json_or_python_schema( 

1869 json_schema=core_schema.chain_schema( 

1870 [core_schema.any_schema(), core_schema.is_instance_schema(collections.abc.Hashable)] 

1871 ), 

1872 python_schema=core_schema.is_instance_schema(collections.abc.Hashable), 

1873 ), 

1874 custom_error_type='is_hashable', 

1875 custom_error_message='Input should be hashable', 

1876 ) 

1877 

1878 def _dataclass_schema( 1jmpgabknqhcdslorief

1879 self, dataclass: type[StandardDataclass], origin: type[StandardDataclass] | None 

1880 ) -> core_schema.CoreSchema: 

1881 """Generate schema for a dataclass.""" 

1882 dataclass_ref = _type_refs.class_type_ref(dataclass, origin) 1jmpgabknqhcdslorief

1883 with ( 1jgabkhcdlief

1884 self.model_type_stack.push(dataclass), 

1885 self.defs.get_definition_ref_schema(ref=dataclass_ref) as maybe_schema, 

1886 ): 

1887 if maybe_schema is not None: 1jmpgabknqhcdslorief

1888 return maybe_schema 1jmpgabknqhcdlorief

1889 

1890 schema = dataclass.__dict__.get('__pydantic_core_schema__') 1jmpgabknqhcdslorief

1891 if schema is not None and not isinstance(schema, MockCoreSchema): 1jmpgabknqhcdslorief

1892 if schema['type'] == 'definitions': 1jmpgabknqhcdlorief

1893 schema = self.defs.unpack_definitions(schema) 1jmpgabknqhcdlorief

1894 ref = get_ref(schema) 1jmpgabknqhcdlorief

1895 if ref: 1jmpgabknqhcdlorief

1896 return self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdlorief

1897 else: 

1898 return schema 1jmpgabknqhcdlorief

1899 

1900 typevars_map = get_standard_typevars_map(dataclass) 1jmpgabknqhcdslorief

1901 if origin is not None: 1jmpgabknqhcdslorief

1902 dataclass = origin 1jmpgabknqhcdlorief

1903 

1904 # if (plain) dataclass doesn't have config, we use the parent's config, hence a default of `None` 

1905 # (Pydantic dataclasses have an empty dict config by default). 

1906 # see https://github.com/pydantic/pydantic/issues/10917 

1907 config = getattr(dataclass, '__pydantic_config__', None) 1jmpgabknqhcdslorief

1908 

1909 from ..dataclasses import is_pydantic_dataclass 1jmpgabknqhcdslorief

1910 

1911 with self._ns_resolver.push(dataclass), self._config_wrapper_stack.push(config): 1jmpgabknqhcdslorief

1912 if is_pydantic_dataclass(dataclass): 1jmpgabknqhcdslorief

1913 if dataclass.__pydantic_fields_complete__(): 1jmpgabknqhcdslorief

1914 # Copy the field info instances to avoid mutating the `FieldInfo` instances 

1915 # of the generic dataclass generic origin (e.g. `apply_typevars_map` below). 

1916 # Note that we don't apply `deepcopy` on `__pydantic_fields__` because we 

1917 # don't want to copy the `FieldInfo` attributes: 

1918 fields = { 1jmpgabknqhcdslorief

1919 f_name: copy(field_info) for f_name, field_info in dataclass.__pydantic_fields__.items() 

1920 } 

1921 if typevars_map: 1jmpgabknqhcdslorief

1922 for field in fields.values(): 1jmpgabknqhcdlorief

1923 field.apply_typevars_map(typevars_map, *self._types_namespace) 1jmpgabknqhcdlorief

1924 else: 

1925 try: 1jmpgabknqhcdlorief

1926 fields = rebuild_dataclass_fields( 1jmpgabknqhcdlorief

1927 dataclass, 

1928 config_wrapper=self._config_wrapper, 

1929 ns_resolver=self._ns_resolver, 

1930 typevars_map=typevars_map or {}, 

1931 ) 

1932 except NameError as e: 1jmpgabknqhcdlorief

1933 raise PydanticUndefinedAnnotation.from_name_error(e) from e 1jmpgabknqhcdlorief

1934 else: 

1935 fields = collect_dataclass_fields( 1jmpgabknqhcdlorief

1936 dataclass, 

1937 typevars_map=typevars_map, 

1938 config_wrapper=self._config_wrapper, 

1939 ) 

1940 

1941 if self._config_wrapper.extra == 'allow': 1jmpgabknqhcdslorief

1942 # disallow combination of init=False on a dataclass field and extra='allow' on a dataclass 

1943 for field_name, field in fields.items(): 1jmpgabknqhcdlorief

1944 if field.init is False: 1jmpgabknqhcdlorief

1945 raise PydanticUserError( 1jmpgabknqhcdlorief

1946 f'Field {field_name} has `init=False` and dataclass has config setting `extra="allow"`. ' 

1947 f'This combination is not allowed.', 

1948 code='dataclass-init-false-extra-allow', 

1949 ) 

1950 

1951 decorators = dataclass.__dict__.get('__pydantic_decorators__') 1jmpgabknqhcdslorief

1952 if decorators is None: 1jmpgabknqhcdslorief

1953 decorators = DecoratorInfos.build(dataclass, replace_wrapped_methods=False) 1jmpgabknqhcdlorief

1954 decorators.update_from_config(self._config_wrapper) 1jmpgabknqhcdlorief

1955 # Move kw_only=False args to the start of the list, as this is how vanilla dataclasses work. 

1956 # Note that when kw_only is missing or None, it is treated as equivalent to kw_only=True 

1957 args = sorted( 1jmpgabknqhcdslorief

1958 (self._generate_dc_field_schema(k, v, decorators) for k, v in fields.items()), 

1959 key=lambda a: a.get('kw_only') is not False, 

1960 ) 

1961 has_post_init = hasattr(dataclass, '__post_init__') 1jmpgabknqhcdslorief

1962 has_slots = hasattr(dataclass, '__slots__') 1jmpgabknqhcdslorief

1963 

1964 args_schema = core_schema.dataclass_args_schema( 1jmpgabknqhcdslorief

1965 dataclass.__name__, 

1966 args, 

1967 computed_fields=[ 

1968 self._computed_field_schema(d, decorators.field_serializers) 

1969 for d in decorators.computed_fields.values() 

1970 ], 

1971 collect_init_only=has_post_init, 

1972 ) 

1973 

1974 model_validators = decorators.model_validators.values() 1jmpgabknqhcdslorief

1975 inner_schema = apply_model_validators(args_schema, model_validators, 'inner') 1jmpgabknqhcdslorief

1976 

1977 core_config = self._config_wrapper.core_config(title=dataclass.__name__) 1jmpgabknqhcdslorief

1978 

1979 dc_schema = core_schema.dataclass_schema( 1jmpgabknqhcdslorief

1980 dataclass, 

1981 inner_schema, 

1982 generic_origin=origin, 

1983 post_init=has_post_init, 

1984 ref=dataclass_ref, 

1985 fields=[field.name for field in dataclasses.fields(dataclass)], 

1986 slots=has_slots, 

1987 config=core_config, 

1988 # we don't use a custom __setattr__ for dataclasses, so we must 

1989 # pass along the frozen config setting to the pydantic-core schema 

1990 frozen=self._config_wrapper_stack.tail.frozen, 

1991 ) 

1992 schema = self._apply_model_serializers(dc_schema, decorators.model_serializers.values()) 1jmpgabknqhcdslorief

1993 schema = apply_model_validators(schema, model_validators, 'outer') 1jmpgabknqhcdslorief

1994 return self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdslorief

1995 

1996 def _call_schema(self, function: ValidateCallSupportedTypes) -> core_schema.CallSchema: 1jmpgabknqhcdslorief

1997 """Generate schema for a Callable. 

1998 

1999 TODO support functional validators once we support them in Config 

2000 """ 

2001 arguments_schema = self._arguments_v3_schema(function) 1jmpgabknqhcdlorief

2002 

2003 return_schema: core_schema.CoreSchema | None = None 1jmpgabknqhcdlorief

2004 config_wrapper = self._config_wrapper 1jmpgabknqhcdlorief

2005 if config_wrapper.validate_return: 1jmpgabknqhcdlorief

2006 sig = _typing_extra.signature_no_eval(function) 1jmpgabknqhcdlorief

2007 return_hint = sig.return_annotation 1jmpgabknqhcdlorief

2008 if return_hint is not sig.empty: 2008 ↛ 2015line 2008 didn't jump to line 2015 because the condition on line 2008 was always true1jmpgabknqhcdlorief

2009 globalns, localns = self._types_namespace 1jmpgabknqhcdlorief

2010 type_hints = _typing_extra.get_function_type_hints( 1jmpgabknqhcdlorief

2011 function, globalns=globalns, localns=localns, include_keys={'return'} 

2012 ) 

2013 return_schema = self.generate_schema(type_hints['return']) 1jmpgabknqhcdlorief

2014 

2015 return core_schema.call_schema( 1jmpgabknqhcdlorief

2016 arguments_schema, 

2017 function, 

2018 return_schema=return_schema, 

2019 ) 

2020 

2021 def _arguments_schema( 1jmpgabknqhcdslorief

2022 self, function: ValidateCallSupportedTypes, parameters_callback: ParametersCallback | None = None 

2023 ) -> core_schema.ArgumentsSchema: 

2024 """Generate schema for a Signature.""" 

2025 mode_lookup: dict[_ParameterKind, Literal['positional_only', 'positional_or_keyword', 'keyword_only']] = { 1jmpgabknqhcdlorief

2026 Parameter.POSITIONAL_ONLY: 'positional_only', 

2027 Parameter.POSITIONAL_OR_KEYWORD: 'positional_or_keyword', 

2028 Parameter.KEYWORD_ONLY: 'keyword_only', 

2029 } 

2030 

2031 sig = _typing_extra.signature_no_eval(function) 1jmpgabknqhcdlorief

2032 globalns, localns = self._types_namespace 1jmpgabknqhcdlorief

2033 type_hints = _typing_extra.get_function_type_hints(function, globalns=globalns, localns=localns) 1jmpgabknqhcdlorief

2034 

2035 arguments_list: list[core_schema.ArgumentsParameter] = [] 1jmpgabknqhcdlorief

2036 var_args_schema: core_schema.CoreSchema | None = None 1jmpgabknqhcdlorief

2037 var_kwargs_schema: core_schema.CoreSchema | None = None 1jmpgabknqhcdlorief

2038 var_kwargs_mode: core_schema.VarKwargsMode | None = None 1jmpgabknqhcdlorief

2039 

2040 core_config = self._config_wrapper.core_config(title=None) 1jmpgabknqhcdlorief

2041 

2042 for i, (name, p) in enumerate(sig.parameters.items()): 1jmpgabknqhcdlorief

2043 if p.annotation is sig.empty: 2043 ↛ 2044line 2043 didn't jump to line 2044 because the condition on line 2043 was never true1jmpgabknqhcdlorief

2044 annotation = typing.cast(Any, Any) 

2045 else: 

2046 annotation = type_hints[name] 1jmpgabknqhcdlorief

2047 

2048 if parameters_callback is not None: 1jmpgabknqhcdlorief

2049 result = parameters_callback(i, name, annotation) 1jmpgabknqhcdlorief

2050 if result == 'skip': 1jmpgabknqhcdlorief

2051 continue 1jmpgabknqhcdlorief

2052 

2053 parameter_mode = mode_lookup.get(p.kind) 1jmpgabknqhcdlorief

2054 if parameter_mode is not None: 1jmpgabknqhcdlorief

2055 arg_schema = self._generate_parameter_schema( 1jmpgabknqhcdlorief

2056 name, annotation, AnnotationSource.FUNCTION, p.default, parameter_mode 

2057 ) 

2058 arguments_list.append(arg_schema) 1jmpgabknqhcdlorief

2059 elif p.kind == Parameter.VAR_POSITIONAL: 1jmpgabknqhcdlorief

2060 var_args_schema = self.generate_schema(annotation) 1jmpgabknqhcdlorief

2061 else: 

2062 assert p.kind == Parameter.VAR_KEYWORD, p.kind 1jmpgabknqhcdlorief

2063 

2064 unpack_type = _typing_extra.unpack_type(annotation) 1jmpgabknqhcdlorief

2065 if unpack_type is not None: 1jmpgabknqhcdlorief

2066 origin = get_origin(unpack_type) or unpack_type 1jmpgabknqhcdlorief

2067 if not is_typeddict(origin): 2067 ↛ 2068line 2067 didn't jump to line 2068 because the condition on line 2067 was never true1jmpgabknqhcdlorief

2068 raise PydanticUserError( 

2069 f'Expected a `TypedDict` class inside `Unpack[...]`, got {unpack_type!r}', 

2070 code='unpack-typed-dict', 

2071 ) 

2072 non_pos_only_param_names = { 1jmpgabknqhcdlorief

2073 name for name, p in sig.parameters.items() if p.kind != Parameter.POSITIONAL_ONLY 

2074 } 

2075 overlapping_params = non_pos_only_param_names.intersection(origin.__annotations__) 1jmpgabknqhcdlorief

2076 if overlapping_params: 2076 ↛ 2077line 2076 didn't jump to line 2077 because the condition on line 2076 was never true1jmpgabknqhcdlorief

2077 raise PydanticUserError( 

2078 f'Typed dictionary {origin.__name__!r} overlaps with parameter' 

2079 f'{"s" if len(overlapping_params) >= 2 else ""} ' 

2080 f'{", ".join(repr(p) for p in sorted(overlapping_params))}', 

2081 code='overlapping-unpack-typed-dict', 

2082 ) 

2083 

2084 var_kwargs_mode = 'unpacked-typed-dict' 1jmpgabknqhcdlorief

2085 var_kwargs_schema = self._typed_dict_schema(unpack_type, get_origin(unpack_type)) 1jmpgabknqhcdlorief

2086 else: 

2087 var_kwargs_mode = 'uniform' 1jmpgabknqhcdlorief

2088 var_kwargs_schema = self.generate_schema(annotation) 1jmpgabknqhcdlorief

2089 

2090 return core_schema.arguments_schema( 1jmpgabknqhcdlorief

2091 arguments_list, 

2092 var_args_schema=var_args_schema, 

2093 var_kwargs_mode=var_kwargs_mode, 

2094 var_kwargs_schema=var_kwargs_schema, 

2095 validate_by_name=core_config.get('validate_by_name'), 

2096 ) 

2097 

2098 def _arguments_v3_schema( 1jmpgabknqhcdslorief

2099 self, function: ValidateCallSupportedTypes, parameters_callback: ParametersCallback | None = None 

2100 ) -> core_schema.ArgumentsV3Schema: 

2101 mode_lookup: dict[ 1jmpgabknqhcdlorief

2102 _ParameterKind, Literal['positional_only', 'positional_or_keyword', 'var_args', 'keyword_only'] 

2103 ] = { 

2104 Parameter.POSITIONAL_ONLY: 'positional_only', 

2105 Parameter.POSITIONAL_OR_KEYWORD: 'positional_or_keyword', 

2106 Parameter.VAR_POSITIONAL: 'var_args', 

2107 Parameter.KEYWORD_ONLY: 'keyword_only', 

2108 } 

2109 

2110 sig = _typing_extra.signature_no_eval(function) 1jmpgabknqhcdlorief

2111 globalns, localns = self._types_namespace 1jmpgabknqhcdlorief

2112 type_hints = _typing_extra.get_function_type_hints(function, globalns=globalns, localns=localns) 1jmpgabknqhcdlorief

2113 

2114 parameters_list: list[core_schema.ArgumentsV3Parameter] = [] 1jmpgabknqhcdlorief

2115 core_config = self._config_wrapper.core_config(title=None) 1jmpgabknqhcdlorief

2116 

2117 for i, (name, p) in enumerate(sig.parameters.items()): 1jmpgabknqhcdlorief

2118 if parameters_callback is not None: 1jmpgabknqhcdlorief

2119 result = parameters_callback(i, name, p.annotation) 1jmpgabknqhcdlorief

2120 if result == 'skip': 1jmpgabknqhcdlorief

2121 continue 1jmpgabknqhcdlorief

2122 

2123 if p.annotation is Parameter.empty: 1jmpgabknqhcdlorief

2124 annotation = typing.cast(Any, Any) 1jmpgabknqhcdlorief

2125 else: 

2126 annotation = type_hints[name] 1jmpgabknqhcdlorief

2127 

2128 parameter_mode = mode_lookup.get(p.kind) 1jmpgabknqhcdlorief

2129 if parameter_mode is None: 1jmpgabknqhcdlorief

2130 assert p.kind == Parameter.VAR_KEYWORD, p.kind 1jmpgabknqhcdlorief

2131 

2132 unpack_type = _typing_extra.unpack_type(annotation) 1jmpgabknqhcdlorief

2133 if unpack_type is not None: 1jmpgabknqhcdlorief

2134 origin = get_origin(unpack_type) or unpack_type 1jmpgabknqhcdlorief

2135 if not is_typeddict(origin): 1jmpgabknqhcdlorief

2136 raise PydanticUserError( 1jmpgabknqhcdlorief

2137 f'Expected a `TypedDict` class inside `Unpack[...]`, got {unpack_type!r}', 

2138 code='unpack-typed-dict', 

2139 ) 

2140 non_pos_only_param_names = { 1jmpgabknqhcdlorief

2141 name for name, p in sig.parameters.items() if p.kind != Parameter.POSITIONAL_ONLY 

2142 } 

2143 overlapping_params = non_pos_only_param_names.intersection(origin.__annotations__) 1jmpgabknqhcdlorief

2144 if overlapping_params: 1jmpgabknqhcdlorief

2145 raise PydanticUserError( 1jmpgabknqhcdlorief

2146 f'Typed dictionary {origin.__name__!r} overlaps with parameter' 

2147 f'{"s" if len(overlapping_params) >= 2 else ""} ' 

2148 f'{", ".join(repr(p) for p in sorted(overlapping_params))}', 

2149 code='overlapping-unpack-typed-dict', 

2150 ) 

2151 parameter_mode = 'var_kwargs_unpacked_typed_dict' 1jmpgabknqhcdlorief

2152 annotation = unpack_type 1jmpgabknqhcdlorief

2153 else: 

2154 parameter_mode = 'var_kwargs_uniform' 1jmpgabknqhcdlorief

2155 

2156 parameters_list.append( 1jmpgabknqhcdlorief

2157 self._generate_parameter_v3_schema( 

2158 name, annotation, AnnotationSource.FUNCTION, parameter_mode, default=p.default 

2159 ) 

2160 ) 

2161 

2162 # Unexpected arguments are only rejected with `'forbid'`, so `'allow'` behaves like `'ignore'`. 

2163 # This is set on the schema (the validator would otherwise read it from the config) so that 

2164 # the JSON Schema generation can take it into account: 

2165 extra = core_config.get('extra_fields_behavior') 1jmpgabknqhcdlorief

2166 extra_behavior: Literal['forbid', 'ignore'] | None = ( 1jmpgabknqhcdlorief

2167 None if extra is None else 'forbid' if extra == 'forbid' else 'ignore' 

2168 ) 

2169 

2170 return core_schema.arguments_v3_schema( 1jmpgabknqhcdlorief

2171 parameters_list, 

2172 validate_by_name=core_config.get('validate_by_name'), 

2173 extra_behavior=extra_behavior, 

2174 ) 

2175 

2176 def _unsubstituted_typevar_schema(self, typevar: typing.TypeVar) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

2177 try: 1jmpgabknqhcdslorief

2178 has_default = typevar.has_default() # pyright: ignore[reportAttributeAccessIssue] 1jmpgabknqhcdslorief

2179 except AttributeError: 1jmknlo

2180 # Happens if using `typing.TypeVar` (and not `typing_extensions`) on Python < 3.13 

2181 pass 1jmknlo

2182 else: 

2183 if has_default: 1jmpgabknqhcdslorief

2184 return self.generate_schema(typevar.__default__) # pyright: ignore[reportAttributeAccessIssue] 1jmpgabknqhcdlorief

2185 

2186 if constraints := typevar.__constraints__: 1jmpgabknqhcdslorief

2187 return self._union_schema(typing.Union[constraints]) # noqa: UP007 1jmpgabknqhcdlorief

2188 

2189 if bound := typevar.__bound__: 1jmpgabknqhcdslorief

2190 schema = self.generate_schema(bound) 1jmpgabknqhcdlorief

2191 schema['serialization'] = core_schema.simple_ser_schema('any') 1jmpgabknqhcdlorief

2192 return schema 1jmpgabknqhcdlorief

2193 

2194 return core_schema.any_schema() 1jmpgabknqhcdslorief

2195 

2196 def _computed_field_schema( 1jmpgabknqhcdslorief

2197 self, 

2198 d: Decorator[ComputedFieldInfo], 

2199 field_serializers: dict[str, Decorator[FieldSerializerDecoratorInfo]], 

2200 ) -> core_schema.ComputedField: 

2201 if d.info.return_type is not PydanticUndefined: 1jmpgabknqhcdlorief

2202 return_type = d.info.return_type 1jmpgabknqhcdlorief

2203 else: 

2204 try: 1jmpgabknqhcdlorief

2205 # Do not pass in globals as the function could be defined in a different module. 

2206 # Instead, let `get_callable_return_type` infer the globals to use, but still pass 

2207 # in locals that may contain a parent/rebuild namespace: 

2208 return_type = _decorators.get_callable_return_type(d.func, localns=self._types_namespace.locals) 1jmpgabknqhcdlorief

2209 except NameError as e: 1jmpgabknqhcdlorief

2210 raise PydanticUndefinedAnnotation.from_name_error(e) from e 1jmpgabknqhcdlorief

2211 if return_type is PydanticUndefined: 1jmpgabknqhcdlorief

2212 raise PydanticUserError( 1jmpgabknqhcdlorief

2213 'Computed field is missing return type annotation or specifying `return_type`' 

2214 ' to the `@computed_field` decorator (e.g. `@computed_field(return_type=int | str)`)', 

2215 code='model-field-missing-annotation', 

2216 ) 

2217 

2218 return_type = replace_types(return_type, self._typevars_map) 1jmpgabknqhcdlorief

2219 # Create a new ComputedFieldInfo so that different type parametrizations of the same 

2220 # generic model's computed field can have different return types. 

2221 d.info = dataclasses.replace(d.info, return_type=return_type) 1jmpgabknqhcdlorief

2222 return_type_schema = self.generate_schema(return_type) 1jmpgabknqhcdlorief

2223 # Apply serializers to computed field if there exist 

2224 return_type_schema = self._apply_field_serializers( 1jmpgabknqhcdlorief

2225 return_type_schema, 

2226 filter_field_decorator_info_by_field(field_serializers.values(), d.cls_var_name), 

2227 ) 

2228 

2229 pydantic_js_updates, pydantic_js_extra = _extract_json_schema_info_from_field_info(d.info) 1jmpgabknqhcdlorief

2230 core_metadata: dict[str, Any] = {} 1jmpgabknqhcdlorief

2231 update_core_metadata( 1jmpgabknqhcdlorief

2232 core_metadata, 

2233 pydantic_js_updates={'readOnly': True, **(pydantic_js_updates if pydantic_js_updates else {})}, 

2234 pydantic_js_extra=pydantic_js_extra, 

2235 ) 

2236 exclude_if = d.info.exclude_if 1jmpgabknqhcdlorief

2237 # TODO: Should we support exclude_if from annotations? 

2238 return core_schema.computed_field( 1jmpgabknqhcdlorief

2239 d.cls_var_name, 

2240 return_schema=return_type_schema, 

2241 alias=d.info.alias, 

2242 serialization_exclude_if=exclude_if, 

2243 metadata=core_metadata, 

2244 ) 

2245 

2246 def _annotated_schema(self, annotated_type: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

2247 """Generate schema for an Annotated type, e.g. `Annotated[int, Field(...)]` or `Annotated[int, Gt(0)]`.""" 

2248 FieldInfo = import_cached_field_info() 1jmpgabknqhcdlorief

2249 source_type, *annotations = self._get_args_resolving_forward_refs( 1jmpgabknqhcdlorief

2250 annotated_type, 

2251 required=True, 

2252 ) 

2253 schema = self._apply_annotations(source_type, annotations) 1jmpgabknqhcdlorief

2254 # put the default validator last so that TypeAdapter.get_default_value() works 

2255 # even if there are function validators involved 

2256 for annotation in annotations: 1jmpgabknqhcdlorief

2257 if isinstance(annotation, FieldInfo): 1jmpgabknqhcdlorief

2258 schema = wrap_default(annotation, schema) 1jmpgabknqhcdlorief

2259 return schema 1jmpgabknqhcdlorief

2260 

2261 def _apply_annotations( 1jmpgabknqhcdslorief

2262 self, 

2263 source_type: Any, 

2264 annotations: list[Any], 

2265 transform_inner_schema: Callable[[CoreSchema], CoreSchema] = lambda x: x, 

2266 check_unsupported_field_info_attributes: bool = True, 

2267 ) -> CoreSchema: 

2268 """Apply arguments from `Annotated` or from `FieldInfo` to a schema. 

2269 

2270 This gets called by `GenerateSchema._annotated_schema` but differs from it in that it does 

2271 not expect `source_type` to be an `Annotated` object, it expects it to be the first argument of that 

2272 (in other words, `GenerateSchema._annotated_schema` just unpacks `Annotated`, this process it). 

2273 """ 

2274 

2275 def inner_handler(obj: Any) -> CoreSchema: 1jmpgabknqhcdslorief

2276 if _is_simple_schema_type(obj): 1jmpgabknqhcdslorief

2277 return transform_inner_schema(self._handlers[obj](self, obj)) 1jmpgabknqhcdslorief

2278 

2279 origin = get_origin(obj) 1jmpgabknqhcdslorief

2280 schema: CoreSchema | None = None 1jmpgabknqhcdslorief

2281 if origin is None: 1jmpgabknqhcdslorief

2282 # If the type has an origin, it is guaranteed to *not* be an ordinary class that could have 

2283 # a `__get_pydantic_core_schema__()` method: 

2284 schema = self._generate_schema_from_get_schema_method(obj, source_type) 1jmpgabknqhcdslorief

2285 

2286 if schema is None: 1jmpgabknqhcdslorief

2287 schema = self._generate_schema_inner(obj, origin) 1jmpgabknqhcdslorief

2288 

2289 # `__get_pydantic_json_schema__()` is checked on the origin if it exists: 

2290 metadata_js_function = _extract_get_pydantic_json_schema(origin if origin is not None else obj) 1jmpgabknqhcdslorief

2291 if metadata_js_function is not None: 1jmpgabknqhcdslorief

2292 metadata_schema = resolve_original_schema(schema, self.defs) 1jmpgabknqhcdslorief

2293 if metadata_schema is not None: 1jmpgabknqhcdslorief

2294 self._add_js_function(metadata_schema, metadata_js_function) 1jmpgabknqhcdslorief

2295 return transform_inner_schema(schema) 1jmpgabknqhcdslorief

2296 

2297 if not annotations: 1jmpgabknqhcdslorief

2298 schema = inner_handler(source_type) 1jmpgabknqhcdslorief

2299 # Preserve the callback handler's reference conversion before applying encoders. 

2300 if schema.get('ref') is not None: 1jmpgabknqhcdslorief

2301 schema = self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdlorief

2302 return _add_custom_serialization_from_json_encoders(self._config_wrapper.json_encoders, source_type, schema) 1jmpgabknqhcdslorief

2303 

2304 annotations = list(_known_annotated_metadata.expand_grouped_metadata(annotations)) 1jmpgabknqhcdslorief

2305 pydantic_js_annotation_functions: list[GetJsonSchemaFunction] = [] 1jmpgabknqhcdslorief

2306 get_inner_schema = CallbackGetCoreSchemaHandler(inner_handler, self) 1jmpgabknqhcdslorief

2307 

2308 for annotation in annotations: 1jmpgabknqhcdslorief

2309 if annotation is None: 1jmpgabknqhcdslorief

2310 continue 1jmpgabknqhcdlorief

2311 get_inner_schema = self._get_wrapped_inner_schema( 1jmpgabknqhcdslorief

2312 get_inner_schema, 

2313 annotation, 

2314 pydantic_js_annotation_functions, 

2315 check_unsupported_field_info_attributes=check_unsupported_field_info_attributes, 

2316 ) 

2317 

2318 schema = get_inner_schema(source_type) 1jmpgabknqhcdslorief

2319 if pydantic_js_annotation_functions: 1jmpgabknqhcdslorief

2320 core_metadata = schema.setdefault('metadata', {}) 1jmpgabknqhcdlorief

2321 update_core_metadata(core_metadata, pydantic_js_annotation_functions=pydantic_js_annotation_functions) 1jmpgabknqhcdlorief

2322 return _add_custom_serialization_from_json_encoders(self._config_wrapper.json_encoders, source_type, schema) 1jmpgabknqhcdslorief

2323 

2324 def _apply_single_annotation( 1jmpgabknqhcdslorief

2325 self, 

2326 schema: core_schema.CoreSchema, 

2327 metadata: Any, 

2328 check_unsupported_field_info_attributes: bool = True, 

2329 ) -> core_schema.CoreSchema: 

2330 FieldInfo = import_cached_field_info() 1jmpgabknqhcdlorief

2331 

2332 if isinstance(metadata, FieldInfo): 1jmpgabknqhcdlorief

2333 if ( 1jgabkhcdlief

2334 check_unsupported_field_info_attributes 

2335 # HACK: we don't want to emit the warning for `FieldInfo` subclasses, because FastAPI does weird manipulations 

2336 # with its subclasses and their annotations: 

2337 and type(metadata) is FieldInfo 

2338 ): 

2339 for attr, value in self._get_unsupported_field_info_attributes(metadata): 1jmpgabknqhcdlorief

2340 warnings.warn( 1jmpgabknqhcdlorief

2341 f'The {attr!r} attribute with value {value!r} was provided to the `Field()` function, ' 

2342 f'which has no effect in the context it was used. {attr!r} is field-specific metadata, ' 

2343 'and can only be attached to a model field using `Annotated` metadata or by assignment. ' 

2344 'This may have happened because an `Annotated` type alias using the `type` statement was ' 

2345 'used, or if the `Field()` function was attached to a single member of a union type.', 

2346 category=UnsupportedFieldAttributeWarning, 

2347 ) 

2348 

2349 # Inside a model, a standalone `default_factory` is already reported as unsupported above: 

2350 if metadata.default_factory_takes_validated_data and self.model_type_stack.get() is None: 1jmpgabknqhcdlorief

2351 warnings.warn( 1jmpgabknqhcdlorief

2352 "A 'default_factory' taking validated data as an argument was provided to the `Field()` function, " 

2353 'but no validated data is available in the context it was used.', 

2354 category=UnsupportedFieldAttributeWarning, 

2355 ) 

2356 

2357 for field_metadata in metadata.metadata: 2357 ↛ 2358line 2357 didn't jump to line 2358 because the loop on line 2357 never started1jmpgabknqhcdlorief

2358 schema = self._apply_single_annotation(schema, field_metadata) 

2359 

2360 if metadata.discriminator is not None: 1jmpgabknqhcdlorief

2361 schema = self._apply_discriminator_to_union(schema, metadata.discriminator) 1jmpgabknqhcdlorief

2362 return schema 1jmpgabknqhcdlorief

2363 

2364 if schema['type'] == 'nullable': 1jmpgabknqhcdlorief

2365 # for nullable schemas, metadata is automatically applied to the inner schema 

2366 inner = schema.get('schema', core_schema.any_schema()) 1jmpgabknqhcdlorief

2367 inner = self._apply_single_annotation(inner, metadata) 1jmpgabknqhcdlorief

2368 if inner: 2368 ↛ 2370line 2368 didn't jump to line 2370 because the condition on line 2368 was always true1jmpgabknqhcdlorief

2369 schema['schema'] = inner 1jmpgabknqhcdlorief

2370 return schema 1jmpgabknqhcdlorief

2371 

2372 if schema['type'] == 'missing-sentinel' and (inner := schema.get('schema')) is not None: 1jmpgabknqhcdlorief

2373 # Same behavior as for nullable schemas: metadata is automatically applied to the inner schema 

2374 inner = self._apply_single_annotation(inner, metadata) 1jmpgabknqhcdlorief

2375 if inner: 2375 ↛ 2377line 2375 didn't jump to line 2377 because the condition on line 2375 was always true1jmpgabknqhcdlorief

2376 schema['schema'] = inner 1jmpgabknqhcdlorief

2377 return schema 1jmpgabknqhcdlorief

2378 

2379 original_schema = schema 1jmpgabknqhcdlorief

2380 ref = schema.get('ref') 1jmpgabknqhcdlorief

2381 if ref is not None: 2381 ↛ 2382line 2381 didn't jump to line 2382 because the condition on line 2381 was never true1jmpgabknqhcdlorief

2382 schema = schema.copy() 

2383 new_ref = ref + f'_{repr(metadata)}' 

2384 if (existing := self.defs.get_schema_from_ref(new_ref)) is not None: 

2385 return existing 

2386 schema['ref'] = new_ref # pyright: ignore[reportGeneralTypeIssues] 

2387 elif schema['type'] == 'definition-ref': 1jmpgabknqhcdlorief

2388 ref = schema['schema_ref'] 1jmpgabknqhcdlorief

2389 if (referenced_schema := self.defs.get_schema_from_ref(ref)) is not None: 2389 ↛ 2396line 2389 didn't jump to line 2396 because the condition on line 2389 was always true1jmpgabknqhcdlorief

2390 schema = referenced_schema.copy() 1jmpgabknqhcdlorief

2391 new_ref = ref + f'_{repr(metadata)}' 1jmpgabknqhcdlorief

2392 if (existing := self.defs.get_schema_from_ref(new_ref)) is not None: 1jmpgabknqhcdlorief

2393 return existing 1jmpgabknqhcdlorief

2394 schema['ref'] = new_ref # pyright: ignore[reportGeneralTypeIssues] 1jmpgabknqhcdlorief

2395 

2396 maybe_updated_schema = _known_annotated_metadata.apply_known_metadata(metadata, schema) 1jmpgabknqhcdlorief

2397 

2398 if maybe_updated_schema is not None: 1jmpgabknqhcdlorief

2399 return maybe_updated_schema 1jmpgabknqhcdlorief

2400 return original_schema 1jmpgabknqhcdlorief

2401 

2402 def _apply_single_annotation_json_schema( 1jmpgabknqhcdslorief

2403 self, schema: core_schema.CoreSchema, metadata: Any 

2404 ) -> core_schema.CoreSchema: 

2405 FieldInfo = import_cached_field_info() 1jmpgabknqhcdlorief

2406 

2407 if isinstance(metadata, FieldInfo): 1jmpgabknqhcdlorief

2408 for field_metadata in metadata.metadata: 2408 ↛ 2409line 2408 didn't jump to line 2409 because the loop on line 2408 never started1jmpgabknqhcdlorief

2409 schema = self._apply_single_annotation_json_schema(schema, field_metadata) 

2410 

2411 pydantic_js_updates, pydantic_js_extra = _extract_json_schema_info_from_field_info(metadata) 1jmpgabknqhcdlorief

2412 core_metadata = schema.setdefault('metadata', {}) 1jmpgabknqhcdlorief

2413 update_core_metadata( 1jmpgabknqhcdlorief

2414 core_metadata, pydantic_js_updates=pydantic_js_updates, pydantic_js_extra=pydantic_js_extra 

2415 ) 

2416 return schema 1jmpgabknqhcdlorief

2417 

2418 def _get_unsupported_field_info_attributes(self, field_info: FieldInfo) -> list[tuple[str, Any]]: 1jmpgabknqhcdslorief

2419 """Get the list of unsupported `FieldInfo` attributes when not directly used in `Annotated` for field annotations.""" 

2420 unused_metadata: list[tuple[str, Any]] = [] 1jmpgabknqhcdlorief

2421 for unused_metadata_name, unset_value in UNSUPPORTED_STANDALONE_FIELDINFO_ATTRIBUTES: 1jmpgabknqhcdlorief

2422 if ( 1gabhcdief

2423 (unused_metadata_value := getattr(field_info, unused_metadata_name)) is not unset_value 

2424 # `default` and `default_factory` can still be used with a type adapter, so only include them 

2425 # if used with a model-like class: 

2426 and ( 

2427 unused_metadata_name not in ('default', 'default_factory') 

2428 or self.model_type_stack.get() is not None 

2429 ) 

2430 # Setting `alias` will set `validation/serialization_alias` as well, so we want to avoid duplicate warnings: 

2431 and ( 

2432 unused_metadata_name not in ('validation_alias', 'serialization_alias') 

2433 or 'alias' not in field_info._attributes_set 

2434 ) 

2435 ): 

2436 unused_metadata.append((unused_metadata_name, unused_metadata_value)) 1jmpgabknqhcdlorief

2437 

2438 return unused_metadata 1jmpgabknqhcdlorief

2439 

2440 def _get_wrapped_inner_schema( 1jmpgabknqhcdslorief

2441 self, 

2442 get_inner_schema: GetCoreSchemaHandler, 

2443 annotation: Any, 

2444 pydantic_js_annotation_functions: list[GetJsonSchemaFunction], 

2445 check_unsupported_field_info_attributes: bool = False, 

2446 ) -> CallbackGetCoreSchemaHandler: 

2447 annotation_get_schema: GetCoreSchemaFunction | None = getattr(annotation, '__get_pydantic_core_schema__', None) 1jmpgabknqhcdslorief

2448 

2449 def new_handler(source: Any) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

2450 if annotation_get_schema is not None: 1jmpgabknqhcdslorief

2451 schema = annotation_get_schema(source, get_inner_schema) 1jmpgabknqhcdslorief

2452 else: 

2453 schema = get_inner_schema(source) 1jmpgabknqhcdlorief

2454 schema = self._apply_single_annotation( 1jmpgabknqhcdlorief

2455 schema, 

2456 annotation, 

2457 check_unsupported_field_info_attributes=check_unsupported_field_info_attributes, 

2458 ) 

2459 schema = self._apply_single_annotation_json_schema(schema, annotation) 1jmpgabknqhcdlorief

2460 

2461 metadata_js_function = _extract_get_pydantic_json_schema(annotation) 1jmpgabknqhcdslorief

2462 if metadata_js_function is not None: 1jmpgabknqhcdslorief

2463 pydantic_js_annotation_functions.append(metadata_js_function) 1jmpgabknqhcdlorief

2464 return schema 1jmpgabknqhcdslorief

2465 

2466 return CallbackGetCoreSchemaHandler(new_handler, self) 1jmpgabknqhcdslorief

2467 

2468 def _apply_field_serializers( 1jmpgabknqhcdslorief

2469 self, 

2470 schema: core_schema.CoreSchema, 

2471 serializers: list[Decorator[FieldSerializerDecoratorInfo]], 

2472 ) -> core_schema.CoreSchema: 

2473 """Apply field serializers to a schema.""" 

2474 if serializers: 1jmpgabknqhcdlorief

2475 schema = copy(schema) 1jmpgabknqhcdlorief

2476 if schema['type'] == 'definitions': 2476 ↛ 2477line 2476 didn't jump to line 2477 because the condition on line 2476 was never true1jmpgabknqhcdlorief

2477 inner_schema = schema['schema'] 

2478 schema['schema'] = self._apply_field_serializers(inner_schema, serializers) 

2479 return schema 

2480 elif 'ref' in schema: 1jmpgabknqhcdlorief

2481 schema = self.defs.create_definition_reference_schema(schema) 1jmpgabknqhcdlorief

2482 

2483 # use the last serializer to make it easy to override a serializer set on a parent model 

2484 serializer = serializers[-1] 1jmpgabknqhcdlorief

2485 is_field_serializer, info_arg = inspect_field_serializer(serializer.func, serializer.info.mode) 1jmpgabknqhcdlorief

2486 

2487 if serializer.info.return_type is not PydanticUndefined: 1jmpgabknqhcdlorief

2488 return_type = serializer.info.return_type 1jmpgabknqhcdlorief

2489 else: 

2490 try: 1jmpgabknqhcdlorief

2491 # Do not pass in globals as the function could be defined in a different module. 

2492 # Instead, let `get_callable_return_type` infer the globals to use, but still pass 

2493 # in locals that may contain a parent/rebuild namespace: 

2494 return_type = _decorators.get_callable_return_type( 1jmpgabknqhcdlorief

2495 serializer.func, localns=self._types_namespace.locals 

2496 ) 

2497 except NameError as e: 1jmpgabknqhcdlorief

2498 raise PydanticUndefinedAnnotation.from_name_error(e) from e 1jmpgabknqhcdlorief

2499 

2500 if return_type is PydanticUndefined: 1jmpgabknqhcdlorief

2501 return_schema = None 1jmpgabknqhcdlorief

2502 else: 

2503 return_schema = self.generate_schema(return_type) 1jmpgabknqhcdlorief

2504 

2505 if serializer.info.mode == 'wrap': 1jmpgabknqhcdlorief

2506 schema['serialization'] = core_schema.wrap_serializer_function_ser_schema( 1jmpgabknqhcdlorief

2507 serializer.func, 

2508 is_field_serializer=is_field_serializer, 

2509 info_arg=info_arg, 

2510 return_schema=return_schema, 

2511 when_used=serializer.info.when_used, 

2512 ) 

2513 else: 

2514 assert serializer.info.mode == 'plain' 1jmpgabknqhcdlorief

2515 schema['serialization'] = core_schema.plain_serializer_function_ser_schema( 1jmpgabknqhcdlorief

2516 serializer.func, 

2517 is_field_serializer=is_field_serializer, 

2518 info_arg=info_arg, 

2519 return_schema=return_schema, 

2520 when_used=serializer.info.when_used, 

2521 ) 

2522 return schema 1jmpgabknqhcdlorief

2523 

2524 def _apply_model_serializers( 1jmpgabknqhcdslorief

2525 self, schema: core_schema.CoreSchema, serializers: Iterable[Decorator[ModelSerializerDecoratorInfo]] 

2526 ) -> core_schema.CoreSchema: 

2527 """Apply model serializers to a schema.""" 

2528 ref: str | None = schema.pop('ref', None) # type: ignore 1jmpgabknqhcdslorief

2529 if serializers: 1jmpgabknqhcdslorief

2530 serializer = list(serializers)[-1] 1jmpgabknqhcdlorief

2531 info_arg = inspect_model_serializer(serializer.func, serializer.info.mode) 1jmpgabknqhcdlorief

2532 

2533 if serializer.info.return_type is not PydanticUndefined: 2533 ↛ 2534line 2533 didn't jump to line 2534 because the condition on line 2533 was never true1jmpgabknqhcdlorief

2534 return_type = serializer.info.return_type 

2535 else: 

2536 try: 1jmpgabknqhcdlorief

2537 # Do not pass in globals as the function could be defined in a different module. 

2538 # Instead, let `get_callable_return_type` infer the globals to use, but still pass 

2539 # in locals that may contain a parent/rebuild namespace: 

2540 return_type = _decorators.get_callable_return_type( 1jmpgabknqhcdlorief

2541 serializer.func, localns=self._types_namespace.locals 

2542 ) 

2543 except NameError as e: 

2544 raise PydanticUndefinedAnnotation.from_name_error(e) from e 

2545 

2546 if return_type is PydanticUndefined: 1jmpgabknqhcdlorief

2547 return_schema = None 1jmpgabknqhcdlorief

2548 else: 

2549 return_schema = self.generate_schema(return_type) 1jmpgabknqhcdlorief

2550 

2551 if serializer.info.mode == 'wrap': 1jmpgabknqhcdlorief

2552 ser_schema: core_schema.SerSchema = core_schema.wrap_serializer_function_ser_schema( 1jmpgabknqhcdlorief

2553 serializer.func, 

2554 info_arg=info_arg, 

2555 return_schema=return_schema, 

2556 when_used=serializer.info.when_used, 

2557 ) 

2558 else: 

2559 # plain 

2560 ser_schema = core_schema.plain_serializer_function_ser_schema( 1jmpgabknqhcdlorief

2561 serializer.func, 

2562 info_arg=info_arg, 

2563 return_schema=return_schema, 

2564 when_used=serializer.info.when_used, 

2565 ) 

2566 schema['serialization'] = ser_schema 1jmpgabknqhcdlorief

2567 if ref: 2567 ↛ 2569line 2567 didn't jump to line 2569 because the condition on line 2567 was always true1jmpgabknqhcdslorief

2568 schema['ref'] = ref # type: ignore 1jmpgabknqhcdslorief

2569 return schema 1jmpgabknqhcdslorief

2570 

2571 

2572def _convert_to_aliases( 1jmpgabknqhcdslorief

2573 alias: str | AliasChoices | AliasPath | None, 

2574) -> str | list[str | int] | list[list[str | int]] | None: 

2575 if isinstance(alias, (AliasChoices, AliasPath)): 1jmpgabknqhcdslorief

2576 return alias.convert_to_aliases() 1jmpgabknqhcdlorief

2577 else: 

2578 return alias 1jmpgabknqhcdslorief

2579 

2580 

2581def apply_model_validators( 1jmpgabknqhcdslorief

2582 schema: core_schema.CoreSchema, 

2583 validators: Iterable[Decorator[ModelValidatorDecoratorInfo]], 

2584 mode: Literal['inner', 'outer', 'all'], 

2585) -> core_schema.CoreSchema: 

2586 """Apply model validators to a schema. 

2587 

2588 If mode == 'inner', only "before" validators are applied 

2589 If mode == 'outer', validators other than "before" are applied 

2590 If mode == 'all', all validators are applied 

2591 

2592 Args: 

2593 schema: The schema to apply validators on. 

2594 validators: An iterable of validators. 

2595 mode: The validator mode. 

2596 

2597 Returns: 

2598 The updated schema. 

2599 """ 

2600 ref: str | None = schema.pop('ref', None) # type: ignore 1jmpgabknqhcdslorief

2601 for validator in validators: 1jmpgabknqhcdslorief

2602 if mode == 'inner' and validator.info.mode != 'before': 1jmpgabknqhcdlorief

2603 continue 1jmpgabknqhcdlorief

2604 if mode == 'outer' and validator.info.mode == 'before': 1jmpgabknqhcdlorief

2605 continue 1jmpgabknqhcdlorief

2606 info_arg = inspect_validator(validator.func, mode=validator.info.mode, type='model') 1jmpgabknqhcdlorief

2607 if validator.info.mode == 'wrap': 1jmpgabknqhcdlorief

2608 if info_arg: 1jmpgabknqhcdlorief

2609 schema = core_schema.with_info_wrap_validator_function(function=validator.func, schema=schema) 1jmpgabknqhcdlorief

2610 else: 

2611 schema = core_schema.no_info_wrap_validator_function(function=validator.func, schema=schema) 1jmpgabknqhcdlorief

2612 elif validator.info.mode == 'before': 1jmpgabknqhcdlorief

2613 if info_arg: 1jmpgabknqhcdlorief

2614 schema = core_schema.with_info_before_validator_function(function=validator.func, schema=schema) 1jmpgabknqhcdlorief

2615 else: 

2616 schema = core_schema.no_info_before_validator_function(function=validator.func, schema=schema) 1jmpgabknqhcdlorief

2617 else: 

2618 assert validator.info.mode == 'after' 1jmpgabknqhcdlorief

2619 if info_arg: 1jmpgabknqhcdlorief

2620 schema = core_schema.with_info_after_validator_function(function=validator.func, schema=schema) 1jmpgabknqhcdlorief

2621 else: 

2622 schema = core_schema.no_info_after_validator_function(function=validator.func, schema=schema) 1jmpgabknqhcdlorief

2623 if ref: 1jmpgabknqhcdslorief

2624 schema['ref'] = ref # type: ignore 1jmpgabknqhcdslorief

2625 return schema 1jmpgabknqhcdslorief

2626 

2627 

2628def wrap_default(field_info: FieldInfo, schema: core_schema.CoreSchema) -> core_schema.CoreSchema: 1jmpgabknqhcdslorief

2629 """Wrap schema with default schema if default value or `default_factory` are available. 

2630 

2631 Args: 

2632 field_info: The field info object. 

2633 schema: The schema to apply default on. 

2634 

2635 Returns: 

2636 Updated schema by default value or `default_factory`. 

2637 """ 

2638 if field_info.default_factory: 1jmpgabknqhcdslorief

2639 return core_schema.with_default_schema( 1jmpgabknqhcdslorief

2640 schema, 

2641 default_factory=field_info.default_factory, 

2642 default_factory_takes_data=takes_validated_data_argument(field_info.default_factory), 

2643 validate_default=field_info.validate_default, 

2644 ) 

2645 elif field_info.default is not PydanticUndefined: 1jmpgabknqhcdslorief

2646 return core_schema.with_default_schema( 1jmpgabknqhcdslorief

2647 schema, default=field_info.default, validate_default=field_info.validate_default 

2648 ) 

2649 else: 

2650 return schema 1jmpgabknqhcdlorief

2651 

2652 

2653def _extract_get_pydantic_json_schema(tp: Any) -> GetJsonSchemaFunction | None: 1jmpgabknqhcdslorief

2654 """Extract `__get_pydantic_json_schema__` from a type.""" 

2655 return getattr(tp, '__get_pydantic_json_schema__', None) 1jmpgabknqhcdslorief

2656 

2657 

2658def resolve_original_schema(schema: CoreSchema, definitions: _Definitions) -> CoreSchema | None: 1jmpgabknqhcdslorief

2659 if schema['type'] == 'definition-ref': 1jmpgabknqhcdslorief

2660 return definitions.get_schema_from_ref(schema['schema_ref']) 1jmpgabknqhcdslorief

2661 elif schema['type'] == 'definitions': 2661 ↛ 2662line 2661 didn't jump to line 2662 because the condition on line 2661 was never true1jmpgabknqhcdlorief

2662 return schema['schema'] 

2663 else: 

2664 return schema 1jmpgabknqhcdlorief

2665 

2666 

2667def _inlining_behavior( 1jmpgabknqhcdslorief

2668 def_ref: core_schema.DefinitionReferenceSchema, 

2669) -> Literal['inline', 'keep', 'preserve_metadata']: 

2670 """Determine the inlining behavior of the `'definition-ref'` schema. 

2671 

2672 - If no `'serialization'` schema and no metadata is attached, the schema can safely be inlined. 

2673 - If it has metadata but only related to the deferred discriminator application, it can be inlined 

2674 provided that such metadata is kept. 

2675 - Otherwise, the schema should not be inlined. Doing so would remove the `'serialization'` schema or metadata. 

2676 """ 

2677 if 'serialization' in def_ref: 1jmpgabknqhcdslorief

2678 return 'keep' 1jmpgabknqhcdlorief

2679 metadata = def_ref.get('metadata') 1jmpgabknqhcdslorief

2680 if not metadata: 1jmpgabknqhcdslorief

2681 return 'inline' 1jmpgabknqhcdslorief

2682 if len(metadata) == 1 and 'pydantic_internal_union_discriminator' in metadata: 2682 ↛ 2683line 2682 didn't jump to line 2683 because the condition on line 2682 was never true1jmpgabknqhcdlorief

2683 return 'preserve_metadata' 

2684 return 'keep' 1jmpgabknqhcdlorief

2685 

2686 

2687class _Definitions: 1jmpgabknqhcdslorief

2688 """Keeps track of references and definitions.""" 

2689 

2690 _recursively_seen: set[str] 1jmpgabknqhcdslorief

2691 """A set of recursively seen references. 1jmpgabknqhcdslorief

2692 

2693 When a referenceable type is encountered, the `get_schema_or_ref` context manager is 

2694 entered to compute the reference. If the type references itself by some way (e.g. for 

2695 a dataclass a Pydantic model, the class can be referenced as a field annotation), 

2696 entering the context manager again will yield a `'definition-ref'` schema that should 

2697 short-circuit the normal generation process, as the reference was already in this set. 

2698 """ 

2699 

2700 _definitions: dict[str, core_schema.CoreSchema] 1jmpgabknqhcdslorief

2701 """A mapping of references to their corresponding schema. 1jmpgabknqhcdslorief

2702 

2703 When a schema for a referenceable type is generated, it is stored in this mapping. If the 

2704 same type is encountered again, the reference is yielded by the `get_schema_or_ref` context 

2705 manager. 

2706 """ 

2707 

2708 def __init__(self) -> None: 1jmpgabknqhcdslorief

2709 self._recursively_seen = set() 1jmpgabknqhcdslorief

2710 self._definitions = {} 1jmpgabknqhcdslorief

2711 

2712 @contextmanager 1jmpgabknqhcdslorief

2713 def get_definition_ref_schema(self, *, ref: str) -> Generator[core_schema.DefinitionReferenceSchema | None]: 1jmpgabknqhcdslorief

2714 """Get a `'definition-ref'` schema for `ref`, if the reference was already encountered (or if we are in a cycle). 

2715 Get a definition for `tp` if one exists. 

2716 

2717 This should be called for any type that can be identified by reference. 

2718 This includes any recursive types. 

2719 

2720 At present the following types can be named/recursive: 

2721 

2722 - Pydantic model 

2723 - Pydantic and stdlib dataclasses 

2724 - Typed dictionaries 

2725 - Named tuples 

2726 - `TypeAliasType` instances 

2727 - Enums 

2728 """ 

2729 # return the reference if we're either (1) in a cycle or (2) it the reference was already encountered: 

2730 if ref in self._recursively_seen or ref in self._definitions: 1jmpgabknqhcdslorief

2731 yield core_schema.definition_reference_schema(ref) 1jmpgabknqhcdslorief

2732 else: 

2733 self._recursively_seen.add(ref) 1jmpgabknqhcdslorief

2734 try: 1jmpgabknqhcdslorief

2735 yield None 1jmpgabknqhcdslorief

2736 finally: 

2737 self._recursively_seen.discard(ref) 1jmpgabknqhcdslorief

2738 

2739 def get_schema_from_ref(self, ref: str) -> CoreSchema | None: 1jmpgabknqhcdslorief

2740 """Resolve the schema from the given reference.""" 

2741 return self._definitions.get(ref) 1jmpgabknqhcdslorief

2742 

2743 def create_definition_reference_schema(self, schema: CoreSchema) -> core_schema.DefinitionReferenceSchema: 1jmpgabknqhcdslorief

2744 """Store the schema as a definition and return a `'definition-reference'` schema pointing to it. 

2745 

2746 The schema must have a reference attached to it. 

2747 """ 

2748 ref = schema['ref'] # pyright: ignore 1jmpgabknqhcdslorief

2749 self._definitions[ref] = schema 1jmpgabknqhcdslorief

2750 return core_schema.definition_reference_schema(ref) 1jmpgabknqhcdslorief

2751 

2752 def unpack_definitions(self, schema: core_schema.DefinitionsSchema) -> CoreSchema: 1jmpgabknqhcdslorief

2753 """Store the definitions of the `'definitions'` core schema and return the inner core schema.""" 

2754 for def_schema in schema['definitions']: 1jmpgabknqhcdlorief

2755 self._definitions[def_schema['ref']] = def_schema # pyright: ignore 1jmpgabknqhcdlorief

2756 return schema['schema'] 1jmpgabknqhcdlorief

2757 

2758 def finalize_schema(self, schema: CoreSchema) -> CoreSchema: 1jmpgabknqhcdslorief

2759 """Finalize the core schema. 

2760 

2761 This traverses the core schema and referenced definitions, replaces `'definition-ref'` schemas 

2762 by the referenced definition if possible, and applies deferred discriminators. 

2763 """ 

2764 definitions = self._definitions 1jmpgabknqhcdslorief

2765 try: 1jmpgabknqhcdslorief

2766 gather_result = gather_schemas_for_cleaning( 1jmpgabknqhcdslorief

2767 schema, 

2768 definitions=definitions, 

2769 ) 

2770 except MissingDefinitionError as e: 1jmpgabknqhcdlorief

2771 raise InvalidSchemaError from e 1jmpgabknqhcdlorief

2772 

2773 remaining_defs: dict[str, CoreSchema] = {} 1jmpgabknqhcdslorief

2774 

2775 # References that will be kept as actual definitions (i.e. not inlined). When resolving an 

2776 # "intermediate" `'definition-ref'` schema (see `_resolve_definition()`), we must not follow 

2777 # the reference chain through one of these definitions: 

2778 kept_refs = { 1jmpgabknqhcdslorief

2779 ref 

2780 for ref, inlinable_def_ref in gather_result['collected_references'].items() 

2781 if inlinable_def_ref is None or _inlining_behavior(inlinable_def_ref) == 'keep' 

2782 } 

2783 

2784 # Note: this logic doesn't play well when core schemas with deferred discriminator metadata 

2785 # and references are encountered. See the `test_deferred_discriminated_union_and_references()` test. 

2786 for ref, inlinable_def_ref in gather_result['collected_references'].items(): 1jmpgabknqhcdslorief

2787 if inlinable_def_ref is not None and (inlining_behavior := _inlining_behavior(inlinable_def_ref)) != 'keep': 1jmpgabknqhcdslorief

2788 if inlining_behavior == 'inline': 2788 ↛ 2795line 2788 didn't jump to line 2795 because the condition on line 2788 was always true1jmpgabknqhcdslorief

2789 # `ref` was encountered, and only once: 

2790 # - `inlinable_def_ref` is a `'definition-ref'` schema and is guaranteed to be 

2791 # the only one. Transform it into the definition it points to. 

2792 # - Do not store the definition in the `remaining_defs`. 

2793 inlinable_def_ref.clear() # pyright: ignore[reportAttributeAccessIssue] 1jmpgabknqhcdslorief

2794 inlinable_def_ref.update(self._resolve_definition(ref, definitions, kept_refs)) # pyright: ignore 1jmpgabknqhcdslorief

2795 elif inlining_behavior == 'preserve_metadata': 

2796 # `ref` was encountered, and only once, but contains discriminator metadata. 

2797 # We will do the same thing as if `inlining_behavior` was `'inline'`, but make 

2798 # sure to keep the metadata for the deferred discriminator application logic below. 

2799 meta = inlinable_def_ref.pop('metadata') 

2800 inlinable_def_ref.clear() # pyright: ignore[reportAttributeAccessIssue] 

2801 inlinable_def_ref.update(self._resolve_definition(ref, definitions, kept_refs)) # pyright: ignore 

2802 inlinable_def_ref['metadata'] = meta 

2803 else: 

2804 # `ref` was encountered, at least two times (or only once, but with metadata or a serialization schema): 

2805 # - Do not inline the `'definition-ref'` schemas (they are not provided in the gather result anyway). 

2806 # - Store the definition in the `remaining_defs` 

2807 remaining_defs[ref] = self._resolve_definition(ref, definitions, kept_refs) 1jmpgabknqhcdslorief

2808 

2809 for cs in gather_result['deferred_discriminator_schemas']: 1jmpgabknqhcdslorief

2810 discriminator: str | None = cs['metadata'].pop('pydantic_internal_union_discriminator', None) # pyright: ignore[reportTypedDictNotRequiredAccess] 1jmpgabknqhcdlorief

2811 if discriminator is None: 2811 ↛ 2815line 2811 didn't jump to line 2815 because the condition on line 2811 was never true1jmpgabknqhcdlorief

2812 # This can happen in rare scenarios, when a deferred schema is present multiple times in the 

2813 # gather result (e.g. when using the `Sequence` type -- see `test_sequence_discriminated_union()`). 

2814 # In this case, a previous loop iteration applied the discriminator and so we can just skip it here. 

2815 continue 

2816 applied = _discriminated_union.apply_discriminator(cs.copy(), discriminator, remaining_defs) 1jmpgabknqhcdlorief

2817 # Mutate the schema directly to have the discriminator applied 

2818 cs.clear() # pyright: ignore[reportAttributeAccessIssue] 1jmpgabknqhcdlorief

2819 cs.update(applied) # pyright: ignore 1jmpgabknqhcdlorief

2820 

2821 if remaining_defs: 1jmpgabknqhcdslorief

2822 schema = core_schema.definitions_schema(schema=schema, definitions=[*remaining_defs.values()]) 1jmpgabknqhcdslorief

2823 return schema 1jmpgabknqhcdslorief

2824 

2825 def _resolve_definition(self, ref: str, definitions: dict[str, CoreSchema], kept_refs: set[str]) -> CoreSchema: 1jmpgabknqhcdslorief

2826 definition = definitions[ref] 1jmpgabknqhcdslorief

2827 if definition['type'] != 'definition-ref': 1jmpgabknqhcdslorief

2828 return definition 1jmpgabknqhcdslorief

2829 

2830 # Some `'definition-ref'` schemas might act as "intermediate" references (e.g. when using 

2831 # a PEP 695 type alias (which is referenceable) that references another PEP 695 type alias): 

2832 visited: set[str] = set() 1jmpgabknqhcdlorief

2833 while definition['type'] == 'definition-ref' and _inlining_behavior(definition) == 'inline': 1jmpgabknqhcdlorief

2834 schema_ref = definition['schema_ref'] 1jmpgabknqhcdlorief

2835 if schema_ref in kept_refs and schema_ref != ref: 1jmpgabknqhcdlorief

2836 # The reference chain leads to a *different* definition that is kept on its own (e.g. a 

2837 # recursive model referenced through a PEP 695 type alias). Resolve to a reference 

2838 # pointing to it instead of following the chain and inlining a copy of that definition, 

2839 # which could otherwise introduce a reference cycle in the resulting schema. 

2840 # Note: when `schema_ref == ref`, the reference points back to itself, which is a genuine 

2841 # circular reference and is reported as an error by the `visited` logic below. 

2842 return {**definition, 'ref': ref} 1jmpgabknqhcdlorief

2843 if schema_ref in visited: 1jmpgabknqhcdlorief

2844 raise PydanticUserError( 1jmpgabknqhcdlorief

2845 f'{ref} contains a circular reference to itself.', code='circular-reference-schema' 

2846 ) 

2847 visited.add(schema_ref) 1jmpgabknqhcdlorief

2848 definition = definitions[schema_ref] 1jmpgabknqhcdlorief

2849 return {**definition, 'ref': ref} # pyright: ignore[reportReturnType] 1jmpgabknqhcdlorief

2850 

2851 

2852class _FieldNameStack: 1jmpgabknqhcdslorief

2853 __slots__ = ('_stack',) 1jmpgabknqhcdslorief

2854 

2855 def __init__(self) -> None: 1jmpgabknqhcdslorief

2856 self._stack: list[str] = [] 1jmpgabknqhcdslorief

2857 

2858 @contextmanager 1jmpgabknqhcdslorief

2859 def push(self, field_name: str) -> Iterator[None]: 1jmpgabknqhcdslorief

2860 self._stack.append(field_name) 1jmpgabknqhcdslorief

2861 try: 1jmpgabknqhcdslorief

2862 yield 1jmpgabknqhcdslorief

2863 finally: 

2864 self._stack.pop() 1jmpgabknqhcdslorief

2865 

2866 def get(self) -> str | None: 1jmpgabknqhcdslorief

2867 if self._stack: 1jmpgabknqhcdlorief

2868 return self._stack[-1] 1jmpgabknqhcdlorief

2869 else: 

2870 return None 1jmpgabknqhcdlorief

2871 

2872 

2873class _ModelTypeStack: 1jmpgabknqhcdslorief

2874 __slots__ = ('_stack',) 1jmpgabknqhcdslorief

2875 

2876 def __init__(self) -> None: 1jmpgabknqhcdslorief

2877 self._stack: list[type] = [] 1jmpgabknqhcdslorief

2878 

2879 @contextmanager 1jmpgabknqhcdslorief

2880 def push(self, type_obj: type) -> Iterator[None]: 1jmpgabknqhcdslorief

2881 self._stack.append(type_obj) 1jmpgabknqhcdslorief

2882 try: 1jmpgabknqhcdslorief

2883 yield 1jmpgabknqhcdslorief

2884 finally: 

2885 self._stack.pop() 1jmpgabknqhcdslorief

2886 

2887 def get(self) -> type | None: 1jmpgabknqhcdslorief

2888 if self._stack: 1jmpgabknqhcdlorief

2889 return self._stack[-1] 1jmpgabknqhcdlorief

2890 else: 

2891 return None 1jmpgabknqhcdlorief