3 ms·
Python has context managers, which were added for exactly this purpose. with alloc_resource() as resource: resource.use()
by tstack 11y ago
Python has context managers, which were added for exactly this purpose.
with alloc_resource() as resource:
resource.use()
- czinck 11y agoI mentioned those. They work, but they're just a weak form of RAII without any extra power.
- tstack 11y agoCan you elaborate on "extra power"? A c++ constructor/destructor pair is equivalent to __enter__ and __exit__. I fail to see how this grants a significant amount of power. There's certainly differences, but the gap is probably not as large as your weasel words make it out to be. You complain about having to put initialization into 2 constructors, but there's the flip-side with things like mutexes. In c++, you have to have 2 classes, one for the lock and one for the guard. Whereas with a context-manager, you have one class and the locking code is in the __enter__ and __exit__. with self.lock: self.do_stuff() In that case, I would say that the context-manager is nicer.
- czinck 11y agoI didn't have any example of extra power, just in with blocks you have some downsides compared to RAII but no upsides. By downsides I mean that in C++ you write the constructor/destructor and never worry about it again, but in python every caller has to use a with block, plus what I said above about exceptions being thrown before __enter__. I haven't done much with mutexes, but doesn't having it split over 2 classes introduce a race condition? Seems like a weird way to implement it to me.
- EpicEng 11y agoAgree with @czinck. It works, it does the job, but it's not as fool proof as: { Type obj; // do stuff } // obj destructor just ran C# and other languages have similar paradigms, but they require more attention to detail than a destructor does.