Coverage for pydantic / _internal / _generics.py: 93.62%

237 statements  

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

1from __future__ import annotations 1abghijcdklmnsefopqr

2 

3import operator 1abghijcdklmnsefopqr

4import sys 1abghijcdklmnsefopqr

5import types 1abghijcdklmnsefopqr

6import typing 1abghijcdklmnsefopqr

7from collections import ChainMap 1abghijcdklmnsefopqr

8from collections.abc import Generator, Mapping 1abghijcdklmnsefopqr

9from contextvars import ContextVar 1abghijcdklmnsefopqr

10from functools import reduce 1abghijcdklmnsefopqr

11from itertools import zip_longest 1abghijcdklmnsefopqr

12from types import prepare_class 1abghijcdklmnsefopqr

13from typing import TYPE_CHECKING, Annotated, Any, TypedDict, TypeVar, cast 1abghijcdklmnsefopqr

14from weakref import WeakValueDictionary 1abghijcdklmnsefopqr

15 

16import typing_extensions 1abghijcdklmnsefopqr

17from typing_inspection import typing_objects 1abghijcdklmnsefopqr

18from typing_inspection.introspection import is_union_origin 1abghijcdklmnsefopqr

19 

20from . import _type_refs, _typing_extra 1abghijcdklmnsefopqr

21from ._contextlib import contextmanager 1abghijcdklmnsefopqr

22from ._forward_ref import PydanticRecursiveRef 1abghijcdklmnsefopqr

23from ._utils import all_identical, is_model_class 1abghijcdklmnsefopqr

24 

25if TYPE_CHECKING: 1abghijcdklmnsefopqr

26 from ..main import BaseModel 

27 

28GenericTypesCacheKey = tuple[Any, Any, tuple[Any, ...]] 1abghijcdklmnsefopqr

29 

30# Note: We want to remove LimitedDict, but to do this, we'd need to improve the handling of generics caching. 

31# Right now, to handle recursive generics, we some types must remain cached for brief periods without references. 

32# By chaining the WeakValuesDict with a LimitedDict, we have a way to retain caching for all types with references, 

33# while also retaining a limited number of types even without references. This is generally enough to build 

34# specific recursive generic models without losing required items out of the cache. 

35 

36KT = TypeVar('KT') 1abghijcdklmnsefopqr

37VT = TypeVar('VT') 1abghijcdklmnsefopqr

38_LIMITED_DICT_SIZE = 100 1abghijcdklmnsefopqr

39 

40 

41class LimitedDict(dict[KT, VT]): 1abghijcdklmnsefopqr

42 def __init__(self, size_limit: int = _LIMITED_DICT_SIZE) -> None: 1abghijcdklmnsefopqr

43 self.size_limit = size_limit 1abghijcdklmnefopqr

44 super().__init__() 1abghijcdklmnefopqr

45 

46 def __setitem__(self, key: KT, value: VT, /) -> None: 1abghijcdklmnsefopqr

47 super().__setitem__(key, value) 1abghijcdklmnefopqr

48 if len(self) > self.size_limit: 1abghijcdklmnefopqr

49 excess = len(self) - self.size_limit + self.size_limit // 10 1abghijcdklmnefopqr

50 to_remove = list(self.keys())[:excess] 1abghijcdklmnefopqr

51 for k in to_remove: 1abghijcdklmnefopqr

52 del self[k] 1abghijcdklmnefopqr

53 

54 

55# weak dictionaries allow the dynamically created parametrized versions of generic models to get collected 

56# once they are no longer referenced by the caller. 

57GenericTypesCache = WeakValueDictionary[GenericTypesCacheKey, 'type[BaseModel]'] 1abghijcdklmnsefopqr

58 

59if TYPE_CHECKING: 1abghijcdklmnsefopqr

60 

61 class DeepChainMap(ChainMap[KT, VT]): # type: ignore 

62 ... 

63 

64else: 

65 

66 class DeepChainMap(ChainMap): 1abghijcdklmnsefopqr

67 """Variant of ChainMap that allows direct updates to inner scopes. 

68 

69 Taken from https://docs.python.org/3/library/collections.html#collections.ChainMap, 

70 with some light modifications for this use case. 

71 """ 

