Coming from C++, I have been using constructor/destructors to perform RAII-like wrappers. So a local object that goes out of scope (e.g. end of a function) would have its destructor immediately called, which can be used to unlock a mutex, free a resource, or perform some deinitialization immediately.
Is there a pythonic way to do the same?
class DoSomethingWhenDone:
def __init(self)__:
pass
def __out_of_scope__(self):
# Do something!
def foo():
obj = DoSomethingWhenDone()
# Magic happens ...
# <= Ensure __out_of_scope__() is called here
It seems with file.open(...) as f:
is doing something like that?