0

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?

3
  • Absolutely, thanks for flagging it Commented Aug 7, 2020 at 3:13
  • You don't need to put two underscores before and after every def statement in a class, you only need to use them while initialising the class (def __init__(self)). Also, put the (self, parameters) after the two underscores in __init__ Commented Aug 7, 2020 at 3:47
  • 1
    Right, that was only to convey the idea that this could be a somewhat special method. Which is the case with __enter__ and __exit__ Commented Aug 8, 2020 at 2:40

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.