72 

73 def clear(self) -> None: 1abghijcdklmnsefopqr

74 for mapping in self.maps: 

75 mapping.clear() 

76 

77 def __setitem__(self, key: KT, value: VT) -> None: 1abghijcdklmnsefopqr

78 for mapping in self.maps: 

79 mapping[key] = value 

80 

81 def __delitem__(self, key: KT) -> None: 1abghijcdklmnsefopqr

82 hit = False 

83 for mapping in self.maps: 

84 if key in mapping: 

85 del mapping[key] 

86 hit = True 

87 if not hit: 

88 raise KeyError(key) 

89 

90 

91# Despite the fact that LimitedDict _seems_ no longer necessary, I'm very nervous to actually remove it 

92# and discover later on that we need to re-add all this infrastructure... 

93# _GENERIC_TYPES_CACHE = DeepChainMap(GenericTypesCache(), LimitedDict()) 

94 

95_GENERIC_TYPES_CACHE = GenericTypesCache() 1abghijcdklmnsefopqr

96 

97 

98class PydanticGenericMetadata(TypedDict): 1abghijcdklmnsefopqr

99 origin: type[BaseModel] | None # analogous to typing._GenericAlias.__origin__ 1abghijcdklmnsefopqr

100 args: tuple[Any, ...] # analogous to typing._GenericAlias.__args__ 1abghijcdklmnsefopqr

101 parameters: tuple[TypeVar, ...] # analogous to typing.Generic.__parameters__ 1abghijcdklmnsefopqr

102 

103 

104def create_generic_submodel( 1abghijcdklmnsefopqr

105 model_name: str, origin: type[BaseModel], args: tuple[Any, ...], params: tuple[Any, ...] 

106) -> type[BaseModel]: 

107 """Dynamically create a submodel of a provided (generic) BaseModel. 

108 

109 This is used when producing concrete parametrizations of generic models. This function 

110 only *creates* the new subclass; the schema/validators/serialization must be updated to 

111 reflect a concrete parametrization elsewhere. 

112 

113 Args: 

114 model_name: The name of the newly created model. 

115 origin: The base class for the new model to inherit from. 

116 args: A tuple of generic metadata arguments. 

117 params: A tuple of generic metadata parameters. 

118 

119 Returns: 

120 The created submodel. 

121 """ 

122 model_module, called_globally = _get_caller_frame_info(depth=3) 1abghijcdklmnsefopqr

123 # If parametrized at the module level, the parametrized class is registered in this module (see below). 

124 # Its `__module__` must match. We fall back to the module of the origin for backwards compatibility reasons. 

125 module = model_module if called_globally and model_module is not None else origin.__module__ 1abghijcdklmnsefopqr

126 namespace: dict[str, Any] = {'__module__': module} 1abghijcdklmnsefopqr

127 # As per https://docs.python.org/3/reference/datamodel.html#slots: 

128 # "The action of a __slots__ declaration is not limited to the class where it is defined. 

129 # __slots__ declared in parents are available in child classes. However, instances of a 

130 # child subclass will get a __dict__ and __weakref__ unless the subclass also defines 

131 # __slots__". 

132 # Because when users parameterize a generic model, we create a subclass of such generic model 

133 # (what happens in this function), they can't control the fact that no slots is defined on the 

134 # dynamic subclass, and so even if they defined extra __slots__ on the generic class (which results 

135 # in the class *not* being weakref-able), the parameterized class *will* be weakref-able. 

136 # For this reason (and to make Pydantic generic models behavior closer to generic aliases), 

137 # we forward any slots from the origin: 

138 if '__slots__' in origin.__dict__: 1abghijcdklmnsefopqr

139 namespace['__slots__'] = origin.__dict__['__slots__'] 1abghijcdklmnefopqr

140 bases = (origin,) 1abghijcdklmnsefopqr

141 meta, ns, kwds = prepare_class(model_name, bases) 1abghijcdklmnsefopqr

142 namespace.update(ns) 1abghijcdklmnsefopqr

