A problem with opening a file -- again

Chris Angelico rosuav at gmail.com
Mon Nov 30 14:02:49 EST 2020


On Tue, Dec 1, 2020 at 5:36 AM Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
>         Off-hand, since you aren't explicitly using "del lf" it means that
> __del__() is being called during the process shutdown. Thing is, there is
> no guarantee during shutdown of when things are deleted. There is a faint
> possibility that the internal "module" that contains the built-in "open"
> could be marked unavailable before your "lf" object is deleted.
> ...
>         HOWEVER! YOU DO STILL HAVE THE PROBLEM THAT __del__() is relying on
> features that might not be available if it is invoked as part of process
> shutdown! You MUST explicitly "del" the object to have any chance that it
> runs properly.
>

Be aware that "del lf" does NOT guarantee that lf.__del__() will be
called. The __del__ method is only called when the object is no longer
referenced anywhere, and there are certain situations where it might
not be called even then (during interpreter shutdown, for instance;
and I think some Pythons don't guarantee that __del__ will be called
when breaking a reference loop, but don't quote me on that). You
absolutely cannot rely on __del__ for this kind of thing, hence the
general consensus that a context manager is the way to do it.

ChrisA


More information about the Python-list mailing list