Make a commit after executing a method - decorator

I am new to decorators and I am trying to create one that executes self.commit()

after the method is executed.

I have a problem with arguments. The commit method (decorator) is inside the class.

def commit(func):
    def func_wrapper(func):
        func()
        self.commit()
    return func_wrapper   

      

I made a test method:

@commit
def h(self):
    pass

      

And calling it:

db = database()
db.create_tables()
db.h()

      

MISTAKE: TypeError: commit() takes exactly 2 arguments (1 given)

I know the error comes from the fact that it is not a static method, so I tried to put an argument in there self

, but errors still appear.

Do you know where the problem is?

+3


source to share


3 answers


You create decorators for methods in the same way as for functions, but you need to take self

into account the wrapper function
:

def commit(func):
    def func_wrapper(self):
        func(self)
        self.commit()
    return func_wrapper

      




Update:

A better approach would be to make the decorator useful for functions and methods . This can be done by supplying *args

and **kwargs

as parameters to the shell so that it can take any arbitrary number of arguments and keyword arguments.

Hope it helps :)

+1


source


You need to pass the actual argument to the wrapper function and call the decorated function with that argument:



def commit(func):
    def func_wrapper(self):
        func(self)
        self.commit()
    return func_wrapper

      

+1


source


You need to pass arguments to the function as previous posts said. But you most likely do not want to limit the arguments that performs a function in your decorator, use for this *args

, **kwargs

. Finally, it is recommended to use functools.wraps to preserve the original function metadata.

Complete example:

from functools import wraps

def commit(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        func(self, *args, **kwargs)
        self.commit()
    return wrapper

      

+1


source







All Articles