143 created_model = meta( 1abghijcdklmnsefopqr

144 model_name, 

145 bases, 

146 namespace, 

147 __pydantic_generic_metadata__={ 

148 'origin': origin, 

149 'args': args, 

150 'parameters': params, 

151 }, 

152 __pydantic_reset_parent_namespace__=False, 

153 **kwds, 

154 ) 

155 

156 if called_globally: # create global reference and therefore allow pickling 1abghijcdklmnsefopqr

157 object_by_reference = None 1abghijcdklmnsefopqr

158 reference_name = model_name 1abghijcdklmnsefopqr

159 reference_module_globals = sys.modules[module].__dict__ 1abghijcdklmnsefopqr

160 while object_by_reference is not created_model: 1abghijcdklmnsefopqr

161 object_by_reference = reference_module_globals.setdefault(reference_name, created_model) 1abghijcdklmnsefopqr

162 reference_name += '_' 1abghijcdklmnsefopqr

163 

164 return created_model 1abghijcdklmnsefopqr

165 

166 

167def _get_caller_frame_info(depth: int = 2) -> tuple[str | None, bool]: 1abghijcdklmnsefopqr

168 """Used inside a function to check whether it was called globally. 

169 

170 Args: 

171 depth: The depth to get the frame. 

172 

173 Returns: 

174 A tuple contains `module_name` and `called_globally`. 

175 

176 Raises: 

177 RuntimeError: If the function is not called inside a function. 

178 """ 

179 try: 1abghijcdklmnsefopqr

180 previous_caller_frame = sys._getframe(depth) 1abghijcdklmnsefopqr

181 except ValueError as e: 1abghijcdklmnefopqr

182 raise RuntimeError('This function must be used inside another function') from e 1abghijcdklmnefopqr

183 except AttributeError: # sys module does not have _getframe function, so there's nothing we can do about it 1abghijcdklmnefopqr

184 return None, False 1abghijcdklmnefopqr

185 frame_globals = previous_caller_frame.f_globals 1abghijcdklmnsefopqr

186 return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals 1abghijcdklmnsefopqr

187 

188 

189DictValues: type[Any] = {}.values().__class__ 1abghijcdklmnsefopqr

190 

191 

192def iter_contained_typevars(v: Any) -> Generator[TypeVar]: 1abghijcdklmnsefopqr

193 """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found. 

194 

195 This is inspired as an alternative to directly accessing the `__parameters__` attribute of a GenericAlias, 

196 since __parameters__ of (nested) generic BaseModel subclasses won't show up in that list. 

197 """ 

198 if isinstance(v, TypeVar): 1abghijcdklmnsefopqr

199 yield v 1abghijcdklmnefopqr

200 elif is_model_class(v): 1abghijcdklmnsefopqr

201 yield from v.__pydantic_generic_metadata__['parameters'] 1abghijcdklmnsefopqr

202 elif isinstance(v, (DictValues, list)): 1abghijcdklmnsefopqr

203 for var in v: 1abghijcdklmnsefopqr

204 yield from iter_contained_typevars(var) 1abghijcdklmnsefopqr

205 else: 

206 args = get_args(v) 1abghijcdklmnsefopqr

207 for arg in args: 1abghijcdklmnsefopqr

208 yield from iter_contained_typevars(arg) 1abghijcdklmnefopqr

209 

210 

211def get_args(v: Any) -> Any: 1abghijcdklmnsefopqr

212 pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None) 1abghijcdklmnsefopqr

213 if pydantic_generic_metadata: 1abghijcdklmnsefopqr

214 return pydantic_generic_metadata.get('args') 1abghijcdklmnefopqr

215 return typing_extensions.get_args(v) 1abghijcdklmnsefopqr

216 

217 

218def get_origin(v: Any) -> Any: 1abghijcdklmnsefopqr

219 pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None) 1abghijcdklmnsefopqr

220 if pydantic_generic_metadata: 1abghijcdklmnsefopqr

221 return pydantic_generic_metadata.get('origin') 1abghijcdklmnefopqr

222 return typing_extensions.get_origin(v) 1abghijcdklmnsefopqr

223 

224 

225def _map_type_parameters(target: Any, parameters: tuple[Any, ...], args: tuple[Any, ...]) -> dict[TypeVar, Any]: 1abghijcdklmnsefopqr

