[Python-Dev] cpython: Rename contextlib.ignored() to contextlib.ignore(). (original) (raw)
R. David Murray rdmurray at bitdance.com
Tue Oct 15 21:58:07 CEST 2013
- Previous message: [Python-Dev] cpython: Rename contextlib.ignored() to contextlib.ignore().
- Next message: [Python-Dev] cpython: Rename contextlib.ignored() to contextlib.ignore().
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Tue, 15 Oct 2013 15:02:15 -0300, Zero Piraeus <z at etiol.net> wrote:
:
On Tue, Oct 15, 2013 at 09:45:59AM -0700, Ethan Furman wrote: > [...] if the CM provides the value before, and the with block accepts > it, it can then have the exception added to it: > > with trap(OSError) as cm: > os.unlink('missing.txt') > if cm.exc: > dosomething() Is there some advantage to this over try: os.unlink('missing.txt') except OSError as exc: dosomething() I thought the whole point was to replace code that would otherwise contain 'except: pass' with something slightly more concise. Once you expose the exception, it becomes just an uglier version of a try/except block, as far as I can see.
Obviously not :)
You wouldn't use trap/as for that. Instead you use it to replace this:
exc = None
try:
os.unlink('missing.txt')
except OSError as exc:
pass
some
other
code
if exc is not None:
do_something()
with:
with trap(OSError) as cm:
os.unlink('missing.txt')
some
other
code
if cm.exc is not None:
do_something()
which saves you three lines, not just two :)
Of course in real life, in order for 'some other code' really be the best way to organize this snippet, you're going to be doing something more complicated than catching OSError from an unlink call.
If this is accepted, I do not expect to see this in real code very often at all. The main motivation for it is to make the semantics of the context manager clearer, and as a bonus make it work like assertRaises, which is our existing stdlib context manager that traps exceptions.
I'd be happy with 'trap' or 'catch' without 'as' support, but the names make more sense if the exception is actually available after it is trapped/caught.
--David
- Previous message: [Python-Dev] cpython: Rename contextlib.ignored() to contextlib.ignore().
- Next message: [Python-Dev] cpython: Rename contextlib.ignored() to contextlib.ignore().
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]