A problem with opening a file -- again

Chris Angelico rosuav at gmail.com
Sun Nov 29 16:42:35 EST 2020


On Mon, Nov 30, 2020 at 8:37 AM Gabor Urban <urbangabo at gmail.com> wrote:
> class Naplo:
>     def __del__(self):
>         if self.sor != 0:
>             if self.start:
>                 trc = open(self.logNev,self.startMode)
>             else:
>                 trc = open(self.logNev,self.mode)
>             for idx in xrange(self.meret):
>                 trc.write(self.puffer[idx])
>             trc.close()
>

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.

ChrisA


More information about the Python-list mailing list