226 """Return a mapping between the type parameters of `target` and the provided arguments. 

227 

228 Missing arguments are filled with the parameter's default (if any). 

229 

230 Raises: 

231 TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments). 

232 

233 Note: 

234 This function is analogous to the private `typing._check_generic_specialization` function. 

235 """ 

236 expected_len = len(parameters) 1abghijcdklmnsefopqr

237 typevars_map: dict[TypeVar, Any] = {} 1abghijcdklmnsefopqr

238 

239 _MISSING = typing_extensions.Sentinel('_MISSING') 1abghijcdklmnsefopqr

240 for parameter, argument in zip_longest(parameters, args, fillvalue=_MISSING): 1abghijcdklmnsefopqr

241 if parameter is _MISSING: 1abghijcdklmnsefopqr

242 raise TypeError(f'Too many arguments for {target}; actual {len(args)}, expected {expected_len}') 1abghijcdklmnefopqr

243 

244 if argument is _MISSING: 1abghijcdklmnsefopqr

245 param = cast(TypeVar, parameter) 1abghijcdklmnefopqr

246 try: 1abghijcdklmnefopqr

247 has_default = param.has_default() # pyright: ignore[reportAttributeAccessIssue] 1abghijcdklmnefopqr

248 except AttributeError: 1abcdef

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

250 has_default = False 1abcdef

251 if has_default: 1abghijcdklmnefopqr

252 # The default might refer to other type parameters. For an example, see: 

253 # https://typing.python.org/en/latest/spec/generics.html#type-parameters-as-parameters-to-generics 

254 typevars_map[param] = replace_types(param.__default__, typevars_map) # pyright: ignore[reportAttributeAccessIssue] 1abghijcdklmnefopqr

255 else: 

256 expected_len -= sum(hasattr(p, 'has_default') and p.has_default() for p in parameters) # pyright: ignore[reportAttributeAccessIssue] 1abghijcdklmnefopqr

257 raise TypeError(f'Too few arguments for {target}; actual {len(args)}, expected at least {expected_len}') 1abghijcdklmnefopqr

258 else: 

259 param = cast(TypeVar, parameter) 1abghijcdklmnsefopqr

260 typevars_map[param] = argument 1abghijcdklmnsefopqr

261 

262 return typevars_map 1abghijcdklmnsefopqr

263 

264 

265def get_standard_typevars_map(cls: Any) -> dict[TypeVar, Any] | None: 1abghijcdklmnsefopqr

266 """Package a generic type's typevars and parametrization (if present) into a dictionary compatible with the 

267 `replace_types` function. Specifically, this works with standard typing generics and typing._GenericAlias. 

268 """ 

269 origin = get_origin(cls) 1abghijcdklmnsefopqr

270 if origin is None: 1abghijcdklmnsefopqr

271 return None 1abghijcdklmnsefopqr

272 if not hasattr(origin, '__parameters__'): 1abghijcdklmnefopqr

273 return None 1abghijcdklmnefopqr

274 

275 # In this case, we know that cls is a _GenericAlias, and origin is the generic type 

276 # So it is safe to access cls.__args__ and origin.__parameters__ 

277 args: tuple[Any, ...] = cls.__args__ # type: ignore 1abghijcdklmnefopqr

278 parameters: tuple[TypeVar, ...] = origin.__parameters__ 1abghijcdklmnefopqr

279 # Type parameter defaults are not always applied to `__args__` (e.g. for type aliases 

280 # created with the `type` statement), so missing arguments are filled from the defaults: 

281 return _map_type_parameters(origin, parameters, args) 1abghijcdklmnefopqr

282 

283 

284def get_model_typevars_map(cls: type[BaseModel]) -> dict[TypeVar, Any]: 1abghijcdklmnsefopqr

285 """Package a generic BaseModel's typevars and concrete parametrization (if present) into a dictionary compatible 

286 with the `replace_types` function. 

287 

288 Since BaseModel.__class_getitem__ does not produce a typing._GenericAlias, and the BaseModel generic info is 

289 stored in the __pydantic_generic_metadata__ attribute, we need special handling here. 

290 """ 

291 # TODO: This could be unified with `get_standard_typevars_map` if we stored the generic metadata 

