3 ms·
To me, insisting on using `__del__` is just a sign of someone trying to write C++ in Python. If cleanup needs to happen, the Pythonic way is to make the lifetim
by gvx 8y ago
To me, insisting on using `__del__` is just a sign of someone trying to write C++ in Python. If cleanup needs to happen, the Pythonic way is to make the lifetime of a resource explicit with a context manager. In the cases where that doesn't make sense, there is usually nothing to explicitly clean up anyway.
I honestly don't remember ever having to write a __del__ method in the decade I've been using Python.
- syllogism 8y agoContext managers change the API a lot though. If the resource cleanup is an implementation detail like freeing a handle to some C data, it's much better to do that in a __del__ method.
- wwright 8y agoIf context managers have changed your API, then the context of the resources is no longer an implementation detail; the lifetime of your object and the lifetime of your resources are linked.
- uryga 8y ago> If cleanup needs to happen, the Pythonic way is to make the lifetime of a resource explicit with a context manager. in some cases resources are long-lived and not possible to enclose in a context manager. as an example, a while ago i wrote some PyOpenGL cide and wanted to automatically release some temp GPU buffers when no longer needed. however, they had to live for multiple iterations of the app's main loop, so a context manager wouldn't work – __del__ was the best place to release them.
- uryga 8y agoto be fair though, __del__ did cause problems. when the app was exiting, PyOpenGL would release the GL context before my buffers were __del__'ed, so the __del__s tried to free a buffer that stopped existing and crashed. it'd be nice if those methods were called at a predictable time and not "sometime after the object's RC drops to zero, maybe".
- nerdponx 8y agoCan an object safely call del on itself from inside __exit__?