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(arg1, arg2):
return [arg1, arg2]
myfunc(1,2) # cache miss
myfunc(1,2) # cache hit
myfunc(2,3) # cache miss
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!"