292 # in the __origin__, __args__, and __parameters__ attributes of the model. 

293 generic_metadata = cls.__pydantic_generic_metadata__ 1abghijcdklmnsefopqr

294 origin = generic_metadata['origin'] 1abghijcdklmnsefopqr

295 args = generic_metadata['args'] 1abghijcdklmnsefopqr

296 if not args: 1abghijcdklmnsefopqr

297 # No need to go into `iter_contained_typevars`: 

298 return {} 1abghijcdklmnsefopqr

299 return dict(zip(iter_contained_typevars(origin), args, strict=True)) 1abghijcdklmnsefopqr

300 

301 

302def replace_types(type_: Any, type_map: Mapping[TypeVar, Any] | None) -> Any: 1abghijcdklmnsefopqr

303 """Return type with all occurrences of `type_map` keys recursively replaced with their values. 

304 

305 Args: 

306 type_: The class or generic alias. 

307 type_map: Mapping from `TypeVar` instance to concrete types. 

308 

309 Returns: 

310 A new type representing the basic structure of `type_` with all 

311 `typevar_map` keys recursively replaced. 

312 

313 Example: 

314 ```python 

315 from pydantic._internal._generics import replace_types 

316 

317 replace_types(tuple[str, list[str] | float], {str: int}) 

318 #> tuple[int, list[int] | float] 

319 ``` 

320 """ 

321 if not type_map: 1abghijcdklmnsefopqr

322 return type_ 1abghijcdklmnsefopqr

323 

324 type_args = get_args(type_) 1abghijcdklmnsefopqr

325 origin_type = get_origin(type_) 1abghijcdklmnsefopqr

326 

327 if typing_objects.is_annotated(origin_type): 1abghijcdklmnsefopqr

328 annotated_type, *annotations = type_args 1abghijcdklmnefopqr

329 annotated_type = replace_types(annotated_type, type_map) 1abghijcdklmnefopqr

330 return Annotated[annotated_type, *annotations] 1abghijcdklmnefopqr

331 

332 # Having type args is a good indicator that this is a typing special form 

333 # instance or a generic alias of some sort. 

334 if type_args: 1abghijcdklmnsefopqr

335 resolved_type_args = tuple(replace_types(arg, type_map) for arg in type_args) 1abghijcdklmnsefopqr

336 if all_identical(type_args, resolved_type_args): 1abghijcdklmnsefopqr

337 # If all arguments are the same, there is no need to modify the 

338 # type or create a new object at all 

339 return type_ 1abghijcdklmnsefopqr

340 

341 if ( 1hijlmnpqr

342 origin_type is not None 

343 and isinstance(type_, _typing_extra.typing_base) 

344 and not isinstance(origin_type, _typing_extra.typing_base) 

345 and getattr(type_, '_name', None) is not None 

346 ): 

347 # In python < 3.9 generic aliases don't exist so any of these like `list`, 

348 # `type` or `collections.abc.Callable` need to be translated. 

349 # See: https://www.python.org/dev/peps/pep-0585 

350 origin_type = getattr(typing, type_._name) 1abghijcdklmnefopqr

351 assert origin_type is not None 1abghijcdklmnefopqr

352 

353 if is_union_origin(origin_type): 1abghijcdklmnefopqr

354 if any(typing_objects.is_any(arg) for arg in resolved_type_args): 1abghijcdklmnefopqr

355 # `Any | T` ~ `Any`: 

356 resolved_type_args = (Any,) 1abghijcdklmnefopqr

357 # `Never | T` ~ `T`: 

358 resolved_type_args = tuple( 1abghijcdklmnefopqr

359 arg 

360 for arg in resolved_type_args 

361 if not (typing_objects.is_noreturn(arg) or typing_objects.is_never(arg)) 

362 ) 

363 

364 # PEP-604 syntax (e.g. `list | str`) is represented with a types.UnionType object that does not 

365 # implement `__getitem__()`. In Python 3.14+, `typing.Union` and `types.UnionType` are the same, 

366 # and we instead rely on `typing.Union` as it implicitly converts string annotations to `ForwardRef` 

367 # instances (this is to avoid type errors as per https://github.com/python/cpython/pull/105366). 

