<br><br><div class="gmail_quote">On Sun, Sep 6, 2009 at 4:31 PM, r <span dir="ltr"><<a href="mailto:rt8396@gmail.com">rt8396@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
On Sep 6, 1:14 pm, "Jan Kaliszewski" <<a href="mailto:z...@chopin.edu.pl">z...@chopin.edu.pl</a>> wrote:<br>
<div class="im">> 05-09-2009 r <<a href="mailto:rt8...@gmail.com">rt8...@gmail.com</a>> wrote:<br>
> > i find the with statement (while quite useful in general<br>
> > practice) is not a "cure all" for situations that need and exception<br>
> > caught.<br>
><br>
</div>> In what sense?<br>
<br>
*ahem*! in the sense that the with statement (while quite useful in<br>
<div class="im">general practice) is not a "cure all" for situations that need and<br>
</div>exception caught ;-)</blockquote><div><br></div><div>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.</div>
<div><br></div><div> import contextlib</div><div><br></div><div> @contextlib.contextmanager</div><div> def file_with_errorhandling(filename, mode, exceptions=(IOError,OSError)):</div><div> fp = file(filename, mode)</div>
<div> try:</div><div> yield fp</div><div> except exceptions:</div><div> print "Handle file-operation errors gracefully here."</div><div> fp.close()</div><div><br></div>
<div> with file_with_errorhandling(filename, 'r') as fp:</div><div> fp.read() # or whatever</div><div><br></div><div>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.</div>
<div><br></div><div>The with statement isn't about never having to type try again, I don't think. </div><div><br></div><div>--S</div></div>