Cached class properties/methods (cached)#

Routines to define cached properties/methods in a class.

Functions:

decorate(*[, key, check_use_cache, as_property])

General purpose cached decorator.

prop([func, key, check_use_cache])

Decorator to cache a property within a class.

meth([func, key, check_use_cache])

Decorator to cache a function within a class

clear(key_or_func, *keys)

Decorator to clear self._cache of specified properties

Classes:

CachedProperty(prop[, key, check_use_cache])

Simplified version of property with typing.

module_utilities.cached.decorate(*, key=None, check_use_cache=False, as_property=True)[source]#

General purpose cached decorator.

Must always be called.

module_utilities.cached.prop(func=None, /, *, key=None, check_use_cache=False)[source]#

Decorator to cache a property within a class.

Parameters:
  • func (callable()) – This parameter is used in the case that you decorate without (). That is, you can decorate with @prop or @prop(). Positional only.

  • key (string, optional) – Optional key for storage in _cache. Default to attribute/method __name__. Keyword only.

  • check_use_cache (bool, default False) – If True, then only apply caching if self._use_cache = True. Note that the default value of self._use_cache is False. If False, then always apply caching. Keyword only.

Notes

To set key or check_use_cache, must pass with keyword.

Examples

>>> class A:
...    def __init__(self):
...        # this isn't strictly needed as it will be created on demand
...        # but should be included if using static typing (mypy, etc)
...        self._cache = {}
...
...    @prop(key='keyname')
...    def size(self):
...        '''
...        This code gets ran only if the lookup of keyname fails
...        After this code has been ran once, the result is stored in
...        _cache with the key: 'keyname'
...        '''
...        print('set size')
...        return [10]
...
...    #no arguments implies give cache function name
...    @prop
...    def myprop(self):
...        print('set myprop')
...        return [1.0]
...
...    @prop(check_use_cache=True)
...    def checker(self):
...        print('set checker')
...        return [2.0]
>>> x = A()
>>> x.size
set size
[10]
>>> x._cache['keyname'] is x.size
True
>>> x.size
[10]
>>> x.myprop
set myprop
[1.0]
>>> x._cache['myprop'] is x.myprop
True
>>> x.myprop
[1.0]

If you pass check_use_cache=True and either _use_cache=False or the instance doens’t have That property, then caching will NOT be done.

>>> x.checker
set checker
[2.0]
>>> x.checker
set checker
[2.0]

See also

clear

corresponding decorator to clear cache

meth

decorator for cache creation of function

module_utilities.cached.meth(func=None, /, *, key=None, check_use_cache=False)[source]#

Decorator to cache a function within a class

Requires the Class to have a cache dict called _cache.

Examples

>>> class A(object):
...    @meth(key='key')
...    def method(self, x, y=2):
...        # This code gets ran only if the lookup of keyname fails
...        # After this code has been ran once, the result is stored in
...        # _cache with the key: 'keyname'
...        # a long calculation....
...        print('calling method')
...        return [x, y]
...
...
>>> x = A()
>>> x.method(1, 2)
calling method
[1, 2]

This will respect default params

>>> x.method(1)
[1, 2]

And keyword arguments

>>> x.method(y=2, x=1)
[1, 2]
>>> print(x._cache)
{'key': {((1, 2), frozenset()): [1, 2]}}

See also

clear

corresponding decorator to remove cache

prop

decorator for properties

module_utilities.cached.clear(key_or_func, *keys)[source]#

Decorator to clear self._cache of specified properties

Parameters:

*keys – Remove these keys from cache. if len(keys)==0, remove all keys.

Examples

>>> class Example:
...    @prop
...    def a(self):
...        print('calling a')
...        return 'a'
...
...    @prop
...    def b(self):
...        print('calling b')
...        return 'b'
...
...    @clear
...    def method_that_clears_all(self):
...        pass
...
...    @clear('a')
...    def method_that_clears_a(self):
...        pass
>>> x = Example()
>>> x.a, x.b
calling a
calling b
('a', 'b')
>>> x.a, x.b
('a', 'b')
>>> x.method_that_clears_all()
>>> x.a, x.b
calling a
calling b
('a', 'b')
>>> x.a, x.b
('a', 'b')
>>> x.method_that_clears_a()
>>> x.a, x.b
calling a
('a', 'b')

See also

prop

corresponding decorator for cache creation of property

meth

decorator for cache creation of function

class module_utilities.cached.CachedProperty(prop, key=None, check_use_cache=False)[source]#

Bases: Generic[S, R]

Simplified version of property with typing.

Examples

>>> class Example:
...     def __init__(self):
...         self._cache: dict[str, Any] = {}
...
...     def prop(self) -> int:
...         print("calling prop")
...         return 1
...
...     prop = CachedProperty(prop, key="hello")
...
>>> x = Example()
>>> print(x.prop)
calling prop
1
>>> print(x.prop)
1