Python's "only one way to do it" philosophy isn't good?

Douglas Alan doug at alum.mit.edu
Thu Jul 5 17:12:22 EDT 2007


"Chris Mellon" <arkanes at gmail.com> writes:

>> Some people here have been arguing that all code should use "with" to
>> ensure that the files are closed.  But this still wouldn't solve the
>> problem of the large data structures being left around for an
>> arbitrary amount of time.

> I don't think anyone has suggested that. Let me be clear about *my*
> position: When you need to ensure that a file has been closed by a
> certain time, you need to be explicit about it. When you don't care,
> just that it will be closed "soonish" then relying on normal object
> lifetime calls is sufficient. This is true regardless of whether
> object lifetimes are handled via refcount or via "true" garbage
> collection.

But it's *not* true at all when relying only on a "true GC"!  Your
program could easily run out of file descriptors if you only have a
real garbage collector and code this way (and are opening lots of
files).  This is why destructors are useless in Java -- you can't rely
on them *ever* being called.  In Python, however, destructors are
quite useful due to the refcounter.

> Relying on the specific semantics of refcounting to give
> certain lifetimes is a logic error.
>
> For example:
>
> f = some_file() #maybe it's the file store for a database implementation
> f.write('a bunch of stuff')
> del f
> #insert code that assumes f is closed.

That's not a logic error if you are coding in CPython, though I agree
that in this particular case the explicit use of "with" would be
preferable due to its clarity.

|>oug



More information about the Python-list mailing list