Q on explicitly calling file.close

Stephen Hansen apt.shansen at gmail.com
Sun Sep 6 06:37:34 CEST 2009


On Sat, Sep 5, 2009 at 6:51 PM, kj <no.email at please.post> wrote:

> In <02b2e6ca$0$17565$c3e8da3 at news.astraweb.com> Steven D'Aprano <
> steve at REMOVE-THIS-cybersource.com.au> writes:
>
> >(3) For quick and dirty scripts, or programs that only use one or two
> >files, relying on the VM to close the file is sufficient (although lazy
> >in my opinion *wink*)
>
> It's not a matter of laziness or industriousness, but rather of
> code readability.  The real problem here is not the close() per
> se, but rather all the additional machinery required to ensure that
> the close happens.  When the code is working with multiple file
> handles simultaneously, one ends up with a thicket of try/finally's
> that makes the code just *nasty* to look at.  E.g., even with only
> two files, namely an input and an output file, compare:
>

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.

As for why you didn't see much of that style code in the wild-- that's
because the with statement is just pretty new. 2.5 had it with a future
statement, and although there's lots of code out there that /supports/
Python 2.5, there's not /that/ much which /requires/ it of yet. As time goes
on and people stop wanting to support earlier versions of Python in various
libraries, you'll see more of it in publicly available code. I'm personally
rewriting a huge chunk of code in the office to convert everything from
try/finally to with statements as we move our codebase to 2.5 finally, and
am quite gleeful. It's a lot cleaner and clearer.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090905/408e514c/attachment.html>


More information about the Python-list mailing list