One functionality of python that I found very handy when working with databases (or files) are the __enter__ and __exit__ functions you can give to a class. Now by using the with statement you can make sure that in this block __enter__ is first called (and you can open the database or file) and after it’s done __exit__ is called (and you can close a database or file.
I want to open and close a sqlite transaction every time a function from my Database class is called. I can do it at the start and end of every function, but since it has to be done for every function is that class, I was wondering, are there methods that get called before and after each function call? Like SetUp and TearDown in unittesting.
You can decorate every member function with a pie decorator, something like
and transaction is a decorator you define to wrap the function with a pre and post.
Yes, you have to do it for every function. Here is an example
.
The alternative is that you use a metaclass, like this:
This is pure black magic, but it works
You normally don’t want to decorate the
__init__, and you may want to decorate only those methods with a special name, so you may want to replacewith something like
This way, only methods called trans_whatever will be transactioned.