368 if sys.version_info < (3, 14) and origin_type is types.UnionType: 1abghijcdklmnefopqr

369 return reduce(operator.or_, resolved_type_args) 1abgcdkefo

370 # NotRequired[T] and Required[T] don't support tuple type resolved_type_args, hence the condition below 

371 return origin_type[resolved_type_args[0] if len(resolved_type_args) == 1 else resolved_type_args] 1abghijcdklmnefopqr

372 

373 # We handle pydantic generic models separately as they don't have the same 

374 # semantics as "typing" classes or generic aliases 

375 

376 if not origin_type and is_model_class(type_): 1abghijcdklmnsefopqr

377 parameters = type_.__pydantic_generic_metadata__['parameters'] 1abghijcdklmnefopqr

378 if not parameters: 1abghijcdklmnefopqr

379 return type_ 1abghijcdklmnefopqr

380 resolved_type_args = tuple(replace_types(t, type_map) for t in parameters) 1abghijcdklmnefopqr

381 if all_identical(parameters, resolved_type_args): 1abghijcdklmnefopqr

382 return type_ 1abghijcdklmnefopqr

383 return type_[resolved_type_args] 1abghijcdklmnefopqr

384 

385 # Handle special case for typehints that can have lists as arguments. 

386 # `typing.Callable[[int, str], int]` is an example for this. 

387 if isinstance(type_, list): 1abghijcdklmnsefopqr

388 resolved_list = [replace_types(element, type_map) for element in type_] 1abghijcdklmnefopqr

389 if all_identical(type_, resolved_list): 1abghijcdklmnefopqr

390 return type_ 1abghijcdklmnefopqr

391 return resolved_list 1abghijcdklmnefopqr

392 

393 # If all else fails, we try to resolve the type directly and otherwise just 

394 # return the input with no modifications. 

395 return type_map.get(type_, type_) 1abghijcdklmnsefopqr

396 

397 

398def map_generic_model_arguments(cls: type[BaseModel], args: tuple[Any, ...]) -> dict[TypeVar, Any]: 1abghijcdklmnsefopqr

399 """Return a mapping between the parameters of a generic model and the provided arguments during parameterization. 

400 

401 Raises: 

402 TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments). 

403 

404 Example: 

405 ```python {test="skip" lint="skip"} 

406 class Model[T, U, V = int](BaseModel): ... 

407 

408 map_generic_model_arguments(Model, (str, bytes)) 

409 #> {T: str, U: bytes, V: int} 

410 

411 map_generic_model_arguments(Model, (str,)) 

412 #> TypeError: Too few arguments for <class '__main__.Model'>; actual 1, expected at least 2 

413 

414 map_generic_model_arguments(Model, (str, bytes, int, complex)) 

415 #> TypeError: Too many arguments for <class '__main__.Model'>; actual 4, expected 3 

416 ``` 

417 

418 Note: 

419 This function is analogous to the private `typing._check_generic_specialization` function. 

420 """ 

421 parameters = cls.__pydantic_generic_metadata__['parameters'] 1abghijcdklmnsefopqr

422 return _map_type_parameters(cls, parameters, args) 1abghijcdklmnsefopqr

423 

424 

425_generic_recursion_cache: ContextVar[set[str] | None] = ContextVar('_generic_recursion_cache', default=None) 1abghijcdklmnsefopqr

426 

427 

428@contextmanager 1abghijcdklmnsefopqr

429def generic_recursion_self_type( 1abghijcdklmnsefopqr

430 origin: type[BaseModel], args: tuple[Any, ...] 

431) -> Generator[PydanticRecursiveRef | None]: 

432 """This contextmanager should be placed around the recursive calls used to build a generic type, 

433 and accept as arguments the generic origin type and the type arguments being passed to it. 

434 

435 If the same origin and arguments are observed twice, it implies that a self-reference placeholder 

436 can be used while building the core schema, and will produce a schema_ref that will be valid in the 

437 final parent schema. 

438 """ 

439 previously_seen_type_refs = _generic_recursion_cache.get() 1abghijcdklmnsefopqr

440 if previously_seen_type_refs is None: 1abghijcdklmnsefopqr

