usdk 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
uapi/_models.py ADDED
@@ -0,0 +1,840 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ import weakref
6
+ from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, Optional, cast
7
+ from datetime import date, datetime
8
+ from typing_extensions import (
9
+ List,
10
+ Unpack,
11
+ Literal,
12
+ ClassVar,
13
+ Protocol,
14
+ Required,
15
+ ParamSpec,
16
+ TypedDict,
17
+ TypeGuard,
18
+ final,
19
+ override,
20
+ runtime_checkable,
21
+ )
22
+
23
+ import pydantic
24
+ from pydantic.fields import FieldInfo
25
+
26
+ from ._types import (
27
+ Body,
28
+ IncEx,
29
+ Query,
30
+ ModelT,
31
+ Headers,
32
+ Timeout,
33
+ NotGiven,
34
+ AnyMapping,
35
+ HttpxRequestFiles,
36
+ )
37
+ from ._utils import (
38
+ PropertyInfo,
39
+ is_list,
40
+ is_given,
41
+ json_safe,
42
+ lru_cache,
43
+ is_mapping,
44
+ parse_date,
45
+ coerce_boolean,
46
+ parse_datetime,
47
+ strip_not_given,
48
+ extract_type_arg,
49
+ is_annotated_type,
50
+ is_type_alias_type,
51
+ strip_annotated_type,
52
+ )
53
+ from ._compat import (
54
+ PYDANTIC_V1,
55
+ ConfigDict,
56
+ GenericModel as BaseGenericModel,
57
+ get_args,
58
+ is_union,
59
+ parse_obj,
60
+ get_origin,
61
+ is_literal_type,
62
+ get_model_config,
63
+ get_model_fields,
64
+ field_get_default,
65
+ )
66
+ from ._constants import RAW_RESPONSE_HEADER
67
+
68
+ if TYPE_CHECKING:
69
+ from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema
70
+
71
+ __all__ = ["BaseModel", "GenericModel"]
72
+
73
+ _T = TypeVar("_T")
74
+ _BaseModelT = TypeVar("_BaseModelT", bound="BaseModel")
75
+
76
+ P = ParamSpec("P")
77
+
78
+
79
+ @runtime_checkable
80
+ class _ConfigProtocol(Protocol):
81
+ allow_population_by_field_name: bool
82
+
83
+
84
+ class BaseModel(pydantic.BaseModel):
85
+ if PYDANTIC_V1:
86
+
87
+ @property
88
+ @override
89
+ def model_fields_set(self) -> set[str]:
90
+ # a forwards-compat shim for pydantic v2
91
+ return self.__fields_set__ # type: ignore
92
+
93
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
94
+ extra: Any = pydantic.Extra.allow # type: ignore
95
+ else:
96
+ model_config: ClassVar[ConfigDict] = ConfigDict(
97
+ extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
98
+ )
99
+
100
+ def to_dict(
101
+ self,
102
+ *,
103
+ mode: Literal["json", "python"] = "python",
104
+ use_api_names: bool = True,
105
+ exclude_unset: bool = True,
106
+ exclude_defaults: bool = False,
107
+ exclude_none: bool = False,
108
+ warnings: bool = True,
109
+ ) -> dict[str, object]:
110
+ """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
111
+
112
+ By default, fields that were not set by the API will not be included,
113
+ and keys will match the API response, *not* the property names from the model.
114
+
115
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
116
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
117
+
118
+ Args:
119
+ mode:
120
+ If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
121
+ If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
122
+
123
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
124
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
125
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
126
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
127
+ warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
128
+ """
129
+ return self.model_dump(
130
+ mode=mode,
131
+ by_alias=use_api_names,
132
+ exclude_unset=exclude_unset,
133
+ exclude_defaults=exclude_defaults,
134
+ exclude_none=exclude_none,
135
+ warnings=warnings,
136
+ )
137
+
138
+ def to_json(
139
+ self,
140
+ *,
141
+ indent: int | None = 2,
142
+ use_api_names: bool = True,
143
+ exclude_unset: bool = True,
144
+ exclude_defaults: bool = False,
145
+ exclude_none: bool = False,
146
+ warnings: bool = True,
147
+ ) -> str:
148
+ """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
149
+
150
+ By default, fields that were not set by the API will not be included,
151
+ and keys will match the API response, *not* the property names from the model.
152
+
153
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
154
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
155
+
156
+ Args:
157
+ indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
158
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
159
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
160
+ exclude_defaults: Whether to exclude fields that have the default value.
161
+ exclude_none: Whether to exclude fields that have a value of `None`.
162
+ warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
163
+ """
164
+ return self.model_dump_json(
165
+ indent=indent,
166
+ by_alias=use_api_names,
167
+ exclude_unset=exclude_unset,
168
+ exclude_defaults=exclude_defaults,
169
+ exclude_none=exclude_none,
170
+ warnings=warnings,
171
+ )
172
+
173
+ @override
174
+ def __str__(self) -> str:
175
+ # mypy complains about an invalid self arg
176
+ return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc]
177
+
178
+ # Override the 'construct' method in a way that supports recursive parsing without validation.
179
+ # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
180
+ @classmethod
181
+ @override
182
+ def construct( # pyright: ignore[reportIncompatibleMethodOverride]
183
+ __cls: Type[ModelT],
184
+ _fields_set: set[str] | None = None,
185
+ **values: object,
186
+ ) -> ModelT:
187
+ m = __cls.__new__(__cls)
188
+ fields_values: dict[str, object] = {}
189
+
190
+ config = get_model_config(__cls)
191
+ populate_by_name = (
192
+ config.allow_population_by_field_name
193
+ if isinstance(config, _ConfigProtocol)
194
+ else config.get("populate_by_name")
195
+ )
196
+
197
+ if _fields_set is None:
198
+ _fields_set = set()
199
+
200
+ model_fields = get_model_fields(__cls)
201
+ for name, field in model_fields.items():
202
+ key = field.alias
203
+ if key is None or (key not in values and populate_by_name):
204
+ key = name
205
+
206
+ if key in values:
207
+ fields_values[name] = _construct_field(value=values[key], field=field, key=key)
208
+ _fields_set.add(name)
209
+ else:
210
+ fields_values[name] = field_get_default(field)
211
+
212
+ extra_field_type = _get_extra_fields_type(__cls)
213
+
214
+ _extra = {}
215
+ for key, value in values.items():
216
+ if key not in model_fields:
217
+ parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value
218
+
219
+ if PYDANTIC_V1:
220
+ _fields_set.add(key)
221
+ fields_values[key] = parsed
222
+ else:
223
+ _extra[key] = parsed
224
+
225
+ object.__setattr__(m, "__dict__", fields_values)
226
+
227
+ if PYDANTIC_V1:
228
+ # init_private_attributes() does not exist in v2
229
+ m._init_private_attributes() # type: ignore
230
+
231
+ # copied from Pydantic v1's `construct()` method
232
+ object.__setattr__(m, "__fields_set__", _fields_set)
233
+ else:
234
+ # these properties are copied from Pydantic's `model_construct()` method
235
+ object.__setattr__(m, "__pydantic_private__", None)
236
+ object.__setattr__(m, "__pydantic_extra__", _extra)
237
+ object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
238
+
239
+ return m
240
+
241
+ if not TYPE_CHECKING:
242
+ # type checkers incorrectly complain about this assignment
243
+ # because the type signatures are technically different
244
+ # although not in practice
245
+ model_construct = construct
246
+
247
+ if PYDANTIC_V1:
248
+ # we define aliases for some of the new pydantic v2 methods so
249
+ # that we can just document these methods without having to specify
250
+ # a specific pydantic version as some users may not know which
251
+ # pydantic version they are currently using
252
+
253
+ @override
254
+ def model_dump(
255
+ self,
256
+ *,
257
+ mode: Literal["json", "python"] | str = "python",
258
+ include: IncEx | None = None,
259
+ exclude: IncEx | None = None,
260
+ by_alias: bool | None = None,
261
+ exclude_unset: bool = False,
262
+ exclude_defaults: bool = False,
263
+ exclude_none: bool = False,
264
+ round_trip: bool = False,
265
+ warnings: bool | Literal["none", "warn", "error"] = True,
266
+ context: dict[str, Any] | None = None,
267
+ serialize_as_any: bool = False,
268
+ fallback: Callable[[Any], Any] | None = None,
269
+ ) -> dict[str, Any]:
270
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
271
+
272
+ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
273
+
274
+ Args:
275
+ mode: The mode in which `to_python` should run.
276
+ If mode is 'json', the dictionary will only contain JSON serializable types.
277
+ If mode is 'python', the dictionary may contain any Python objects.
278
+ include: A list of fields to include in the output.
279
+ exclude: A list of fields to exclude from the output.
280
+ by_alias: Whether to use the field's alias in the dictionary key if defined.
281
+ exclude_unset: Whether to exclude fields that are unset or None from the output.
282
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
283
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
284
+ round_trip: Whether to enable serialization and deserialization round-trip support.
285
+ warnings: Whether to log warnings when invalid fields are encountered.
286
+
287
+ Returns:
288
+ A dictionary representation of the model.
289
+ """
290
+ if mode not in {"json", "python"}:
291
+ raise ValueError("mode must be either 'json' or 'python'")
292
+ if round_trip != False:
293
+ raise ValueError("round_trip is only supported in Pydantic v2")
294
+ if warnings != True:
295
+ raise ValueError("warnings is only supported in Pydantic v2")
296
+ if context is not None:
297
+ raise ValueError("context is only supported in Pydantic v2")
298
+ if serialize_as_any != False:
299
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
300
+ if fallback is not None:
301
+ raise ValueError("fallback is only supported in Pydantic v2")
302
+ dumped = super().dict( # pyright: ignore[reportDeprecated]
303
+ include=include,
304
+ exclude=exclude,
305
+ by_alias=by_alias if by_alias is not None else False,
306
+ exclude_unset=exclude_unset,
307
+ exclude_defaults=exclude_defaults,
308
+ exclude_none=exclude_none,
309
+ )
310
+
311
+ return cast("dict[str, Any]", json_safe(dumped)) if mode == "json" else dumped
312
+
313
+ @override
314
+ def model_dump_json(
315
+ self,
316
+ *,
317
+ indent: int | None = None,
318
+ include: IncEx | None = None,
319
+ exclude: IncEx | None = None,
320
+ by_alias: bool | None = None,
321
+ exclude_unset: bool = False,
322
+ exclude_defaults: bool = False,
323
+ exclude_none: bool = False,
324
+ round_trip: bool = False,
325
+ warnings: bool | Literal["none", "warn", "error"] = True,
326
+ context: dict[str, Any] | None = None,
327
+ fallback: Callable[[Any], Any] | None = None,
328
+ serialize_as_any: bool = False,
329
+ ) -> str:
330
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
331
+
332
+ Generates a JSON representation of the model using Pydantic's `to_json` method.
333
+
334
+ Args:
335
+ indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
336
+ include: Field(s) to include in the JSON output. Can take either a string or set of strings.
337
+ exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings.
338
+ by_alias: Whether to serialize using field aliases.
339
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
340
+ exclude_defaults: Whether to exclude fields that have the default value.
341
+ exclude_none: Whether to exclude fields that have a value of `None`.
342
+ round_trip: Whether to use serialization/deserialization between JSON and class instance.
343
+ warnings: Whether to show any warnings that occurred during serialization.
344
+
345
+ Returns:
346
+ A JSON string representation of the model.
347
+ """
348
+ if round_trip != False:
349
+ raise ValueError("round_trip is only supported in Pydantic v2")
350
+ if warnings != True:
351
+ raise ValueError("warnings is only supported in Pydantic v2")
352
+ if context is not None:
353
+ raise ValueError("context is only supported in Pydantic v2")
354
+ if serialize_as_any != False:
355
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
356
+ if fallback is not None:
357
+ raise ValueError("fallback is only supported in Pydantic v2")
358
+ return super().json( # type: ignore[reportDeprecated]
359
+ indent=indent,
360
+ include=include,
361
+ exclude=exclude,
362
+ by_alias=by_alias if by_alias is not None else False,
363
+ exclude_unset=exclude_unset,
364
+ exclude_defaults=exclude_defaults,
365
+ exclude_none=exclude_none,
366
+ )
367
+
368
+
369
+ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
370
+ if value is None:
371
+ return field_get_default(field)
372
+
373
+ if PYDANTIC_V1:
374
+ type_ = cast(type, field.outer_type_) # type: ignore
375
+ else:
376
+ type_ = field.annotation # type: ignore
377
+
378
+ if type_ is None:
379
+ raise RuntimeError(f"Unexpected field type is None for {key}")
380
+
381
+ return construct_type(value=value, type_=type_, metadata=getattr(field, "metadata", None))
382
+
383
+
384
+ def _get_extra_fields_type(cls: type[pydantic.BaseModel]) -> type | None:
385
+ if PYDANTIC_V1:
386
+ # TODO
387
+ return None
388
+
389
+ schema = cls.__pydantic_core_schema__
390
+ if schema["type"] == "model":
391
+ fields = schema["schema"]
392
+ if fields["type"] == "model-fields":
393
+ extras = fields.get("extras_schema")
394
+ if extras and "cls" in extras:
395
+ # mypy can't narrow the type
396
+ return extras["cls"] # type: ignore[no-any-return]
397
+
398
+ return None
399
+
400
+
401
+ def is_basemodel(type_: type) -> bool:
402
+ """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
403
+ if is_union(type_):
404
+ for variant in get_args(type_):
405
+ if is_basemodel(variant):
406
+ return True
407
+
408
+ return False
409
+
410
+ return is_basemodel_type(type_)
411
+
412
+
413
+ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]:
414
+ origin = get_origin(type_) or type_
415
+ if not inspect.isclass(origin):
416
+ return False
417
+ return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
418
+
419
+
420
+ def build(
421
+ base_model_cls: Callable[P, _BaseModelT],
422
+ *args: P.args,
423
+ **kwargs: P.kwargs,
424
+ ) -> _BaseModelT:
425
+ """Construct a BaseModel class without validation.
426
+
427
+ This is useful for cases where you need to instantiate a `BaseModel`
428
+ from an API response as this provides type-safe params which isn't supported
429
+ by helpers like `construct_type()`.
430
+
431
+ ```py
432
+ build(MyModel, my_field_a="foo", my_field_b=123)
433
+ ```
434
+ """
435
+ if args:
436
+ raise TypeError(
437
+ "Received positional arguments which are not supported; Keyword arguments must be used instead",
438
+ )
439
+
440
+ return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs))
441
+
442
+
443
+ def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T:
444
+ """Loose coercion to the expected type with construction of nested values.
445
+
446
+ Note: the returned value from this function is not guaranteed to match the
447
+ given type.
448
+ """
449
+ return cast(_T, construct_type(value=value, type_=type_))
450
+
451
+
452
+ def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]] = None) -> object:
453
+ """Loose coercion to the expected type with construction of nested values.
454
+
455
+ If the given value does not match the expected type then it is returned as-is.
456
+ """
457
+
458
+ # store a reference to the original type we were given before we extract any inner
459
+ # types so that we can properly resolve forward references in `TypeAliasType` annotations
460
+ original_type = None
461
+
462
+ # we allow `object` as the input type because otherwise, passing things like
463
+ # `Literal['value']` will be reported as a type error by type checkers
464
+ type_ = cast("type[object]", type_)
465
+ if is_type_alias_type(type_):
466
+ original_type = type_ # type: ignore[unreachable]
467
+ type_ = type_.__value__ # type: ignore[unreachable]
468
+
469
+ # unwrap `Annotated[T, ...]` -> `T`
470
+ if metadata is not None and len(metadata) > 0:
471
+ meta: tuple[Any, ...] = tuple(metadata)
472
+ elif is_annotated_type(type_):
473
+ meta = get_args(type_)[1:]
474
+ type_ = extract_type_arg(type_, 0)
475
+ else:
476
+ meta = tuple()
477
+
478
+ # we need to use the origin class for any types that are subscripted generics
479
+ # e.g. Dict[str, object]
480
+ origin = get_origin(type_) or type_
481
+ args = get_args(type_)
482
+
483
+ if is_union(origin):
484
+ try:
485
+ return validate_type(type_=cast("type[object]", original_type or type_), value=value)
486
+ except Exception:
487
+ pass
488
+
489
+ # if the type is a discriminated union then we want to construct the right variant
490
+ # in the union, even if the data doesn't match exactly, otherwise we'd break code
491
+ # that relies on the constructed class types, e.g.
492
+ #
493
+ # class FooType:
494
+ # kind: Literal['foo']
495
+ # value: str
496
+ #
497
+ # class BarType:
498
+ # kind: Literal['bar']
499
+ # value: int
500
+ #
501
+ # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then
502
+ # we'd end up constructing `FooType` when it should be `BarType`.
503
+ discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta)
504
+ if discriminator and is_mapping(value):
505
+ variant_value = value.get(discriminator.field_alias_from or discriminator.field_name)
506
+ if variant_value and isinstance(variant_value, str):
507
+ variant_type = discriminator.mapping.get(variant_value)
508
+ if variant_type:
509
+ return construct_type(type_=variant_type, value=value)
510
+
511
+ # if the data is not valid, use the first variant that doesn't fail while deserializing
512
+ for variant in args:
513
+ try:
514
+ return construct_type(value=value, type_=variant)
515
+ except Exception:
516
+ continue
517
+
518
+ raise RuntimeError(f"Could not convert data into a valid instance of {type_}")
519
+
520
+ if origin == dict:
521
+ if not is_mapping(value):
522
+ return value
523
+
524
+ _, items_type = get_args(type_) # Dict[_, items_type]
525
+ return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}
526
+
527
+ if (
528
+ not is_literal_type(type_)
529
+ and inspect.isclass(origin)
530
+ and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel))
531
+ ):
532
+ if is_list(value):
533
+ return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value]
534
+
535
+ if is_mapping(value):
536
+ if issubclass(type_, BaseModel):
537
+ return type_.construct(**value) # type: ignore[arg-type]
538
+
539
+ return cast(Any, type_).construct(**value)
540
+
541
+ if origin == list:
542
+ if not is_list(value):
543
+ return value
544
+
545
+ inner_type = args[0] # List[inner_type]
546
+ return [construct_type(value=entry, type_=inner_type) for entry in value]
547
+
548
+ if origin == float:
549
+ if isinstance(value, int):
550
+ coerced = float(value)
551
+ if coerced != value:
552
+ return value
553
+ return coerced
554
+
555
+ return value
556
+
557
+ if type_ == datetime:
558
+ try:
559
+ return parse_datetime(value) # type: ignore
560
+ except Exception:
561
+ return value
562
+
563
+ if type_ == date:
564
+ try:
565
+ return parse_date(value) # type: ignore
566
+ except Exception:
567
+ return value
568
+
569
+ return value
570
+
571
+
572
+ @runtime_checkable
573
+ class CachedDiscriminatorType(Protocol):
574
+ __discriminator__: DiscriminatorDetails
575
+
576
+
577
+ DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary()
578
+
579
+
580
+ class DiscriminatorDetails:
581
+ field_name: str
582
+ """The name of the discriminator field in the variant class, e.g.
583
+
584
+ ```py
585
+ class Foo(BaseModel):
586
+ type: Literal['foo']
587
+ ```
588
+
589
+ Will result in field_name='type'
590
+ """
591
+
592
+ field_alias_from: str | None
593
+ """The name of the discriminator field in the API response, e.g.
594
+
595
+ ```py
596
+ class Foo(BaseModel):
597
+ type: Literal['foo'] = Field(alias='type_from_api')
598
+ ```
599
+
600
+ Will result in field_alias_from='type_from_api'
601
+ """
602
+
603
+ mapping: dict[str, type]
604
+ """Mapping of discriminator value to variant type, e.g.
605
+
606
+ {'foo': FooVariant, 'bar': BarVariant}
607
+ """
608
+
609
+ def __init__(
610
+ self,
611
+ *,
612
+ mapping: dict[str, type],
613
+ discriminator_field: str,
614
+ discriminator_alias: str | None,
615
+ ) -> None:
616
+ self.mapping = mapping
617
+ self.field_name = discriminator_field
618
+ self.field_alias_from = discriminator_alias
619
+
620
+
621
+ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
622
+ cached = DISCRIMINATOR_CACHE.get(union)
623
+ if cached is not None:
624
+ return cached
625
+
626
+ discriminator_field_name: str | None = None
627
+
628
+ for annotation in meta_annotations:
629
+ if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None:
630
+ discriminator_field_name = annotation.discriminator
631
+ break
632
+
633
+ if not discriminator_field_name:
634
+ return None
635
+
636
+ mapping: dict[str, type] = {}
637
+ discriminator_alias: str | None = None
638
+
639
+ for variant in get_args(union):
640
+ variant = strip_annotated_type(variant)
641
+ if is_basemodel_type(variant):
642
+ if PYDANTIC_V1:
643
+ field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
644
+ if not field_info:
645
+ continue
646
+
647
+ # Note: if one variant defines an alias then they all should
648
+ discriminator_alias = field_info.alias
649
+
650
+ if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation):
651
+ for entry in get_args(annotation):
652
+ if isinstance(entry, str):
653
+ mapping[entry] = variant
654
+ else:
655
+ field = _extract_field_schema_pv2(variant, discriminator_field_name)
656
+ if not field:
657
+ continue
658
+
659
+ # Note: if one variant defines an alias then they all should
660
+ discriminator_alias = field.get("serialization_alias")
661
+
662
+ field_schema = field["schema"]
663
+
664
+ if field_schema["type"] == "literal":
665
+ for entry in cast("LiteralSchema", field_schema)["expected"]:
666
+ if isinstance(entry, str):
667
+ mapping[entry] = variant
668
+
669
+ if not mapping:
670
+ return None
671
+
672
+ details = DiscriminatorDetails(
673
+ mapping=mapping,
674
+ discriminator_field=discriminator_field_name,
675
+ discriminator_alias=discriminator_alias,
676
+ )
677
+ DISCRIMINATOR_CACHE.setdefault(union, details)
678
+ return details
679
+
680
+
681
+ def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None:
682
+ schema = model.__pydantic_core_schema__
683
+ if schema["type"] == "definitions":
684
+ schema = schema["schema"]
685
+
686
+ if schema["type"] != "model":
687
+ return None
688
+
689
+ schema = cast("ModelSchema", schema)
690
+ fields_schema = schema["schema"]
691
+ if fields_schema["type"] != "model-fields":
692
+ return None
693
+
694
+ fields_schema = cast("ModelFieldsSchema", fields_schema)
695
+ field = fields_schema["fields"].get(field_name)
696
+ if not field:
697
+ return None
698
+
699
+ return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast]
700
+
701
+
702
+ def validate_type(*, type_: type[_T], value: object) -> _T:
703
+ """Strict validation that the given value matches the expected type"""
704
+ if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
705
+ return cast(_T, parse_obj(type_, value))
706
+
707
+ return cast(_T, _validate_non_model_type(type_=type_, value=value))
708
+
709
+
710
+ def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None:
711
+ """Add a pydantic config for the given type.
712
+
713
+ Note: this is a no-op on Pydantic v1.
714
+ """
715
+ setattr(typ, "__pydantic_config__", config) # noqa: B010
716
+
717
+
718
+ # our use of subclassing here causes weirdness for type checkers,
719
+ # so we just pretend that we don't subclass
720
+ if TYPE_CHECKING:
721
+ GenericModel = BaseModel
722
+ else:
723
+
724
+ class GenericModel(BaseGenericModel, BaseModel):
725
+ pass
726
+
727
+
728
+ if not PYDANTIC_V1:
729
+ from pydantic import TypeAdapter as _TypeAdapter
730
+
731
+ _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter))
732
+
733
+ if TYPE_CHECKING:
734
+ from pydantic import TypeAdapter
735
+ else:
736
+ TypeAdapter = _CachedTypeAdapter
737
+
738
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
739
+ return TypeAdapter(type_).validate_python(value)
740
+
741
+ elif not TYPE_CHECKING: # TODO: condition is weird
742
+
743
+ class RootModel(GenericModel, Generic[_T]):
744
+ """Used as a placeholder to easily convert runtime types to a Pydantic format
745
+ to provide validation.
746
+
747
+ For example:
748
+ ```py
749
+ validated = RootModel[int](__root__="5").__root__
750
+ # validated: 5
751
+ ```
752
+ """
753
+
754
+ __root__: _T
755
+
756
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
757
+ model = _create_pydantic_model(type_).validate(value)
758
+ return cast(_T, model.__root__)
759
+
760
+ def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]:
761
+ return RootModel[type_] # type: ignore
762
+
763
+
764
+ class FinalRequestOptionsInput(TypedDict, total=False):
765
+ method: Required[str]
766
+ url: Required[str]
767
+ params: Query
768
+ headers: Headers
769
+ max_retries: int
770
+ timeout: float | Timeout | None
771
+ files: HttpxRequestFiles | None
772
+ idempotency_key: str
773
+ json_data: Body
774
+ extra_json: AnyMapping
775
+ follow_redirects: bool
776
+
777
+
778
+ @final
779
+ class FinalRequestOptions(pydantic.BaseModel):
780
+ method: str
781
+ url: str
782
+ params: Query = {}
783
+ headers: Union[Headers, NotGiven] = NotGiven()
784
+ max_retries: Union[int, NotGiven] = NotGiven()
785
+ timeout: Union[float, Timeout, None, NotGiven] = NotGiven()
786
+ files: Union[HttpxRequestFiles, None] = None
787
+ idempotency_key: Union[str, None] = None
788
+ post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven()
789
+ follow_redirects: Union[bool, None] = None
790
+
791
+ # It should be noted that we cannot use `json` here as that would override
792
+ # a BaseModel method in an incompatible fashion.
793
+ json_data: Union[Body, None] = None
794
+ extra_json: Union[AnyMapping, None] = None
795
+
796
+ if PYDANTIC_V1:
797
+
798
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
799
+ arbitrary_types_allowed: bool = True
800
+ else:
801
+ model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
802
+
803
+ def get_max_retries(self, max_retries: int) -> int:
804
+ if isinstance(self.max_retries, NotGiven):
805
+ return max_retries
806
+ return self.max_retries
807
+
808
+ def _strip_raw_response_header(self) -> None:
809
+ if not is_given(self.headers):
810
+ return
811
+
812
+ if self.headers.get(RAW_RESPONSE_HEADER):
813
+ self.headers = {**self.headers}
814
+ self.headers.pop(RAW_RESPONSE_HEADER)
815
+
816
+ # override the `construct` method so that we can run custom transformations.
817
+ # this is necessary as we don't want to do any actual runtime type checking
818
+ # (which means we can't use validators) but we do want to ensure that `NotGiven`
819
+ # values are not present
820
+ #
821
+ # type ignore required because we're adding explicit types to `**values`
822
+ @classmethod
823
+ def construct( # type: ignore
824
+ cls,
825
+ _fields_set: set[str] | None = None,
826
+ **values: Unpack[FinalRequestOptionsInput],
827
+ ) -> FinalRequestOptions:
828
+ kwargs: dict[str, Any] = {
829
+ # we unconditionally call `strip_not_given` on any value
830
+ # as it will just ignore any non-mapping types
831
+ key: strip_not_given(value)
832
+ for key, value in values.items()
833
+ }
834
+ if PYDANTIC_V1:
835
+ return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated]
836
+ return super().model_construct(_fields_set, **kwargs)
837
+
838
+ if not TYPE_CHECKING:
839
+ # type checkers incorrectly complain about this assignment
840
+ model_construct = construct