Q on explicitly calling file.close
Terry Reedy
tjreedy at udel.edu
Sun Sep 6 10:03:43 EDT 2009
Stephen Hansen wrote:
> This is precisely why the with statement exists; to provide a cleaner
> way to wrap a block in setup and teardown functions. Closing is one.
> Yeah, you get some extra indentation-- but you sorta have to live with
> it if you're worried about correct code. I think it's a good compromise
> between your examples of nasty and nice :)
>
> def compromise(from_, to_):
> with file(to_) as to_h:
> with file(from_) as from_h:
> for line in from_h:
> print >> to_h, munge(line)
>
> It's just too bad that 'with' doesn't support multiple separate "x as y"
> clauses.
The developers already agreed with you ;-).
"With more than one item, the context managers are processed as if
multiple with statements were nested:
with A() as a, B() as b:
suite
is equivalent to
with A() as a:
with B() as b:
suite
Changed in version 3.1: Support for multiple context expressions.
"
(I suspect this will also be in 2.7)
Terry Jan Reedy
More information about the Python-list
mailing list