Skip to content
This repository was archived by the owner on Mar 26, 2026. It is now read-only.

Commit c25fb2b

Browse files
committed
change logic of cache
1 parent 9ebb566 commit c25fb2b

1 file changed

Lines changed: 9 additions & 22 deletions

File tree

gapic/utils/cache.py

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import functools
1616
import contextlib
17-
from contextvars import ContextVar
17+
import threading
1818
from typing import Dict, Optional, Any
1919

2020

@@ -48,33 +48,20 @@ def inner(self):
4848
return property(inner)
4949

5050

51-
# 1. The ContextVar (Default is None)
52-
# This replaces threading.local with the async-safe standard.
53-
generation_cache: ContextVar[Optional[Dict[Any, Any]]] = ContextVar(
54-
"generation_cache", default=None
55-
)
56-
57-
# Optimization: Bind .get for speed
58-
_get_cache = generation_cache.get
51+
# Thread-local storage for the simple cache dictionary
52+
_thread_local = threading.local()
5953

6054

6155
@contextlib.contextmanager
6256
def generation_cache_context():
63-
"""Context manager to explicitly manage the cache lifecycle.
64-
65-
Usage:
66-
with generation_cache_context():
67-
# Cache is active (fast)
68-
...
69-
"""
70-
# Initialize: Create a new dictionary and set it in the ContextVar
71-
token = generation_cache.set({})
57+
"""Context manager to explicitly manage the cache lifecycle."""
58+
# Initialize the cache as a standard dictionary
59+
_thread_local.cache = {}
7260
try:
7361
yield
7462
finally:
75-
# Cleanup: Reset the ContextVar to its previous state (None)
76-
# This allows the dictionary to be garbage collected.
77-
generation_cache.reset(token)
63+
# Delete the dictionary to free all memory and pinned objects
64+
del _thread_local.cache
7865

7966

8067
def cached_proto_context(func):
@@ -84,7 +71,7 @@ def cached_proto_context(func):
8471
def wrapper(self, *, collisions, **kwargs):
8572
# 1. Initialize cache if not provided (handles the root call case)
8673

87-
context_cache = _get_cache()
74+
context_cache = getattr(_thread_local, "cache", None)
8875
if context_cache is None:
8976
return func(self, collisions=collisions, **kwargs)
9077

0 commit comments

Comments
 (0)