Examples
The function block below illustrates basic usage of the function cacher.
Minimal Example
from functionCacher.Cacher import Cacher
cacher_instance = Cacher()
@cacher_instance.cache
def myfunc(*args):
print(f"myfunc is getting called with {args}")
return args
print(myfunc(1,2,3)) # cache miss; prints "myfunc is getting..."
print(myfunc(1,2,3)) # cache hit ; prints nothing
print(myfunc(2,3,4)) # cache miss; prints "myfunc is getting..."
print(f"Cache path is: {cacher_instance.cachePath}")
Extended Configuration
import datetime
from functionCacher.Cacher import Cacher, CompressionType
cacher_instance = Cacher(
cachePath="/path/to/cacheDirectory",
cacheFolder="caches",
compressionType=CompressionType.ZSTD,
maxCacheAge=datetime.timedelta(days=1),
hmac_key=b"super-secure-hmac-key")
@cacher_instance.cache
def myfunc(*args):
print(f"myfunc is getting called with {args}")
return args
print(myfunc(1,2,3)) # cache miss; prints "myfunc is getting..."
print(myfunc(1,2,3)) # cache hit ; prints nothing
print(myfunc(2,3,4)) # cache miss; prints "myfunc is getting..."
print(f"Cache path is: {cacher_instance.cachePath}")
Data-base code
from functionCacher.Cacher import Cacher
cacher_instance = Cacher()
import psycopg2
_conn = psycopg2.connect(**_connection_settings)
@cacher_instance.Cache.cache(exclude_kwargs=["conn"])
def execute(conn, query: str, var = None):
cur = conn.cursor()
cur.execute(_query, vars)
return cur.fetchall()
result = execute(_conn, "select mycol from mytable") # cache miss
result = execute(_conn, "select mycol from mytable") # cache hit
Note: The decorated function execute contains the parameter conn, which refers to the psycopg2 database connection handle. This handle contains several connection-specific parameters and will almost always lead to a different hash on consecutive executions. Therefore we use the decorator parameter exclude_kwargs to specifically exclude this parameter from cache ID generation. Hence only query and var are considered for the parameter hash.
Capture cache feedback
from functionCacher.Cacher import Cacher
cacher_instance = Cacher()
def response_callback(did_hit: bool):
print(f"Cache {'hit' if did_hit else 'miss'}!")
@cacher_instance.cache(cache_response_callback=response_callback)
def myfunc(arg1, arg2):
return [arg1, arg2]
myfunc(1,2) # will print "Cache miss!"
myfunc(1,2) # will print "Cache hit!"
myfunc(2,3) # will print "Cache miss!"