Skip to content

Commit 9e7e0ff

Browse files
committed
misc: Fix local cache initialization
1 parent e182032 commit 9e7e0ff

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

devito/tools/memoization.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,21 +38,28 @@ def _get_cache(self, obj: InstanceType) -> dict[Hashable, ReturnType]:
3838
it if necessary.
3939
"""
4040
# Try-catch is theoretically faster on the happy path
41+
_local: local
4142
try:
42-
# Attempt to access the cache directly
43-
return obj._memoized_meth__local.cache
43+
# Attempt to access the thread-local data
44+
_local = obj._memoized_meth__local
4445

4546
# If the cache doesn't exist, initialize it
4647
except AttributeError:
4748
with self._lock:
4849
# Check again in case another thread initialized outside the lock
49-
if not hasattr(obj, '_memoized_cache'):
50-
# Initialize the cache if it doesn't exist
50+
if not hasattr(obj, '_memoized_meth__local'):
51+
# Initialize the local data if it doesn't exist
5152
obj._memoized_meth__local = local()
52-
obj._memoized_meth__local.cache = {}
5353

54-
# Return the cache
55-
return obj._memoized_meth__local.cache
54+
# Get the thread-local data
55+
_local = obj._memoized_meth__local
56+
57+
# Local data is initialized; create or retrieve the cache
58+
try:
59+
return _local.cache
60+
except AttributeError:
61+
_local.cache = {}
62+
return _local.cache
5663

5764
def __call__(self, obj: InstanceType,
5865
*args: ParamsType.args, **kwargs: ParamsType.kwargs) -> ReturnType:
@@ -179,7 +186,7 @@ def _get_cache(self, obj: InstanceType) -> dict[Hashable, SafeTee[YieldType]]:
179186
except AttributeError:
180187
with self._lock:
181188
# Check again in case another thread initialized outside the lock
182-
if not hasattr(obj, '_memoized_cache'):
189+
if not hasattr(obj, '_memoized_generator__cache'):
183190
# Initialize the cache if it doesn't exist
184191
obj._memoized_generator__cache = {}
185192

0 commit comments

Comments
 (0)