3 ms·
To people who don’t like __del__: what do you do to protect resources when people forget to use with statement? Are there any good pattern for using __exit__ wi
by sytelus 8y ago
To people who don’t like __del__: what do you do to protect resources when people forget to use with statement? Are there any good pattern for using __exit__ with __del__?
- blattimwind 8y ago> what do you do to protect resources when people forget to use with statement? In many cases it is perfectly reasonable to only allow context manager use. And if it isn't possible, offer explicit close() or dispose() interfaces, don't rely on __del__.
- wwright 8y agoThere's a really simple and easy solution in the standard library, but like many things in Python, it's not the first solution you're usually shown: `contextlib.contextmanager` [1]. This API cleanly separates the "context manager" part of your code from the "context" part. The result of calling your function is only a context manager, with no side effects. Using `with` on that context manager yields your actual object :-) Very simple usage: from contextlib import contextmanager @contextmanager def my_context(...): print("Started") try: yield 5 finally: print("Finished") # Calling the function alone does nothing >>> my_context() <contextlib._GeneratorContextManager object at 0x10de07588> # Using `with` runs our side effects >>> with my_context() as context: ... print(context) ... Started 5 Finished [1]: https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager https://docs.python.org/3/library/contextlib.html#contextlib...
- emidln 8y agoIt's not my responsibility as a library author to protect users from themselves. If they have leaks because they refuse to use my API then so be it. If you don't want to use with, you're free to call __enter__() and __exit__() yourself in a way you see fit.