-
-
Notifications
You must be signed in to change notification settings - Fork 65
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
"""Caching. | ||
Custom caching function to be used with class methods. | ||
""" | ||
|
||
__cache = {} | ||
|
||
|
||
def cache(f): | ||
"""Decorator for caching the result of a function.""" | ||
|
||
def cached_f(self, *args, **kwargs): | ||
global __cache | ||
key = f"{args} {kwargs}" | ||
if self not in __cache[f.__name__]: | ||
__cache[f.__name__][self] = {} | ||
if key not in __cache[f.__name__][self]: | ||
__cache[f.__name__][self][key] = f(self, *args, **kwargs) | ||
return __cache[f.__name__][self][key] | ||
|
||
return cached_f | ||
|
||
|
||
def initialise_cache(function_name: str): | ||
"""Initialise a cacge for a given function.""" | ||
global __cache | ||
__cache[function_name] = {} | ||
|
||
|
||
def empty_cache(function_name: str): | ||
"""Remove the cache for a given function.""" | ||
global __cache | ||
del __cache[function_name] |