Can a class own a content manager in python?

  contextmanager, python-3.x

I have a class that manages some shared resources and currently provides a get_X() and put_X() method to access the resources. A better interface for this would be to use a context manager for each resource as in

with ResourceManager.X() as x:
   # do stuff

But my use is a QT5 Widget class that grabs the resource then it gets configured and has to release the resource when the widget is destroyed:

class MyWidget(QtGui.Widgets.QTableWidget):
    def conf(self):
        self.x = ResourceManager.get_x()

    def closeEvent(self, event):
        ResourceManager.put_x()
        super().closeEvent()

So is there a more pythonic way analog to the context manager "with" construct to keep a resource allocated for the livetime of a class?

Note: Qt5 doesn’t allow multiple inheritance

Source: Python-3x Questions

LEAVE A COMMENT