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

Douglas Alan doug at
Fri Jun 29 23:59:05 CEST 2007

Lenard Lindstrom <len-l at> writes:

> Douglas Alan wrote:

>> [I]n Python, you can be 100% sure that your files
>> will be closed in a timely manner without explicitly closing them, as
>> long as you are safe in making certain assumptions about how your code
>> will be used.  Such assumptions are called "preconditions", which are
>> an understood notion in software engineering and by me when I write
>> software.

> So documenting an assumption is more effective than removing the
> assumption using a with statement?

Once again I state that I have nothing against "with" statements.  I
used it all the time ages ago in Lisp.

But (1) try/finally blocks were not to my liking for this sort of
thing because they are verbose and I think error-prone for code
maintenance.  I and many others prefer relying on the refcounter for
file closing over the try/finally solution.  Consequently, using the
refcounter for such things is a well-entrenched and succinct idiom.
"with" statements are a big improvement over try/finally, but for
things like file closing, it's six of one, half dozen of the other
compared against just relying on the refcounter.

(2) "with" statements do not work in all situations because often you
need to have an open file (or what have you) survive the scope in
which it was opened.  You may need to have multiple objects be able to
read and/or write to the file.  And yet, the file may not want to be
kept open for the entire life of the program.  If you have to decide
when to explicitly close the file, then you end up with the same sort
of modularity issues as when you have to free memory explicitly.  The
refcounter handles these sorts of situations with aplomb.

(3) Any code that is saving tracebacks should assume that it is likely
to cause trouble, unless it is using code that is explicitly
documented to be robust in the face of this, just as any code that
wants to share objects between multiple threads should assume that
this is likely to cause trouble, unless it is using code that is
explicitly documented to be robust in the face of this.

(4) Any code that catches exceptions should either return soon or
clear the exception.  If it doesn't, the problem is not with the
callee, but with the caller.

(5) You don't necessarily want a function that raises an exception to
deallocate all of its resources before raising the exception, since
you may want access to these resources for debugging, or what have you.


More information about the Python-list mailing list