A problem with opening a file -- again
Eryk Sun
eryksun at gmail.com
Sun Nov 29 18:17:25 EST 2020
On 11/29/20, Chris Angelico <rosuav at gmail.com> wrote:
>
> This seems like a really REALLY bad idea. You're putting a lot of work
> into your __del__ function, and that's not getting called until
> everything's shutting down. (Also, xrange doesn't exist, hence the
> "exception ignored" thing.)
>
> Avoid putting this sort of work into __del__ by explicitly marking
> that you're done with the object. A context manager is a good choice
> here.
The documentation of the __del__() finalizer contains the following warning:
__del__() can be executed during interpreter shutdown. As a consequence,
the global variables it needs to access (including other modules) may
already have been deleted or set to None.
A finalizer can locally reference required globals and builtins as the
default value of keyword-only arguments, e.g. __del__(self, *,
open=open). But in this case I second the suggestion to make the
object a context manager with __enter__() and __exit__() methods.
More information about the Python-list
mailing list