Cache Size Decorators in Python

Viewed 15

I am building my own decorator function, but I can't seem to be able to update the func.cache_length method of the function.

The code below simply uses an OrderedDict to store the items from all the dataframes loaded in pandas, with 5 dataframes maximum stored in cache.

I want the user to also find out how many items currently the function has loaded using cache_length but every time I run it I get 0.

from functools import wraps
from collections import OrderedDict


def cache(func, max_length=5):
    
    func.cache_dict = OrderedDict()
    func.cache_length = 0
    @wraps(func)
    
    def wrapper(*args, **kwargs):
        if kwargs['df_name'] in func.cache_dict:
            return func.cache_dict[kwargs['df_name']]
        elif len(func.cache_dict) < max_length:
            print('Running function...')
            df = func(*args, **kwargs)
            func.cache_dict[kwargs['df_name']] = df
            func.cache_length += 1
            return df
        else:
            func.cache_dict.popitem(last=True)
            df = func(*args, **kwargs)
            func.cache_dict[kwargs['df_name']] = df
            return df
    
    func.cache_reset = lambda: func.cache_dict.clear()
        
    return wrapper


import pandas as pd


@cache
def data_reader(*, df_name: pd.DataFrame, file: str):
    df = pd.read_csv(file)
    return df

This is the output vs. expected (I should get 1),


data_reader(df_name='test_dataframe', file="parsed_data.csv")

>>

Running function...
....


>>

data_reader.cache_length

>>

0

0 Answers
Related