Q on explicitly calling file.close
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Sep 7 22:57:10 EDT 2009
En Sun, 06 Sep 2009 21:20:52 -0300, Stephen Hansen <apt.shansen at gmail.com>
escribió:
> 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.
>
> 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.
Note that to correctly emulate the file built-in context manager,
fp.close() should be inside a finally clause.
> The with statement isn't about never having to type try again, I don't
> think.
The with statement is intended as a replacement for common try/finally
blocks, not try/except blocks as the OP seems to imply.
--
Gabriel Genellina
More information about the Python-list
mailing list