Several class instances of MyClass
share a single resource. The resource should be acquired automatically with the creation of the first instance and released automatically when the last instance is deleted.
Normally, with
is the pythonic way to acquire a resource, but here I don’t see how to proceed, unless I manually acquire the resource instead of leaving the machinery to MyClass
:
with Resource() as r:
a1 = MyClass(resource=r)
a2 = MyClass(resource=r)
...
Intuitively, I would use a singleton with a destructor but I don’t understand Python destructors (they’re not always called when expected unlike in C++) and every single piece of advice around is “don’t use them”.
What’s the correct way?
1