does python have useless destructors?

John J. Lee jjl at pobox.com
Sun Jun 13 14:44:36 EDT 2004


Brian van den Broek <bvande at po-box.mcgill.ca> writes:
[...]
> I'm still learning Python as a first language since some BASIC quite
> some time ago, so my level of knowledge/understanding is not too
> sophisticated. From that standpoint, I am wondering why the code that
> Michael P. Soulier provided above would worry an experienced Python
> programmer.

If you have a file open for writing when the process exits, the data
you've .write()ten isn't necessarily guaranteed to actually get
written to disk. (Apparently, whether it does or not depends on the
OS)

So, if an exception occurs after the first .write(), and there's no
finally: there to .close() your file, you might unexpectedly lose the
data that's already been written.

More generally, you might hang on to a resource (much) longer than
necessary, which is a problem if that resource is expensive (because
it's a scarce resource).  For example, a database connection.

[...]
> I had thought I was being careful and smart by always checking for
> filepath existence and always explicitly closing files, but I am
> wondering what red flag I'm overlooking.
[...]

Explicitly checking for a file's existence is another Bad Thing,
because of race conditions.  I think Alex Martelli has written about
this here before (google for LBYL and EAFP).


John



More information about the Python-list mailing list