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

Chris Mellon arkanes at
Fri Jul 6 14:36:04 CEST 2007

On 7/5/07, Douglas Alan <doug at> wrote:
> "Chris Mellon" <arkanes at> 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.

Sure, but thats part of the general refcounting vs GC argument -
refcounting gives (a certain level of) timeliness in resource
collection, GC often only runs under memory pressure. If you're saying
that we should keep refcounting because it provides better handling of
non-memory limited resources like file handles, I probably wouldn't
argue. But saying we should keep refcounting because people like to
and should write code that relies on implicit scope level object
destruction I very strongly argue against.

> > 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.

I stand by my statement. I feel that writing code in this manner is
like writing C code that assumes uninitialized pointers are 0 -
regardless of whether it works, it's erroneous and bad practice at
best, and actively harmful at worst.

More information about the Python-list mailing list