4 ms·
What would be the advantage over just having your __del__ method do the cleanup directly (rather than using a context manager)? You still suffer from most of th
by ali_m 8y ago
What would be the advantage over just having your __del__ method do the cleanup directly (rather than using a context manager)? You still suffer from most of the disadvantages of using __del__ - you have very few guarantees about when it will be called (if at all), and it may render your object un-garbage-collectable if there are cyclic references.
- mlthoughts2018 8y agoIn cases of resource cleanup you often (not always) don’t care so much about deterministic destruction, because holding onto the resource is not acting as a bottleneck and doesn’t lead to any performance or resource problem. In such a case, there’s a big win to avoiding writing custom destructor logic that adds complexity and requires more testing and so on. If you can use something super simple, like a context manager decorator or a simple generator function with a context manager inside, and the destructor logic is basically just “call close()” to trigger the implicit cleanup of the context manager, it’s often worth it. You aren’t writing much logic to specially process a “close” operation.. you’re just electing to let the thing containing the context manager go out of scope. But I do agree in a case where, for example, leaving many open connections to a resource would create a resource limit or bottleneck, then ensuring it happens deterministically is probably important.