• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How to wrap each method in a class with a context manager?

Resolved: How to wrap each method in a class with a context manager?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have a class Class, that has a certain number of methods. I want to wrap each of those methods with a context manager, such that when calling Class().foo, it will run Class.foo 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

Answer:

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!

methods python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to set consistent decimal separators in R data frame?

26/03/2023

Resolved: How to resolve LNK2001 in c++ projects

26/03/2023

Resolved: How to correctly initialize vector of number in Typescript

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.