441 previously_seen_type_refs = set() 1abghijcdklmnsefopqr

442 token = _generic_recursion_cache.set(previously_seen_type_refs) 1abghijcdklmnsefopqr

443 else: 

444 token = None 1abghijcdklmnefopqr

445 

446 try: 1abghijcdklmnsefopqr

447 type_ref = _type_refs.model_type_ref(origin, args_override=args) 1abghijcdklmnsefopqr

448 if type_ref in previously_seen_type_refs: 1abghijcdklmnsefopqr

449 self_type = PydanticRecursiveRef(type_ref=type_ref) 1abghijcdklmnefopqr

450 yield self_type 1abghijcdklmnefopqr

451 else: 

452 previously_seen_type_refs.add(type_ref) 1abghijcdklmnsefopqr

453 yield 1abghijcdklmnsefopqr

454 previously_seen_type_refs.remove(type_ref) 1abghijcdklmnsefopqr

455 finally: 

456 if token: 1abghijcdklmnsefopqr

457 _generic_recursion_cache.reset(token) 1abghijcdklmnsefopqr

458 

459 

460def recursively_defined_type_refs() -> set[str]: 1abghijcdklmnsefopqr

461 visited = _generic_recursion_cache.get() 1abghijcdklmnefopqr

462 if not visited: 1abghijcdklmnefopqr

463 return set() # not in a generic recursion, so there are no types 1abghijcdklmnefopqr

464 

465 return visited.copy() # don't allow modifications 1abghijcdklmnefopqr

466 

467 

468def _generic_cache_get(key: GenericTypesCacheKey) -> type[BaseModel] | None: 1abghijcdklmnsefopqr

469 try: 1abghijcdklmnsefopqr

470 return _GENERIC_TYPES_CACHE.get(key) 1abghijcdklmnsefopqr

471 except TypeError: # unhashable typevar values 1abghijcdklmnefopqr

472 return None 1abghijcdklmnefopqr

473 

474 

475def _generic_cache_set(key: GenericTypesCacheKey, value: type[BaseModel]) -> None: 1abghijcdklmnsefopqr

476 try: 1abghijcdklmnsefopqr

477 _GENERIC_TYPES_CACHE[key] = value 1abghijcdklmnsefopqr

478 except TypeError: # unhashable typevar values 1abghijcdklmnefopqr

479 pass 1abghijcdklmnefopqr

480 

481 

482def get_cached_generic_type_early(parent: type[BaseModel], typevar_values: Any) -> type[BaseModel] | None: 1abghijcdklmnsefopqr

483 """The use of a two-stage cache lookup approach was necessary to have the highest performance possible for 

484 repeated calls to `__class_getitem__` on generic types (which may happen in tighter loops during runtime), 

485 while still ensuring that certain alternative parametrizations ultimately resolve to the same type. 

486 

487 As a concrete example, this approach was necessary to make Model[List[T]][int] equal to Model[List[int]]. 

488 The approach could be modified to not use two different cache keys at different points, but the 

489 _early_cache_key is optimized to be as quick to compute as possible (for repeated-access speed), and the 

490 _late_cache_key is optimized to be as "correct" as possible, so that two types that will ultimately be the 

491 same after resolving the type arguments will always produce cache hits. 

492 

493 If we wanted to move to only using a single cache key per type, we would either need to always use the 

494 slower/more computationally intensive logic associated with _late_cache_key, or would need to accept 

495 that Model[List[T]][int] is a different type than Model[List[T]][int]. Because we rely on subclass relationships 

496 during validation, I think it is worthwhile to ensure that types that are functionally equivalent are actually 

497 equal. 

498 """ 

499 return _generic_cache_get(_early_cache_key(parent, typevar_values)) 1abghijcdklmnsefopqr

500 

501 

502def get_cached_generic_type_late( 1abghijcdklmnsefopqr

503 parent: type[BaseModel], typevar_values: Any, origin: type[BaseModel], args: tuple[Any, ...] 

504) -> type[BaseModel] | None: 

505 """See the docstring of `get_cached_generic_type_early` for more information about the two-stage cache lookup.""" 

506 cached = _generic_cache_get(_late_cache_key(origin, args, typevar_values)) 1abghijcdklmnsefopqr

