0

I want to add a decorator (with arguments) that keeps the formatting of the input file. I've been trying for few days. Below is the closest that I get and I keep getting the error message: TypeError: keep_formatting() missing 4 required positional arguments: 'func1', 'func2', 'path', and 'file'

def keep_formatting(func1, func2, path, file):
    def decorator(func):
        def wrapper(*args, **kwargs):
            df_first_row = func1(file)
            df_wrapper = func(*args, **kwargs)
            df_content = func2(df_wrapper)
            df_merge = pd.DataFrame(np.concatenate((df_first_row.values, df_content.values)))
            df_merge.to_csv(os.path.join(path, file), index=False)
        return wrapper
    return decorator


class InputFile:
    def __init__(self):
        pass

    @keep_formatting()
    def drop_row(self, file, col):
        df = pd.read_csv('xxx.csv')
        df = df.loc[~(df[col] == some_criteria), :]
        return df

    @keep_formatting()
    def some_other_functions(self, file):
        pass

Here are some of the questions I'm wrapping my head around

  • Did I use the decorator correctly? E.g., put it outside the class and call it above the class methods
  • It seems that I have to define the parameters inside @keep_formatting(). However, how do I keep the last parameter (file) open to changes as the file being passed to the function may be different?

Thanks for your help.

Karma
  • 249
  • 1
  • 4
  • 10
  • You've defined your decorator factory to take 4 positional args, but when you decorate your methods, you do not pass any arguments. – ddejohn Dec 10 '22 at 21:25
  • Can you explain your use-case more clearly? This doesn't strike me as an appropriate use of decorators at first glance. – ddejohn Dec 10 '22 at 21:26
  • Hi @ddejohn, the reason I'm using the decorator is that the csv file formatting is weird. For examples, header is on 2nd row, and final row is a footer. So, I use drop_row and some other functions to manipulate any csv input file while trying to maintain the format using the decorator. – Karma Dec 10 '22 at 21:35
  • Does this answer your question? [Decorators with parameters?](https://stackoverflow.com/questions/5929107/decorators-with-parameters) – Daniil Fajnberg Dec 13 '22 at 12:00

0 Answers0