@@ -112,10 +112,12 @@ def __init__(
112112 self .__closed = False
113113 self .__hits = 0
114114 self .__misses = 0
115+ self .__first_loop : Optional [asyncio .AbstractEventLoop ] = None
115116
116117 @property
117118 def __tasks (self ) -> List ["asyncio.Task[_R]" ]:
118- # NOTE: I don't think we need to form a set first here but not too sure we want it for guarantees
119+ # NOTE: I don't think we need to form a set first here but not
120+ # too sure we want it for guarantees
119121 return list (
120122 {
121123 cache_item .task
@@ -124,6 +126,16 @@ def __tasks(self) -> List["asyncio.Task[_R]"]:
124126 }
125127 )
126128
129+ def _check_loop (self , loop : asyncio .AbstractEventLoop ) -> None :
130+ if self .__first_loop is None :
131+ self .__first_loop = loop
132+ elif self .__first_loop is not loop :
133+ raise RuntimeError (
134+ "alru_cache is not safe to use across event loops: this cache "
135+ "instance was first used with a different event loop. "
136+ "Use separate cache instances per event loop."
137+ )
138+
127139 def cache_invalidate (self , / , * args : Hashable , ** kwargs : Any ) -> bool :
128140 key = _make_key (args , kwargs , self .__typed )
129141
@@ -144,6 +156,8 @@ def cache_clear(self) -> None:
144156 self .__cache .clear ()
145157
146158 async def cache_close (self , * , wait : bool = False ) -> None :
159+ loop = asyncio .get_running_loop ()
160+ self ._check_loop (loop )
147161 self .__closed = True
148162
149163 tasks = self .__tasks
@@ -222,6 +236,7 @@ async def __call__(self, /, *fn_args: Any, **fn_kwargs: Any) -> _R:
222236 raise RuntimeError (f"alru_cache is closed for { self } " )
223237
224238 loop = asyncio .get_running_loop ()
239+ self ._check_loop (loop )
225240
226241 key = _make_key (fn_args , fn_kwargs , self .__typed )
227242
@@ -341,7 +356,6 @@ def wrapper(fn: _CBP[_R]) -> _LRUCacheWrapper[_R]:
341356 if not inspect .iscoroutinefunction (origin ):
342357 raise RuntimeError (f"Coroutine function is required, got { fn !r} " )
343358
344- # functools.partialmethod support
345359 if hasattr (fn , "_make_unbound_method" ):
346360 fn = fn ._make_unbound_method ()
347361
0 commit comments