Skip to content

Conversation

sydney-runkle
Copy link
Contributor

@sydney-runkle sydney-runkle commented Dec 14, 2024

Fix #248

While using _LazyTypeAdapter is slightly faster, I think both operations are fast enough that we should use the recommended defer_build pattern here:

from pydantic import TypeAdapter, ConfigDict
from typing_extensions import TypedDict
from typing import TYPE_CHECKING
import time

if TYPE_CHECKING:
    LazyTypeAdapter = TypeAdapter
else:

    class LazyTypeAdapter:
        __slots__ = '_args', '_kwargs', '_type_adapter'

        def __init__(self, *args, **kwargs):
            self._args = args
            self._kwargs = kwargs
            self._type_adapter = None

        def __getattr__(self, item):
            if self._type_adapter is None:
                self._type_adapter = TypeAdapter(*self._args, **self._kwargs)
            return getattr(self._type_adapter, item)


class MyTD(TypedDict):
    a: int
    b: str
    c: bool


start1 = time.time()
ta1 = LazyTypeAdapter(list[MyTD])
end1 = time.time()
print(end1 - start1)
# > 1.1920928955078125e-06

start2 = time.time()
ta2 = TypeAdapter(list[MyTD], config=ConfigDict(defer_build=True))
end2 = time.time()
print(end2 - start2)
# > 1.6927719116210938e-05
# > Note: without defer_build, 0.14297986030578613

Copy link

cloudflare-workers-and-pages bot commented Dec 14, 2024

Deploying pydantic-ai with  Cloudflare Pages  Cloudflare Pages

Latest commit: 2c50868
Status: ✅  Deploy successful!
Preview URL: https://3277ebed.pydantic-ai.pages.dev
Branch Preview URL: https://defer-build-ta.pydantic-ai.pages.dev

View logs

Copy link
Member

@samuelcolvin samuelcolvin left a comment

Choose a reason for hiding this comment

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

otherwise LGTM.

@samuelcolvin samuelcolvin merged commit d3b7f2d into main Dec 14, 2024
14 checks passed
@samuelcolvin samuelcolvin deleted the defer-build-ta branch December 14, 2024 16:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Potentially Remove _LazyTypeAdapter structure from messages.py
2 participants