4 ms·
It's beauty in the sense that it is addressing a language deficiency ("destructor" behavior, awkwardness of the "with" construct) with a library, sure, but this
by ctur 6y ago
It's beauty in the sense that it is addressing a language deficiency ("destructor" behavior, awkwardness of the "with" construct) with a library, sure, but this is ultimately working around a gap in Python itself.
- xapata 6y agoI'd argue the context manager concept is better than destructors, because it's more explicit. BTW, Python does have the `__del__` special method. It's just that almost all usage of it would be better implemented via context manager.
- bobbyi_settv 6y agoI think the idiomatic way is with weakref https://docs.python.org/3/library/weakref.html https://docs.python.org/3/library/weakref.html Particularly note "finalize provides a straight forward way to register a cleanup function to be called when an object is garbage collected"
- ctur 6y agoThat's a little snarkier than I intended. It is good to share this method of handling what is otherwise very awkward code. It just is unfortunate the language itself doesn't have constructs that lend to proper syntactically scalable resource handling other than nested "with" blocks.
- MereInterest 6y agoAgreed. I like Python, and I think ExitStack is a fantastic way to manage resources. However, that is because it most closely emulates RAII in C++. The limitation that I still run into is when a class needs to have some cleanup code added to it. In C++, you just add a destructor. In Python, you are forced to choose between non-deterministic release of resources through __del__, or changing the interface by requiring users to use a "with" block. Neither of those is a particularly satisfying option.
- xapata 6y agoThe need to add cleanup code is a change to the interface. If you don't change the interface, you've left yourself open to bugs around accidentally using an instance after it's been cleaned. If you really want to keep the same interface, add a layer of abstraction. The current interface becomes a wrapper around the underlying context manager.
- MereInterest 6y agoExactly. The language design of Python means that the addition of cleanup code is an API change. The language design of C++ means that the addition of cleanup code is not an API change.
- deleted 6y ago[deleted]
- deleted 6y ago[deleted]
- xapata 6y agoI actually appreciate that API change, as it makes my use of resources more explicit. However, you might be interested in using ``weakref.finalize`` to keep that C++ style. https://docs.python.org/3.6/library/weakref.html#comparing-finalizers-with-del-methods https://docs.python.org/3.6/library/weakref.html#comparing-f...
- epage 6y agoimo the main benefit to context manager is reporting errors during cleanup while the main benefit of RAII/destructors is composability.