Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do commit after method execution - decorator

I'm new in decorators and I'm trying to create one, which do self.commit() after the method is executed.

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

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

I made a testing method:

@commit
def h(self):
    pass

And calling it:

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

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

I do know that the error is being raised because it is not a static method, so I tried to put there self argument but still errors are appearing.

Do you know where is the problem?

like image 973
Milano Avatar asked Dec 03 '25 11:12

Milano


1 Answers

You build decorators for methods the same way as for functions, but you need to take the self into consideration of 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 could be done by putting *args and **kwargs as parameters for the wrapper, so it can accept any arbitrary number of arguments and keyword arguments.

Hope this helps :)

like image 77
elegent Avatar answered Dec 05 '25 01:12

elegent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!