Q on explicitly calling file.close

Stephen Hansen apt.shansen at gmail.com
Sun Sep 6 20:20:52 EDT 2009


On Sun, Sep 6, 2009 at 4:31 PM, r <rt8396 at gmail.com> wrote:

> On Sep 6, 1:14 pm, "Jan Kaliszewski" <z... at chopin.edu.pl> wrote:
> > 05-09-2009 r <rt8... at gmail.com> wrote:
> > > i find the with statement (while quite useful in general
> > > practice) is not a "cure all" for situations that need and exception
> > > caught.
> >
> > In what sense?
>
> *ahem*! in the sense that the with statement (while quite useful in
> general practice) is not a "cure all" for situations that need and
> exception caught ;-)


But what does that even mean? What's the -problem- that it isn't 'curing'?
That 'with' doesn't completely replace all uses of 'try'? It was never meant
to-- that seems like a completely different problem area. But, if you do
want it to handle exception catching, that's just a question of making a
context manager that does so.

    import contextlib

    @contextlib.contextmanager
    def file_with_errorhandling(filename, mode,
exceptions=(IOError,OSError)):
        fp = file(filename, mode)
        try:
            yield fp
        except exceptions:
            print "Handle file-operation errors gracefully here."
        fp.close()

    with file_with_errorhandling(filename, 'r') as fp:
        fp.read() # or whatever

True, the context manager provided by file objects just lets exceptions
propagate up but that's usually the desired behavior. You can make context
managers for particular problems you run across that handle exceptions if
you want.

The with statement isn't about never having to type try again, I don't
think.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090906/9d3fb55c/attachment-0001.html>


More information about the Python-list mailing list