@@ -15,19 +15,18 @@ class CacheInstancesMeta(type):
1515 Metaclass to wrap construction in an LRU cache.
1616 """
1717
18- _cache_clear_funcs : dict [type , Callable [[], None ]] = {}
18+ _cached_types : set [type [ 'CacheInstances' ]] = set ()
1919
2020 def __init__ (cls : type [InstanceType ], * args ) -> None : # type: ignore
2121 super ().__init__ (* args )
2222
23- # Define an instance cache attribute and register a cache clear function
24- cls ._instance_cache : Callable | None = None
25- CacheInstancesMeta ._cache_clear_funcs [cls ] = cls ._clear_cache
23+ # Register the cached type
24+ CacheInstancesMeta ._cached_types .add (cls )
2625
2726 def __call__ (cls : type [InstanceType ], # type: ignore
2827 * args , ** kwargs ) -> InstanceType :
2928 if cls ._instance_cache is None :
30- maxsize = getattr ( cls , ' _instance_cache_size' , 128 )
29+ maxsize = cls . _instance_cache_size
3130 cls ._instance_cache = lru_cache (maxsize = maxsize )(super ().__call__ )
3231
3332 args , kwargs = cls ._preprocess_args (* args , ** kwargs )
@@ -38,15 +37,19 @@ def clear_caches(cls: type['CacheInstancesMeta']) -> None:
3837 """
3938 Clear all caches for classes using this metaclass.
4039 """
41- for clear_func in cls ._cache_clear_funcs .values ():
42- clear_func ()
40+ for cached_type in cls ._cached_types :
41+ if cached_type ._instance_cache is not None :
42+ cached_type ._instance_cache .cache_clear ()
4343
4444
4545class CacheInstances (metaclass = CacheInstancesMeta ):
4646 """
4747 Parent class that wraps construction in an LRU cache.
4848 """
4949
50+ _instance_cache : Callable | None = None
51+ _instance_cache_size : int = 128
52+
5053 @classmethod
5154 def _preprocess_args (cls , * args , ** kwargs ):
5255 """
@@ -55,14 +58,6 @@ def _preprocess_args(cls, *args, **kwargs):
5558 """
5659 return args , kwargs
5760
58- @classmethod
59- def _clear_cache (cls ) -> None :
60- """
61- Clears the cache for this class, if any has been initialized.
62- """
63- if cls ._instance_cache is not None :
64- cls ._instance_cache .cache_clear () # type: ignore
65-
6661 @staticmethod
6762 def clear_caches () -> None :
6863 """
0 commit comments