I have a class
, that has a certain number of methods. I want to wrap each of those methods with a context manager, such that when calling
, it will run
in the context. Here’s the code I have so far:
I’m planning on calling this function (but defined before) at the end of a class definition, so after all the methods are defined
Here is a metaclass version:
You could also do away with the context manager and have the same thing just in the decorator definition, i.e.:
One advantage of the metaclass version is that the work to decorate the methods of the class happens only once, at “import time”, instead of each time you make an instance. So that would be a little more efficient if you are making lots of instances and there are many methods to decorate.
If you have better answer, please add a comment about this, thank you!