507 if cached is not None: 1abghijcdklmnsefopqr

508 set_cached_generic_type(parent, typevar_values, cached, origin, args) 1abghijcdklmnefopqr

509 return cached 1abghijcdklmnsefopqr

510 

511 

512def set_cached_generic_type( 1abghijcdklmnsefopqr

513 parent: type[BaseModel], 

514 typevar_values: tuple[Any, ...], 

515 type_: type[BaseModel], 

516 origin: type[BaseModel] | None = None, 

517 args: tuple[Any, ...] | None = None, 

518) -> None: 

519 """See the docstring of `get_cached_generic_type_early` for more information about why items are cached with 

520 two different keys. 

521 """ 

522 _generic_cache_set(_early_cache_key(parent, typevar_values), type_) 1abghijcdklmnsefopqr

523 if len(typevar_values) == 1: 1abghijcdklmnsefopqr

524 _generic_cache_set(_early_cache_key(parent, typevar_values[0]), type_) 1abghijcdklmnsefopqr

525 if origin and args: 1abghijcdklmnsefopqr

526 _generic_cache_set(_late_cache_key(origin, args, typevar_values), type_) 1abghijcdklmnsefopqr

527 

528 

529def _union_orderings_key(typevar_values: Any) -> Any: 1abghijcdklmnsefopqr

530 """This is intended to help differentiate between Union types with the same arguments in different order. 

531 

532 Thanks to caching internal to the `typing` module, it is not possible to distinguish between 

533 List[Union[int, float]] and List[Union[float, int]] (and similarly for other "parent" origins besides List) 

534 because `typing` considers Union[int, float] to be equal to Union[float, int]. 

535 

536 However, you _can_ distinguish between (top-level) Union[int, float] vs. Union[float, int]. 

537 Because we parse items as the first Union type that is successful, we get slightly more consistent behavior 

538 if we make an effort to distinguish the ordering of items in a union. It would be best if we could _always_ 

539 get the exact-correct order of items in the union, but that would require a change to the `typing` module itself. 

540 (See https://github.com/python/cpython/issues/86483 for reference.) 

541 """ 

542 if isinstance(typevar_values, tuple): 1abghijcdklmnsefopqr

543 return tuple(_union_orderings_key(value) for value in typevar_values) 1abghijcdklmnsefopqr

544 elif typing_objects.is_union(typing_extensions.get_origin(typevar_values)): 1abghijcdklmnsefopqr

545 return get_args(typevar_values) 1abghijcdklmnefopqr

546 else: 

547 return () 1abghijcdklmnsefopqr

548 

549 

550def _early_cache_key(cls: type[BaseModel], typevar_values: Any) -> GenericTypesCacheKey: 1abghijcdklmnsefopqr

551 """This is intended for minimal computational overhead during lookups of cached types. 

552 

553 Note that this is overly simplistic, and it's possible that two different cls/typevar_values 

554 inputs would ultimately result in the same type being created in BaseModel.__class_getitem__. 

555 To handle this, we have a fallback _late_cache_key that is checked later if the _early_cache_key 

556 lookup fails, and should result in a cache hit _precisely_ when the inputs to __class_getitem__ 

557 would result in the same type. 

558 """ 

559 return cls, typevar_values, _union_orderings_key(typevar_values) 1abghijcdklmnsefopqr

560 

561 

562def _late_cache_key(origin: type[BaseModel], args: tuple[Any, ...], typevar_values: Any) -> GenericTypesCacheKey: 1abghijcdklmnsefopqr

563 """This is intended for use later in the process of creating a new type, when we have more information 

564 about the exact args that will be passed. If it turns out that a different set of inputs to 

565 __class_getitem__ resulted in the same inputs to the generic type creation process, we can still 

566 return the cached type, and update the cache with the _early_cache_key as well. 

567 """ 

568 # The _union_orderings_key is placed at the start here to ensure there cannot be a collision with an 

569 # _early_cache_key, as that function will always produce a BaseModel subclass as the first item in the key, 

570 # whereas this function will always produce a tuple as the first item in the key. 

571 return _union_orderings_key(typevar_values), origin, args 1abghijcdklmnsefopqr