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?
def __init__(self)). Also, put the(self, parameters)after the two underscores in__init____enter__and__exit__