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?

Adrien Leravat
  • 2,731
  • 18
  • 32
  • Absolutely, thanks for flagging it – Adrien Leravat Aug 07 '20 at 03: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__` – NMrocks Aug 07 '20 at 03: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__` – Adrien Leravat Aug 08 '20 at 02:40

0 Answers0