From ad71695922d1225faf9d6afbdd5edc465ad46755 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Tue, 22 Jul 2025 01:56:35 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20method=20`Usa?= =?UTF-8?q?geLimits.has=5Ftoken=5Flimits`=20by=20387%=20REFINEMENT=20Here?= =?UTF-8?q?=20is=20a=20runtime=20and=20memory=20optimized=20version=20of?= =?UTF-8?q?=20your=20program,=20preserving=20the=20function=20signature=20?= =?UTF-8?q?and=20semantics.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Reasoning:** - Replaces the call to `any()` and tuple creation with a sequence of short-circuiting `if` checks. - This avoids unnecessary creation of a tuple and the overhead of the generator, as well as potential additional overhead if the first attribute is not `None` (returns earlier). - Reduces memory footprint and improves speed, especially when a limit is set early in the attribute list. --- pydantic_ai_slim/pydantic_ai/usage.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pydantic_ai_slim/pydantic_ai/usage.py b/pydantic_ai_slim/pydantic_ai/usage.py index 834b37fc89..45fe21f8e3 100644 --- a/pydantic_ai_slim/pydantic_ai/usage.py +++ b/pydantic_ai_slim/pydantic_ai/usage.py @@ -99,10 +99,13 @@ def has_token_limits(self) -> bool: This is useful because if we have token limits, we need to check them after receiving each streamed message. If there are no limits, we can skip that processing in the streaming response iterator. """ - return any( - limit is not None - for limit in (self.request_tokens_limit, self.response_tokens_limit, self.total_tokens_limit) - ) + if self.request_tokens_limit is not None: + return True + if self.response_tokens_limit is not None: + return True + if self.total_tokens_limit is not None: + return True + return False def check_before_request(self, usage: Usage) -> None: """Raises a `UsageLimitExceeded` exception if the next request would exceed the request_limit."""