Skip to content

Commit f5dc239

Browse files
stainless-app[bot]stainless-bot
authored andcommitted
chore: rebuild project due to codegen change (#518)
1 parent 6ccb4f3 commit f5dc239

10 files changed

+63
-28
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
[![PyPI version](https://img.shields.io/pypi/v/finch-api.svg)](https://pypi.org/project/finch-api/)
44

5-
The Finch Python library provides convenient access to the Finch REST API from any Python 3.7+
5+
The Finch Python library provides convenient access to the Finch REST API from any Python 3.8+
66
application. The library includes type definitions for all request params and response fields,
77
and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).
88

@@ -429,7 +429,7 @@ print(finch.__version__)
429429

430430
## Requirements
431431

432-
Python 3.7 or higher.
432+
Python 3.8 or higher.
433433

434434
## Contributing
435435

pyproject.toml

+2-3
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,10 @@ dependencies = [
1616
"sniffio",
1717
"cached-property; python_version < '3.8'",
1818
]
19-
requires-python = ">= 3.7"
19+
requires-python = ">= 3.8"
2020
classifiers = [
2121
"Typing :: Typed",
2222
"Intended Audience :: Developers",
23-
"Programming Language :: Python :: 3.7",
2423
"Programming Language :: Python :: 3.8",
2524
"Programming Language :: Python :: 3.9",
2625
"Programming Language :: Python :: 3.10",
@@ -139,7 +138,7 @@ filterwarnings = [
139138
# there are a couple of flags that are still disabled by
140139
# default in strict mode as they are experimental and niche.
141140
typeCheckingMode = "strict"
142-
pythonVersion = "3.7"
141+
pythonVersion = "3.8"
143142

144143
exclude = [
145144
"_dev",

src/finch/_compat.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
44
from datetime import date, datetime
5-
from typing_extensions import Self
5+
from typing_extensions import Self, Literal
66

77
import pydantic
88
from pydantic.fields import FieldInfo
@@ -137,9 +137,11 @@ def model_dump(
137137
exclude_unset: bool = False,
138138
exclude_defaults: bool = False,
139139
warnings: bool = True,
140+
mode: Literal["json", "python"] = "python",
140141
) -> dict[str, Any]:
141-
if PYDANTIC_V2:
142+
if PYDANTIC_V2 or hasattr(model, "model_dump"):
142143
return model.model_dump(
144+
mode=mode,
143145
exclude=exclude,
144146
exclude_unset=exclude_unset,
145147
exclude_defaults=exclude_defaults,

src/finch/_models.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
PropertyInfo,
3838
is_list,
3939
is_given,
40+
json_safe,
4041
lru_cache,
4142
is_mapping,
4243
parse_date,
@@ -279,8 +280,8 @@ def model_dump(
279280
Returns:
280281
A dictionary representation of the model.
281282
"""
282-
if mode != "python":
283-
raise ValueError("mode is only supported in Pydantic v2")
283+
if mode not in {"json", "python"}:
284+
raise ValueError("mode must be either 'json' or 'python'")
284285
if round_trip != False:
285286
raise ValueError("round_trip is only supported in Pydantic v2")
286287
if warnings != True:
@@ -289,7 +290,7 @@ def model_dump(
289290
raise ValueError("context is only supported in Pydantic v2")
290291
if serialize_as_any != False:
291292
raise ValueError("serialize_as_any is only supported in Pydantic v2")
292-
return super().dict( # pyright: ignore[reportDeprecated]
293+
dumped = super().dict( # pyright: ignore[reportDeprecated]
293294
include=include,
294295
exclude=exclude,
295296
by_alias=by_alias,
@@ -298,6 +299,8 @@ def model_dump(
298299
exclude_none=exclude_none,
299300
)
300301

302+
return cast(dict[str, Any], json_safe(dumped)) if mode == "json" else dumped
303+
301304
@override
302305
def model_dump_json(
303306
self,

src/finch/_utils/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
is_list as is_list,
77
is_given as is_given,
88
is_tuple as is_tuple,
9+
json_safe as json_safe,
910
lru_cache as lru_cache,
1011
is_mapping as is_mapping,
1112
is_tuple_t as is_tuple_t,

src/finch/_utils/_transform.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,11 @@ def _transform_recursive(
173173
# Iterable[T]
174174
or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
175175
):
176+
# dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
177+
# intended as an iterable, so we don't transform it.
178+
if isinstance(data, dict):
179+
return cast(object, data)
180+
176181
inner_type = extract_type_arg(stripped_type, 0)
177182
return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
178183

@@ -186,7 +191,7 @@ def _transform_recursive(
186191
return data
187192

188193
if isinstance(data, pydantic.BaseModel):
189-
return model_dump(data, exclude_unset=True)
194+
return model_dump(data, exclude_unset=True, mode="json")
190195

191196
annotated_type = _get_annotated_type(annotation)
192197
if annotated_type is None:
@@ -324,7 +329,7 @@ async def _async_transform_recursive(
324329
return data
325330

326331
if isinstance(data, pydantic.BaseModel):
327-
return model_dump(data, exclude_unset=True)
332+
return model_dump(data, exclude_unset=True, mode="json")
328333

329334
annotated_type = _get_annotated_type(annotation)
330335
if annotated_type is None:

src/finch/_utils/_utils.py

+17
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
overload,
1717
)
1818
from pathlib import Path
19+
from datetime import date, datetime
1920
from typing_extensions import TypeGuard
2021

2122
import sniffio
@@ -395,3 +396,19 @@ def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]:
395396
maxsize=maxsize,
396397
)
397398
return cast(Any, wrapper) # type: ignore[no-any-return]
399+
400+
401+
def json_safe(data: object) -> object:
402+
"""Translates a mapping / sequence recursively in the same fashion
403+
as `pydantic` v2's `model_dump(mode="json")`.
404+
"""
405+
if is_mapping(data):
406+
return {json_safe(key): json_safe(value) for key, value in data.items()}
407+
408+
if is_iterable(data) and not isinstance(data, (str, bytes, bytearray)):
409+
return [json_safe(item) for item in data]
410+
411+
if isinstance(data, (datetime, date)):
412+
return data.isoformat()
413+
414+
return data

tests/test_client.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -810,7 +810,7 @@ class Model(BaseModel):
810810
[3, "", 0.5],
811811
[2, "", 0.5 * 2.0],
812812
[1, "", 0.5 * 4.0],
813-
[-1100, "", 7.8], # test large number potentially overflowing
813+
[-1100, "", 8], # test large number potentially overflowing
814814
],
815815
)
816816
@mock.patch("time.time", mock.MagicMock(return_value=1696004797))
@@ -1697,7 +1697,7 @@ class Model(BaseModel):
16971697
[3, "", 0.5],
16981698
[2, "", 0.5 * 2.0],
16991699
[1, "", 0.5 * 4.0],
1700-
[-1100, "", 7.8], # test large number potentially overflowing
1700+
[-1100, "", 8], # test large number potentially overflowing
17011701
],
17021702
)
17031703
@mock.patch("time.time", mock.MagicMock(return_value=1696004797))

tests/test_models.py

+7-14
Original file line numberDiff line numberDiff line change
@@ -520,19 +520,15 @@ class Model(BaseModel):
520520
assert m3.to_dict(exclude_none=True) == {}
521521
assert m3.to_dict(exclude_defaults=True) == {}
522522

523-
if PYDANTIC_V2:
524-
525-
class Model2(BaseModel):
526-
created_at: datetime
523+
class Model2(BaseModel):
524+
created_at: datetime
527525

528-
time_str = "2024-03-21T11:39:01.275859"
529-
m4 = Model2.construct(created_at=time_str)
530-
assert m4.to_dict(mode="python") == {"created_at": datetime.fromisoformat(time_str)}
531-
assert m4.to_dict(mode="json") == {"created_at": time_str}
532-
else:
533-
with pytest.raises(ValueError, match="mode is only supported in Pydantic v2"):
534-
m.to_dict(mode="json")
526+
time_str = "2024-03-21T11:39:01.275859"
527+
m4 = Model2.construct(created_at=time_str)
528+
assert m4.to_dict(mode="python") == {"created_at": datetime.fromisoformat(time_str)}
529+
assert m4.to_dict(mode="json") == {"created_at": time_str}
535530

531+
if not PYDANTIC_V2:
536532
with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"):
537533
m.to_dict(warnings=False)
538534

@@ -558,9 +554,6 @@ class Model(BaseModel):
558554
assert m3.model_dump(exclude_none=True) == {}
559555

560556
if not PYDANTIC_V2:
561-
with pytest.raises(ValueError, match="mode is only supported in Pydantic v2"):
562-
m.model_dump(mode="json")
563-
564557
with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"):
565558
m.model_dump(round_trip=True)
566559

tests/test_transform.py

+15
Original file line numberDiff line numberDiff line change
@@ -177,17 +177,32 @@ class DateDict(TypedDict, total=False):
177177
foo: Annotated[date, PropertyInfo(format="iso8601")]
178178

179179

180+
class DatetimeModel(BaseModel):
181+
foo: datetime
182+
183+
184+
class DateModel(BaseModel):
185+
foo: Optional[date]
186+
187+
180188
@parametrize
181189
@pytest.mark.asyncio
182190
async def test_iso8601_format(use_async: bool) -> None:
183191
dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00")
192+
tz = "Z" if PYDANTIC_V2 else "+00:00"
184193
assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap]
194+
assert await transform(DatetimeModel(foo=dt), Any, use_async) == {"foo": "2023-02-23T14:16:36.337692" + tz} # type: ignore[comparison-overlap]
185195

186196
dt = dt.replace(tzinfo=None)
187197
assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap]
198+
assert await transform(DatetimeModel(foo=dt), Any, use_async) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap]
188199

189200
assert await transform({"foo": None}, DateDict, use_async) == {"foo": None} # type: ignore[comparison-overlap]
201+
assert await transform(DateModel(foo=None), Any, use_async) == {"foo": None} # type: ignore
190202
assert await transform({"foo": date.fromisoformat("2023-02-23")}, DateDict, use_async) == {"foo": "2023-02-23"} # type: ignore[comparison-overlap]
203+
assert await transform(DateModel(foo=date.fromisoformat("2023-02-23")), DateDict, use_async) == {
204+
"foo": "2023-02-23"
205+
} # type: ignore[comparison-overlap]
191206

192207

193208
@parametrize

0 commit comments

Comments
 (0)