Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python decorator logger

I have the following code:

def log(func):
    def wrapper(*args, **kwargs):
        func_str = func.__name__
        args_str = ', '.join(args)
        kwargs_str = ', '.join([':'.join([str(j) for j in i]) for i in kwargs.iteritems()])
        with open('log.txt', 'w') as f:
            f.write(func_str)
            f.write(args_str)
            f.write(kwargs_str)
        return func(*args, **kwargs)
    return wrapper()


@log
def example(a, b):
    print('example')

However, even without calling any function, I still get the error:

TypeError: example() takes exactly 2 arguments (0 given)

Can someone explain to me why this happens, because it seems the function is called, but I don't understand why.

like image 989
Michel Touw Avatar asked Oct 12 '16 09:10

Michel Touw


1 Answers

You should return the wrapper function without calling it:

return wrapper

Calling it implies the call to wrapper has to be evaluated, which you're however calling with the wrong signature.

like image 106
Moses Koledoye Avatar answered Sep 22 '22 01:09

Moses Koledoye