Skip to content

Instantly share code, notes, and snippets.

@maharjun
Created May 4, 2023 11:26
Show Gist options
  • Save maharjun/459c36ce878af5168e83e79c025cf5a9 to your computer and use it in GitHub Desktop.
Save maharjun/459c36ce878af5168e83e79c025cf5a9 to your computer and use it in GitHub Desktop.
Cached class method decorator
"""
The cached_class_method utility is a Python function decorator that caches the
results of a class method in order to avoid recomputing the same values when the
method is called multiple times with the same arguments. It does so by storing the
results in a cache dictionary as an attribute of the class instance, and looking
them up whenever the method is called with the same arguments.
"""
###############################################################################
# BSD 3-Clause License
#
# Copyright (c) 2023, maharjun
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
import inspect
from contextlib import wraps
def cached_class_method(func):
"""
A decorator for caching the results of class methods.
This decorator caches the results of class methods based on their input arguments,
avoiding the recomputation of values when the method is called multiple times
with the same arguments. The cache is stored as a dictionary attribute of the
class instance.
Parameters
----------
func : callable
The class method to be decorated.
Returns
-------
callable
The decorated class method with caching functionality.
Raises
------
TypeError
If the arguments to the function are not hashable, making caching impossible.
Examples
--------
>>> class MyClass:
... @cached_class_method
... def expensive_operation(self, x, y):
... # Perform some expensive computation
... result = x * y + x ** y
... return result
...
>>> my_instance = MyClass()
>>> result1 = my_instance.expensive_operation(2, 3) # Cache miss, performs the expensive operation
>>> result2 = my_instance.expensive_operation(2, 3) # Cache hit, returns the cached result
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
callargs = inspect.getcallargs(func, self, *args, **kwargs)
cache_name = f'_{func.__name__}'
cache_key = tuple(sorted(callargs.items()))
try:
if not hasattr(self, cache_name):
setattr(self, cache_name, {})
cache_dict = getattr(self, cache_name)
if not cache_key in cache_dict:
cache_dict[cache_key] = func(self, *args, **kwargs)
return cache_dict[cache_key]
except TypeError as E:
if 'unhashable' in E.args[0]:
raise TypeError('The arguments to the function were not hashable making cacheing impossible')
else:
raise E
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment