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

Douglas Alan doug at alum.mit.edu
Mon Jul 2 21:28:34 EDT 2007


Lenard Lindstrom <len-l at telus.net> writes:

>> I'm not sure I understand you here.  You're saying that I should have
>> the foresight to wrap all my file opens is a special class to
>> facilitate debugging?

> Obviously you had the foresight to realize with statements could
> compromise debugging. I never considered it myself.

It's not really so much a matter of having foresight, as much as
having had experience debugging a fair amount of code.  And, at times,
having benefited from the traditional idiomatic way of coding in
Python, where files are not explicitly closed.

Since there are benefits with the typical coding style, and I find
there to be no significant downside, other than if, perhaps some code
holds onto tracebacks, I suggest that the problem be idiomatically
addressed in the *few* code locations that hold onto tracebacks,
rather than in all the *myriad* code locations that open and close
files.

>> Or are you suggesting that early in __main__.main(), when I wish to
>> debug something, I do something like:
>>    __builtins__.open = __builtins__.file = MyFile
>> ?
>> I suppose that would work.

> No, I would never suggest replacing a builtin like that. Even
> replacing a definite hook like __import__ is risky, should more than
> one package try and do it in a program.

That misinterpretation of your idea would only be reasonable while
actually debugging, not for standard execution.  Standard rules of
coding elegance don't apply while debugging, so I think the
misinterpretation might be a reasonable alternative.  Still I think
I'd just prefer to stick to the status quo in this regard.

> As long as the code isn't dependent on explicitly cleared
> exceptions. But if it is I assume it is well documented.

Typically the resource in question is an open file.  These usually
don't have to be closed in a particularly timely fashion.  If, for
some reason, a files absolutelys need to be closed rapidly, then it's
probably best to use "with" in such a case.  Otherwise, I vote for the
de facto standard idiom of relying on the refcounter along with
explicitly clearing exceptions in the situations we've previously
discusses.

If some code doesn't explicitly clear an exception, though, and holds
onto the the most recent one while running in a loop (or what have
you), in the cases we are considering, it hardly seems like the end of
the world.  It will just take a little bit longer for a single file to
be closed than might ideally be desired.  But this lack of ideal
behavior is usually not going to cause much trouble.

|>oug



More information about the Python-list mailing list