Search code examples
pythondataframepython-decorators

'DataFrame' object is not callable error when using Decorator wrapper for run time


I am trying to return a csv file and using decorator for finding the running time. (The following code is the sample code for the same. ) But I am getting an error it is "'DataFrame' object is not callable "

import pandas as pd
import time
import functools

def timer(func):
    @functools.wraps(func)
    def wrapper_timer():
        start_time = time.perf_counter()  
        value = func()
        end_time = time.perf_counter()  
        run_time = end_time - start_time  
        print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
        return value
    return wrapper_timer()


@timer
def generate_df():
    file="file.csv"
    df = pd.read_csv(file)
    return df
df = generate_df()


if __name__ == '__main__':
    print(df.head())

Solution

  • You should be returning the function reference in the decorator

    return wrapper_timer
    

    Rather than calling it.

    A better way to write the code,

    import pandas as pd
    from time import time
    import functools
    
    
    def timer(func):
        @functools.wraps(func)
        def wrapper_timer(*args, **kwargs):
            start_time = time()
            value = func(*args, **kwargs)
            run_time = time() - start_time  
            print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
            return value
        return wrapper_timer
    
    
    @timer
    def generate_df(file):
        df = pd.read_csv(file)
        return df
    
    
    if __name__ == '__main__':
        filepath = "/home/vishnudev/Downloads/CF-Event-equities-21-Feb-2021.csv"
        df = generate_df(filepath)
        print(df.head())