Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: cache TypeAdapters #1114

Merged
merged 7 commits into from
Mar 18, 2024
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/openai/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,15 @@ class GenericModel(BaseGenericModel, BaseModel):


if PYDANTIC_V2:
from pydantic import TypeAdapter
from functools import lru_cache

from pydantic import TypeAdapter as PyTypeAdapter

def TypeAdapter(type_: type[_T]) -> PyTypeAdapter[_T]:
return PyTypeAdapter(type_)

if not TYPE_CHECKING:
TypeAdapter = lru_cache(TypeAdapter)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I think this conveys the intent of this code more clearly (and you can add the lru_cache import at the top of the file), thoughts?

Suggested change
from pydantic import TypeAdapter as PyTypeAdapter
def TypeAdapter(type_: type[_T]) -> PyTypeAdapter[_T]:
return PyTypeAdapter(type_)
if not TYPE_CHECKING:
TypeAdapter = lru_cache(TypeAdapter)
if TYPE_CHECKING:
from pydantic import TypeAdapter
else:
from pydantic import TypeAdapter as _TypeAdapter
TypeAdapter = lru_cache(TypeAdapter)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, It has been modified.


def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
return TypeAdapter(type_).validate_python(value)
Expand Down