[Python-ideas] except expression

Steven D'Aprano steve at pearwood.info
Wed Feb 19 14:39:16 CET 2014


On Wed, Feb 19, 2014 at 10:28:59PM +1000, Nick Coghlan wrote:

> Either way, based on your survey of the stdlib, I agree with MAL's
> suggestion to also rule out embedded name binding. The example you
> give in the PEP of losing the distinction between whether an iterator
> yielded a new incremental value or terminated and returned a final
> value is another sign that allowing name binding is a potential bug
> magnet, because it conflates two different return channels into one.

Hmmm, I think that's a bit strong. If combining the iterator's yield 
value and the iterator's return value is a mistake, that's not the 
syntax that makes it a mistake, it's that the very idea of doing so is 
wrong. We wouldn't say that try...except statements are a bug magnet 
because we can write:

try:
    result = next(it)
except StopIteration as e:
    result = e.args[0]

I had a use-case for naming the exception caught: you are working with 
some library that returns and expects 2-tuples of (success, value). So 
you might do this:

try:
    return (True, expr)
except SomeError as e:
    return (False, e.args[0])

which becomes:

    (True, expr) except SomeError as e: (False, e.args[0])

Chris suggested that there is an example of this in the imap module, but 
it hasn't hit the PEP yet.


-- 
Steven


More information about the Python-ideas mailing list