Michel Touw
Michel Touw

Reputation: 626

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.

Upvotes: 8

Views: 7006

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78564

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.

Upvotes: 8

S. de Melo
S. de Melo

Reputation: 856

Because you are calling it here:

return wrapper()

It should be:

return wrapper

Upvotes: 5

Related Questions