More on "with" statement

Daniel Dittmar daniel at dittmar.net
Fri Jul 13 15:15:00 EDT 2001


> I can only think of two reasons to use it.
> 
>     1) You're a lazy typist. (Or haven't learned to cut and paste)
> 
>     2) You are generally concerned that multiple references to the
>      same object with complex, multilevel access might be confusing
>     to the reader or not optimized by the compiler.

There's a third one: control blocks give visual structure to a method,
making the parts more easily recognizable

with sys.stdout:
    .write (...)
    .write (...)
doSomethingElse ()
with sys.stdout:
    .write (...)
    .write (...)

is at least to me more easily scannable than

write = sys.stdout.write
write (...)
write (...)
doSomethingElse ()
write (...)
write (...)

Of course, the second version is faster, because the lookup of the write
method is cached, not of stdout.

Admittedly, this is highly a matter of taste. To some, a few blank lines
already do the trick. Others will insist that readability is only
achieved by

sys.stdout.write (...)
sys.stdout.write (...)
doSomethingElse ()
sys.stdout.write (...)
sys.stdout.write (...)
# explicit is better than implicit

Daniel



More information about the Python-list mailing list