Hacker News new | ask | show | jobs
by dist-epoch 171 days ago
Python has that too, it's called a context manager, basically the same thing as C++ RAII.

You can argue that RAII is more elegant, because it doesn't add one mandatory indentation level.

2 comments

It's not the same thing at all because you have to remember to use the context manager, while in C++ the user doesn't need to write any extra code to use the destructor, it just happens automatically.
To be fair, that's just an artifact Python's chosen design. A different language could make it so that acquiring the object whose context is being managed could require one to use the context manager. For example, in Python terms, imagine if `with open("foo") as f:` was the only way to call `open`, and gave an error if you just called it on its own.
How do you return a file in the happy path when using a context manager?

If you can't, it's not remotely "basically the same as C++ RAII".