Skip to content

Store elapsed time on stream wrapper to avoid reference cycles#948

Open
mbeijen wants to merge 1 commit into
pydantic:mainfrom
mbeijen:no-weakref
Open

Store elapsed time on stream wrapper to avoid reference cycles#948
mbeijen wants to merge 1 commit into
pydantic:mainfrom
mbeijen:no-weakref

Conversation

@mbeijen
Copy link
Copy Markdown
Contributor

@mbeijen mbeijen commented May 16, 2026

Instead of holding a reference back to the Response in BoundSyncStream/ BoundAsyncStream (which creates a reference cycle), store the elapsed timedelta on the stream itself after close. Response.elapsed reads it back from self.stream via duck typing, falling back to a directly-set _elapsed value for cases like mocking.

This avoids creating reference cycles that can result in significant extra memory usage.

It's an alternative approach to encode/httpx#3733 and I prefer my approach, because it does not use references at all (no weakref).

Instead of holding a reference back to the Response in BoundSyncStream/
BoundAsyncStream (which creates a reference cycle), store the elapsed
timedelta on the stream itself after close. Response.elapsed reads it
back from self.stream via duck typing, falling back to a directly-set
_elapsed value for cases like mocking.

This avoids creating reference cycles that can result in significant
extra memory usage.

It's an alternative approach to encode/httpx#3733
 and I prefer my approach, because it does not use references at all
(no weakref).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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.

1 participant