Debian Codegraph @

src/anthropic/_compat.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
4 from datetime import date, datetime
5 from typing_extensions import Self, Literal, TypedDict
6
7 import pydantic
8 from pydantic.fields import FieldInfo
9
10 from ._types import IncEx, StrBytesIntFloat
11
12 _T = TypeVar("_T")
13 _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
14
15 # --------------- Pydantic v2, v3 compatibility ---------------
16
17 # Pyright incorrectly reports some of our functions as overriding a method when they don't
18 # pyright: reportIncompatibleMethodOverride=false
19
20 PYDANTIC_V1 = pydantic.VERSION.startswith("1.")
21
22 if TYPE_CHECKING:
23
24 def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001
25 ...
26
27 def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001
28 ...
29
30 def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001
31 ...
32
33 def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001
34 ...
35
36 def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001
37 ...
38
39 def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001
40 ...
41
42 else:
43 # v1 re-exports
44 if PYDANTIC_V1:
45 from pydantic.typing import (
46 get_args as get_args,
47 is_union as is_union,
48 get_origin as get_origin,
49 is_literal_type as is_literal_type,
50 )
51 from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
52 else:
53 from ._utils import (
54 get_args as get_args,
55 is_union as is_union,
56 get_origin as get_origin,
57 parse_date as parse_date,
58 parse_datetime as parse_datetime,
59 is_literal_type as is_literal_type,
60 )
61
62
63 # refactored config
64 if TYPE_CHECKING:
65 from pydantic import ConfigDict as ConfigDict
66 else:
67 if PYDANTIC_V1:
68 # TODO: provide an error message here?
69 ConfigDict = None
70 else:
71 from pydantic import ConfigDict as ConfigDict
72
73
74 # renamed methods / properties
75 def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
76 if PYDANTIC_V1:
77 return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
78 else:
79 return model.model_validate(value)
80
81
82 def field_is_required(field: FieldInfo) -> bool:
83 if PYDANTIC_V1:
84 return field.required # type: ignore
85 return field.is_required()
86
87
88 def field_get_default(field: FieldInfo) -> Any:
89 value = field.get_default()
90 if PYDANTIC_V1:
91 return value
92 from pydantic_core import PydanticUndefined
93
94 if value == PydanticUndefined:
95 return None
96 return value
97
98
99 def field_outer_type(field: FieldInfo) -> Any:
100 if PYDANTIC_V1:
101 return field.outer_type_ # type: ignore
102 return field.annotation
103
104
105 def get_model_config(model: type[pydantic.BaseModel]) -> Any:
106 if PYDANTIC_V1:
107 return model.__config__ # type: ignore
108 return model.model_config
109
110
111 def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]:
112 if PYDANTIC_V1:
113 return model.__fields__ # type: ignore
114 return model.model_fields
115
116
117 def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT:
118 if PYDANTIC_V1:
119 return model.copy(deep=deep) # type: ignore
120 return model.model_copy(deep=deep)
121
122
123 def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
124 if PYDANTIC_V1:
125 return model.json(indent=indent) # type: ignore
126 return model.model_dump_json(indent=indent)
127
128
129 def model_parse_json(model: type[_ModelT], data: str | bytes) -> _ModelT:
130 if PYDANTIC_V1:
131 return model.parse_raw(data) # pyright: ignore[reportDeprecated]
132 return model.model_validate_json(data)
133
134
135 class _ModelDumpKwargs(TypedDict, total=False):
136 by_alias: bool
137
138
139 def model_dump(
140 model: pydantic.BaseModel,
141 *,
142 exclude: IncEx | None = None,
143 exclude_unset: bool = False,
144 exclude_defaults: bool = False,
145 warnings: bool = True,
146 mode: Literal["json", "python"] = "python",
147 by_alias: bool | None = None,
148 ) -> dict[str, Any]:
149 if (not PYDANTIC_V1) or hasattr(model, "model_dump"):
150 kwargs: _ModelDumpKwargs = {}
151 if by_alias is not None:
152 kwargs["by_alias"] = by_alias
153 return model.model_dump(
154 mode=mode,
155 exclude=exclude,
156 exclude_unset=exclude_unset,
157 exclude_defaults=exclude_defaults,
158 # warnings are not supported in Pydantic v1
159 warnings=True if PYDANTIC_V1 else warnings,
160 **kwargs,
161 )
162 return cast(
163 "dict[str, Any]",
164 model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
165 exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias)
166 ),
167 )
168
169
170 def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
171 if PYDANTIC_V1:
172 return model.parse_obj(data) # pyright: ignore[reportDeprecated]
173 return model.model_validate(data)
174
175
176 # generic models
177 if TYPE_CHECKING:
178
179 class GenericModel(pydantic.BaseModel): ...
180
181 else:
182 if PYDANTIC_V1:
183 import pydantic.generics
184
185 class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ...
186 else:
187 # there no longer needs to be a distinction in v2 but
188 # we still have to create our own subclass to avoid
189 # inconsistent MRO ordering errors
190 class GenericModel(pydantic.BaseModel): ...
191
192
193 # cached properties
194 if TYPE_CHECKING:
195 cached_property = property
196
197 # we define a separate type (copied from typeshed)
198 # that represents that `cached_property` is `set`able
199 # at runtime, which differs from `@property`.
200 #
201 # this is a separate type as editors likely special case
202 # `@property` and we don't want to cause issues just to have
203 # more helpful internal types.
204
205 class typed_cached_property(Generic[_T]):
206 func: Callable[[Any], _T]
207 attrname: str | None
208
209 def __init__(self, func: Callable[[Any], _T]) -> None: ...
210
211 @overload
212 def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ...
213
214 @overload
215 def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ...
216
217 def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self:
218 raise NotImplementedError()
219
220 def __set_name__(self, owner: type[Any], name: str) -> None: ...
221
222 # __set__ is not defined at runtime, but @cached_property is designed to be settable
223 def __set__(self, instance: object, value: _T) -> None: ...
224 else:
225 from functools import cached_property as cached_property
226
227 typed_cached_property = cached_property