<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Thu, Feb 20, 2014 at 7:15 PM, Chris Angelico <span dir="ltr"><<a href="mailto:rosuav@gmail.com" target="_blank">rosuav@gmail.com</a>></span> wrote:<br>

<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">PEP: 463<br>
Title: Exception-catching expressions<br>
Version: $Revision$<br>
Last-Modified: $Date$<br>
Author: Chris Angelico <<a href="mailto:rosuav@gmail.com">rosuav@gmail.com</a>><br>
Status: Draft<br>
Type: Standards Track<br>
Content-Type: text/x-rst<br>
Created: 15-Feb-2014<br>
Python-Version: 3.5<br>
Post-History: 16-Feb-2014, 21-Feb-2014<br>
<br>
<br>
Abstract<br>
========<br>
<br>
Just as PEP 308 introduced a means of value-based conditions in an<br>
expression, this system allows exception-based conditions to be used<br>
as part of an expression.<br></blockquote><div><br><br></div><div>Chris, while I also commend you for the comprehensive PEP, I'm -1 on the proposal, for two main reasons:<br><br></div><div>1. Many proposals suggest new syntax to gain some succinctness. Each has to be judged for its own merits, and in this case IMHO the cons eclipse the pros. I don't think this will save a lot of code in a typical well-structured program - maybe a few lines out of hundreds. On the other hand, it adds yet another syntax to remember and understand, which is not the Pythonic way.<br>

<br></div><div>2. Worse, this idea subverts exceptions to control flow, which is not only un-Pythonic but also against the accepted practices of programming in general. Here, the comparison to PEP 308 is misguided. PEP 308, whatever syntax it adds, still remains within the domain of normal control flow. PEP 463, OTOH, makes it deliberately easy to make exceptions part of non-exceptional code, encouraging very bad programming practices.<br>

<br></div><div>Eli<br></div><br><div><br> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
<br>
Motivation<br>
==========<br>
<br>
A number of functions and methods have parameters which will cause<br>
them to return a specified value instead of raising an exception.  The<br>
current system is ad-hoc and inconsistent, and requires that each<br>
function be individually written to have this functionality; not all<br>
support this.<br>
<br>
* dict.get(key, default) - second positional argument in place of<br>
  KeyError<br>
<br>
* next(iter, default) - second positional argument in place of<br>
  StopIteration<br>
<br>
* list.pop() - no way to return a default<br>
<br>
* seq[index] - no way to handle a bounds error<br>
<br>
* min(sequence, default=default) - keyword argument in place of<br>
  ValueError<br>
<br>
* sum(sequence, start=default) - slightly different but can do the<br>
  same job<br>
<br>
* statistics.mean(data) - no way to handle an empty iterator<br>
<br>
<br>
Rationale<br>
=========<br>
<br>
The current system requires that a function author predict the need<br>
for a default, and implement support for it.  If this is not done, a<br>
full try/except block is needed.<br>
<br>
Since try/except is a statement, it is impossible to catch exceptions<br>
in the middle of an expression.  Just as if/else does for conditionals<br>
and lambda does for function definitions, so does this allow exception<br>
catching in an expression context.<br>
<br>
This provides a clean and consistent way for a function to provide a<br>
default: it simply raises an appropriate exception, and the caller<br>
catches it.<br>
<br>
With some situations, an LBYL technique can be used (checking if some<br>
sequence has enough length before indexing into it, for instance). This is<br>
not safe in all cases, but as it is often convenient, programmers will be<br>
tempted to sacrifice the safety of EAFP in favour of the notational brevity<br>
of LBYL. Additionally, some LBYL techniques (eg involving getattr with<br>
three arguments) warp the code into looking like literal strings rather<br>
than attribute lookup, which can impact readability. A convenient EAFP<br>
notation solves all of this.<br>
<br>
There's no convenient way to write a helper function to do this; the<br>
nearest is something ugly using either lambda::<br>
<br>
    def except_(expression, exception_list, default):<br>
        try:<br>
            return expression()<br>
        except exception_list:<br>
            return default()<br>
    value = except_(lambda: 1/x, ZeroDivisionError, lambda: float("nan"))<br>
<br>
which is clunky, and unable to handle multiple exception clauses; or<br>
eval::<br>
<br>
    def except_(expression, exception_list, default):<br>
        try:<br>
            return eval(expression, globals_of_caller(), locals_of_caller())<br>
        except exception_list as exc:<br>
            l = locals_of_caller().copy()<br>
            l['exc'] = exc<br>
            return eval(default, globals_of_caller(), l)<br>
<br>
    def globals_of_caller():<br>
        return sys._getframe(2).f_globals<br>
<br>
    def locals_of_caller():<br>
        return sys._getframe(2).f_locals<br>
<br>
    value = except_("""1/x""",ZeroDivisionError,""" "Can't divide by zero" """)<br>
<br>
which is even clunkier, and relies on implementation-dependent hacks.<br>
(Writing globals_of_caller() and locals_of_caller() for interpreters<br>
other than CPython is left as an exercise for the reader.)<br>
<br>
Raymond Hettinger `expresses`__ a desire for such a consistent<br>
API. Something similar has been `requested`__ `multiple`__ `times`__<br>
in the past.<br>
<br>
__ <a href="https://mail.python.org/pipermail/python-ideas/2014-February/025443.html" target="_blank">https://mail.python.org/pipermail/python-ideas/2014-February/025443.html</a><br>
__ <a href="https://mail.python.org/pipermail/python-ideas/2013-March/019760.html" target="_blank">https://mail.python.org/pipermail/python-ideas/2013-March/019760.html</a><br>
__ <a href="https://mail.python.org/pipermail/python-ideas/2009-August/005441.html" target="_blank">https://mail.python.org/pipermail/python-ideas/2009-August/005441.html</a><br>
__ <a href="https://mail.python.org/pipermail/python-ideas/2008-August/001801.html" target="_blank">https://mail.python.org/pipermail/python-ideas/2008-August/001801.html</a><br>
<br>
<br>
Proposal<br>
========<br>
<br>
Just as the 'or' operator and the three part 'if-else' expression give<br>
short circuiting methods of catching a falsy value and replacing it,<br>
this syntax gives a short-circuiting method of catching an exception<br>
and replacing it.<br>
<br>
This currently works::<br>
<br>
    lst = [1, 2, None, 3]<br>
    value = lst[2] or "No value"<br>
<br>
The proposal adds this::<br>
<br>
    lst = [1, 2]<br>
    value = lst[2] except IndexError: "No value"<br>
<br>
Specifically, the syntax proposed is::<br>
<br>
    expr except exception_list: default<br>
<br>
where expr, exception_list, and default are all expressions.  First,<br>
expr is evaluated.  If no exception is raised, its value is the value<br>
of the overall expression.  If any exception is raised, exception_list<br>
is evaluated, and should result in either a type or a tuple, just as<br>
with the statement form of try/except.  Any matching exception will<br>
result in the corresponding default expression being evaluated and<br>
becoming the value of the expression.  As with the statement form of<br>
try/except, non-matching exceptions will propagate upward.<br>
<br>
Note that the current proposal does not allow the exception object to<br>
be captured. Where this is needed, the statement form must be used.<br>
(See below for discussion and elaboration on this.)<br>
<br>
This ternary operator would be between lambda and if/else in<br>
precedence.<br>
<br>
Consider this example of a two-level cache::<br>
    for key in sequence:<br>
        x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: f(key)))<br>
        # do something with x<br>
<br>
This cannot be rewritten as::<br>
        x = lvl1.get(key, lvl2.get(key, f(key)))<br>
<br>
which, despite being shorter, defeats the purpose of the cache, as it must<br>
calculate a default value to pass to get(). The .get() version calculates<br>
backwards; the exception-testing version calculates forwards, as would be<br>
expected. The nearest useful equivalent would be::<br>
        x = lvl1.get(key) or lvl2.get(key) or f(key)<br>
which depends on the values being nonzero, as well as depending on the cache<br>
object supporting this functionality.<br>
<br>
<br>
Alternative Proposals<br>
=====================<br>
<br>
Discussion on python-ideas brought up the following syntax suggestions::<br>
<br>
    value = expr except default if Exception [as e]<br>
    value = expr except default for Exception [as e]<br>
    value = expr except default from Exception [as e]<br>
    value = expr except Exception [as e] return default<br>
    value = expr except (Exception [as e]: default)<br>
    value = expr except Exception [as e] try default<br>
    value = expr except Exception [as e] continue with default<br>
    value = default except Exception [as e] else expr<br>
    value = try expr except Exception [as e]: default<br>
    value = expr except default # Catches anything<br>
    value = expr except(Exception) default # Catches only the named type(s)<br>
    value = default if expr raise Exception<br>
    value = expr or else default if Exception<br>
    value = expr except Exception [as e] -> default<br>
    value = expr except Exception [as e] pass default<br>
<br>
It has also been suggested that a new keyword be created, rather than<br>
reusing an existing one.  Such proposals fall into the same structure<br>
as the last form, but with a different keyword in place of 'pass'.<br>
Suggestions include 'then', 'when', and 'use'. Also, in the context of<br>
the "default if expr raise Exception" proposal, it was suggested that a<br>
new keyword "raises" be used.<br>
<br>
All forms involving the 'as' capturing clause have been deferred from<br>
this proposal in the interests of simplicity, but are preserved in the<br>
table above as an accurate record of suggestions.<br>
<br>
<br>
Open Issues<br>
===========<br>
<br>
Parentheses around the entire expression<br>
----------------------------------------<br>
<br>
Generator expressions require parentheses, unless they would be<br>
strictly redundant.  Ambiguities with except expressions could be<br>
resolved in the same way, forcing nested except-in-except trees to be<br>
correctly parenthesized and requiring that the outer expression be<br>
clearly delineated.  `Steven D'Aprano elaborates on the issue.`__<br>
<br>
__ <a href="https://mail.python.org/pipermail/python-ideas/2014-February/025647.html" target="_blank">https://mail.python.org/pipermail/python-ideas/2014-February/025647.html</a><br>
<br>
<br>
Example usage<br>
=============<br>
<br>
For each example, an approximately-equivalent statement form is given,<br>
to show how the expression will be parsed.  These are not always<br>
strictly equivalent, but will accomplish the same purpose.  It is NOT<br>
safe for the interpreter to translate one into the other.<br>
<br>
A number of these examples are taken directly from the Python standard<br>
library, with file names and line numbers correct as of early Feb 2014.<br>
Many of these patterns are extremely common.<br>
<br>
Retrieve an argument, defaulting to None::<br>
        cond = args[1] except IndexError: None<br>
<br>
        # Lib/pdb.py:803:<br>
        try:<br>
            cond = args[1]<br>
        except IndexError:<br>
            cond = None<br>
<br>
Fetch information from the system if available::<br>
            pwd = os.getcwd() except OSError: None<br>
<br>
            # Lib/tkinter/filedialog.py:210:<br>
            try:<br>
                pwd = os.getcwd()<br>
            except OSError:<br>
                pwd = None<br>
<br>
Attempt a translation, falling back on the original::<br>
        e.widget = self._nametowidget(W) except KeyError: W<br>
<br>
        # Lib/tkinter/__init__.py:1222:<br>
        try:<br>
            e.widget = self._nametowidget(W)<br>
        except KeyError:<br>
            e.widget = W<br>
<br>
Read from an iterator, continuing with blank lines once it's<br>
exhausted::<br>
        line = readline() except StopIteration: ''<br>
<br>
        # Lib/lib2to3/pgen2/tokenize.py:370:<br>
        try:<br>
            line = readline()<br>
        except StopIteration:<br>
            line = ''<br>
<br>
Retrieve platform-specific information (note the DRY improvement);<br>
this particular example could be taken further, turning a series of<br>
separate assignments into a single large dict initialization::<br>
        # sys.abiflags may not be defined on all platforms.<br>
        _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: ''<br>
<br>
        # Lib/sysconfig.py:529:<br>
        try:<br>
            _CONFIG_VARS['abiflags'] = sys.abiflags<br>
        except AttributeError:<br>
            # sys.abiflags may not be defined on all platforms.<br>
            _CONFIG_VARS['abiflags'] = ''<br>
<br>
Retrieve an indexed item, defaulting to None (similar to dict.get)::<br>
    def getNamedItem(self, name):<br>
        return self._attrs[name] except KeyError: None<br>
<br>
    # Lib/xml/dom/minidom.py:573:<br>
    def getNamedItem(self, name):<br>
        try:<br>
            return self._attrs[name]<br>
        except KeyError:<br>
            return None<br>
<br>
<br>
Translate numbers to names, falling back on the numbers::<br>
            g = grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid<br>
            u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: tarinfo.uid<br>
<br>
            # Lib/tarfile.py:2198:<br>
            try:<br>
                g = grp.getgrnam(tarinfo.gname)[2]<br>
            except KeyError:<br>
                g = tarinfo.gid<br>
            try:<br>
                u = pwd.getpwnam(tarinfo.uname)[2]<br>
            except KeyError:<br>
                u = tarinfo.uid<br>
<br>
Perform some lengthy calculations in EAFP mode, handling division by<br>
zero as a sort of sticky NaN::<br>
<br>
    value = calculate(x) except ZeroDivisionError: float("nan")<br>
<br>
    try:<br>
        value = calculate(x)<br>
    except ZeroDivisionError:<br>
        value = float("nan")<br>
<br>
Calculate the mean of a series of numbers, falling back on zero::<br>
<br>
    value = statistics.mean(lst) except statistics.StatisticsError: 0<br>
<br>
    try:<br>
        value = statistics.mean(lst)<br>
    except statistics.StatisticsError:<br>
        value = 0<br>
<br>
Retrieving a message from either a cache or the internet, with auth<br>
check::<br>
<br>
    <a href="http://logging.info" target="_blank">logging.info</a>("Message shown to user: %s",((cache[k]<br>
        except LookupError:<br>
            (backend.read(k) except OSError: 'Resource not available')<br>
        )<br>
        if check_permission(k) else 'Access denied'<br>
    ) except BaseException: "This is like a bare except clause")<br>
<br>
    try:<br>
        if check_permission(k):<br>
            try:<br>
                _ = cache[k]<br>
            except LookupError:<br>
                try:<br>
                    _ = backend.read(k)<br>
                except OSError:<br>
                    _ = 'Resource not available'<br>
        else:<br>
            _ = 'Access denied'<br>
    except BaseException:<br>
        _ = "This is like a bare except clause"<br>
    <a href="http://logging.info" target="_blank">logging.info</a>("Message shown to user: %s", _)<br>
<br>
Looking up objects in a sparse list of overrides::<br>
<br>
    (overrides[x] or default except IndexError: default).ping()<br>
<br>
    try:<br>
        (overrides[x] or default).ping()<br>
    except IndexError:<br>
        default.ping()<br>
<br>
<br>
Narrowing of exception-catching scope<br>
-------------------------------------<br>
<br>
The following examples, taken directly from Python's standard library,<br>
demonstrate how the scope of the try/except can be conveniently narrowed.<br>
To do this with the statement form of try/except would require a temporary<br>
variable, but it's far cleaner as an expression.<br>
<br>
Lib/ipaddress.py:343::<br>
            try:<br>
                ips.append(ip.ip)<br>
            except AttributeError:<br>
                ips.append(ip.network_address)<br>
Becomes::<br>
            ips.append(ip.ip except AttributeError: ip.network_address)<br>
The expression form is nearly equivalent to this::<br>
            try:<br>
                _ = ip.ip<br>
            except AttributeError:<br>
                _ = ip.network_address<br>
            ips.append(_)<br>
<br>
Lib/tempfile.py:130::<br>
    try:<br>
        dirlist.append(_os.getcwd())<br>
    except (AttributeError, OSError):<br>
        dirlist.append(_os.curdir)<br>
Becomes::<br>
    dirlist.append(_os.getcwd() except (AttributeError, OSError): _os.curdir)<br>
<br>
Lib/asyncore.py:264::<br>
            try:<br>
                status.append('%s:%d' % self.addr)<br>
            except TypeError:<br>
                status.append(repr(self.addr))<br>
Becomes::<br>
            status.append('%s:%d' % self.addr except TypeError: repr(self.addr))<br>
<br>
<br>
Comparisons with other languages<br>
================================<br>
<br>
(With thanks to Andrew Barnert for compiling this section.)<br>
<br>
`Ruby's`__ "begin…rescue…rescue…else…ensure…end" is an expression<br>
(potentially with statements inside it).  It has the equivalent of an "as"<br>
clause, and the equivalent of bare except.  And it uses no punctuation or<br>
keyword between the bare except/exception class/exception class with as<br>
clause and the value.  (And yes, it's ambiguous unless you understand<br>
Ruby's statement/expression rules.)<br>
<br>
__ <a href="http://www.skorks.com/2009/09/ruby-exceptions-and-exception-handling/" target="_blank">http://www.skorks.com/2009/09/ruby-exceptions-and-exception-handling/</a><br>
<br>
::<br>
<br>
    x = begin computation() rescue MyException => e default(e) end;<br>
    x = begin computation() rescue MyException default() end;<br>
    x = begin computation() rescue default() end;<br>
    x = begin computation() rescue MyException default() rescue<br>
OtherException other() end;<br>
<br>
In terms of this PEP::<br>
<br>
    x = computation() except MyException as e default(e)<br>
    x = computation() except MyException default(e)<br>
    x = computation() except default(e)<br>
    x = computation() except MyException default() except OtherException other()<br>
<br>
`Erlang`__ has a try expression that looks like this::<br>
<br>
__ <a href="http://erlang.org/doc/reference_manual/expressions.html#id79284" target="_blank">http://erlang.org/doc/reference_manual/expressions.html#id79284</a><br>
<br>
    x = try computation() catch MyException:e -> default(e) end;<br>
    x = try computation() catch MyException:e -> default(e);<br>
OtherException:e -> other(e) end;<br>
<br>
The class and "as" name are mandatory, but you can use "_" for either.<br>
There's also an optional "when" guard on each, and a "throw" clause that<br>
you can catch, which I won't get into.  To handle multiple exceptions,<br>
you just separate the clauses with semicolons, which I guess would map<br>
to commas in Python.  So::<br>
<br>
    x = try computation() except MyException as e -> default(e)<br>
    x = try computation() except MyException as e -> default(e),<br>
OtherException as e->other_default(e)<br>
<br>
Erlang also has a "catch" expression, which, despite using the same keyword,<br>
is completely different, and you don't want to know about it.<br>
<br>
<br>
The ML family has two different ways of dealing with this, "handle" and<br>
"try"; the difference between the two is that "try" pattern-matches the<br>
exception, which gives you the effect of multiple except clauses and as<br>
clauses.  In either form, the handler clause is punctuated by "=>" in<br>
some dialects, "->" in others.<br>
<br>
To avoid confusion, I'll write the function calls in Python style.<br>
<br>
Here's `SML's`__ "handle"::<br>
__ <a href="http://www.cs.cmu.edu/~rwh/introsml/core/exceptions.htm" target="_blank">http://www.cs.cmu.edu/~rwh/introsml/core/exceptions.htm</a><br>
<br>
    let x = computation() handle MyException => default();;<br>
<br>
Here's `OCaml's`__ "try"::<br>
__ <a href="http://www2.lib.uchicago.edu/keith/ocaml-class/exceptions.html" target="_blank">http://www2.lib.uchicago.edu/keith/ocaml-class/exceptions.html</a><br>
<br>
    let x = try computation() with MyException explanation -><br>
default(explanation);;<br>
<br>
    let x = try computation() with<br>
<br>
        MyException(e) -> default(e)<br>
      | MyOtherException() -> other_default()<br>
      | (e) -> fallback(e);;<br>
<br>
In terms of this PEP, these would be something like::<br>
<br>
    x = computation() except MyException => default()<br>
    x = try computation() except MyException e -> default()<br>
    x = (try computation()<br>
         except MyException as e -> default(e)<br>
         except MyOtherException -> other_default()<br>
         except BaseException as e -> fallback(e))<br>
<br>
Many ML-inspired but not-directly-related languages from academia mix things<br>
up, usually using more keywords and fewer symbols. So, the `Oz`__ would map<br>
to Python as::<br>
__ <a href="http://mozart.github.io/mozart-v1/doc-1.4.0/tutorial/node5.html" target="_blank">http://mozart.github.io/mozart-v1/doc-1.4.0/tutorial/node5.html</a><br>
<br>
    x = try computation() catch MyException as e then default(e)<br>
<br>
<br>
Many Lisp-derived languages, like `Clojure,`__ implement try/catch as special<br>
forms (if you don't know what that means, think function-like macros), so you<br>
write, effectively::<br>
__ <a href="http://clojure.org/special_forms#Special%20Forms--(try%20expr*%20catch-clause*%20finally-clause" target="_blank">http://clojure.org/special_forms#Special%20Forms--(try%20expr*%20catch-clause*%20finally-clause</a>?)<br>


<br>
    try(computation(), catch(MyException, explanation, default(explanation)))<br>
<br>
    try(computation(),<br>
        catch(MyException, explanation, default(explanation)),<br>
        catch(MyOtherException, explanation, other_default(explanation)))<br>
<br>
In Common Lisp, this is done with a slightly clunkier `"handler-case" macro,`__<br>
but the basic idea is the same.<br>
<br>
__ <a href="http://clhs.lisp.se/Body/m_hand_1.htm" target="_blank">http://clhs.lisp.se/Body/m_hand_1.htm</a><br>
<br>
<br>
The Lisp style is, surprisingly, used by some languages that don't have<br>
macros, like Lua, where `xpcall`__ takes functions. Writing lambdas<br>
Python-style instead of Lua-style::<br>
__ <a href="http://www.gammon.com.au/scripts/doc.php?lua=xpcall" target="_blank">http://www.gammon.com.au/scripts/doc.php?lua=xpcall</a><br>
<br>
    x = xpcall(lambda: expression(), lambda e: default(e))<br>
<br>
This actually returns (true, expression()) or (false, default(e)), but<br>
I think we can ignore that part.<br>
<br>
<br>
Haskell is actually similar to Lua here (except that it's all done<br>
with monads, of course)::<br>
<br>
    x = do catch(lambda: expression(), lambda e: default(e))<br>
<br>
You can write a pattern matching expression within the function to decide<br>
what to do with it; catching and re-raising exceptions you don't want is<br>
cheap enough to be idiomatic.<br>
<br>
But Haskell infixing makes this nicer::<br>
<br>
    x = do expression() `catch` lambda: default()<br>
    x = do expression() `catch` lambda e: default(e)<br>
<br>
And that makes the parallel between the lambda colon and the except<br>
colon in the proposal much more obvious::<br>
<br>
<br>
    x = expression() except Exception: default()<br>
    x = expression() except Exception as e: default(e)<br>
<br>
<br>
`Tcl`__ has the other half of Lua's xpcall; catch is a function which returns<br>
true if an exception was caught, false otherwise, and you get the value out<br>
in other ways.  And it's all built around the the implicit quote-and-exec<br>
that everything in Tcl is based on, making it even harder to describe in<br>
Python terms than Lisp macros, but something like::<br>
__ <a href="http://wiki.tcl.tk/902" target="_blank">http://wiki.tcl.tk/902</a><br>
<br>
    if {[ catch("computation()") "explanation"]} { default(explanation) }<br>
<br>
<br>
`Smalltalk`__ is also somewhat hard to map to Python. The basic version<br>
would be::<br>
__ <a href="http://smalltalk.gnu.org/wiki/exceptions" target="_blank">http://smalltalk.gnu.org/wiki/exceptions</a><br>
<br>
    x := computation() on:MyException do:default()<br>
<br>
… but that's basically Smalltalk's passing-arguments-with-colons<br>
syntax, not its exception-handling syntax.<br>
<br>
<br>
Deferred sub-proposals<br>
======================<br>
<br>
Multiple except clauses<br>
-----------------------<br>
<br>
An examination of use-cases shows that this is not needed as often as<br>
it would be with the statement form, and as its syntax is a point on<br>
which consensus has not been reached, the entire feature is deferred.<br>
<br>
In order to ensure compatibility with future versions, ensure that any<br>
consecutive except operators are parenthesized to guarantee the<br>
interpretation you expect.<br>
<br>
Multiple 'except' keywords can be used, and they will all catch<br>
exceptions raised in the original expression (only)::<br>
<br>
    # Will catch any of the listed exceptions thrown by expr;<br>
    # any exception thrown by a default expression will propagate.<br>
    value = (expr<br>
        except Exception1 [as e]: default1<br>
        except Exception2 [as e]: default2<br>
        # ... except ExceptionN [as e]: defaultN<br>
    )<br>
<br>
Using parentheses to force an alternative interpretation works as<br>
expected::<br>
<br>
    # Will catch an Exception2 thrown by either expr or default1<br>
    value = (<br>
        (expr except Exception1: default1)<br>
        except Exception2: default2<br>
    )<br>
    # Will catch an Exception2 thrown by default1 only<br>
    value = (expr except Exception1:<br>
        (default1 except Exception2: default2)<br>
    )<br>
<br>
This last form is confusing and should be discouraged by PEP 8, but it<br>
is syntactically legal: you can put any sort of expression inside a<br>
ternary-except; ternary-except is an expression; therefore you can put<br>
a ternary-except inside a ternary-except.<br>
<br>
Open question: Where there are multiple except clauses, should they be<br>
separated by commas?  It may be easier for the parser, that way::<br>
<br>
    value = (expr<br>
        except Exception1 [as e]: default1,<br>
        except Exception2 [as e]: default2,<br>
        # ... except ExceptionN [as e]: defaultN,<br>
    )<br>
<br>
with an optional comma after the last, as per tuple rules.  Downside:<br>
Omitting the comma would be syntactically valid, and would have almost<br>
identical semantics, but would nest the entire preceding expression in<br>
its exception catching rig - a matching exception raised in the<br>
default clause would be caught by the subsequent except clause.  As<br>
this difference is so subtle, it runs the risk of being a major bug<br>
magnet.<br>
<br>
As a mitigation of this risk, this form::<br>
<br>
    value = expr except Exception1: default1 except Exception2: default2<br>
<br>
could be syntactically forbidden, and parentheses required if the<br>
programmer actually wants that behaviour::<br>
<br>
    value = (expr except Exception1: default1) except Exception2: default2<br>
<br>
This would prevent the accidental omission of a comma from changing<br>
the expression's meaning.<br>
<br>
<br>
Capturing the exception object<br>
------------------------------<br>
<br>
In a try/except block, the use of 'as' to capture the exception object<br>
creates a local name binding, and implicitly deletes that binding in a<br>
finally clause.  As 'finally' is not a part of this proposal (see<br>
below), this makes it tricky to describe; also, this use of 'as' gives<br>
a way to create a name binding in an expression context.  Should the<br>
default clause have an inner scope in which the name exists, shadowing<br>
anything of the same name elsewhere?  Should it behave the same way the<br>
statement try/except does, and unbind the name?  Should it bind the<br>
name and leave it bound? (Almost certainly not; this behaviour was<br>
changed in Python 3 for good reason.)<br>
<br>
Additionally, this syntax would allow a convenient way to capture<br>
exceptions in interactive Python; returned values are captured by "_",<br>
but exceptions currently are not. This could be spelled:<br>
<br>
>>> expr except Exception as e: e<br>
<br>
(The inner scope idea is tempting, but currently CPython handles list<br>
comprehensions with a nested function call, as this is considered<br>
easier.  It may be of value to simplify both comprehensions and except<br>
expressions, but that is a completely separate proposal to this PEP;<br>
alternatively, it may be better to stick with what's known to<br>
work. `Nick Coghlan elaborates.`__)<br>
<br>
__ <a href="https://mail.python.org/pipermail/python-ideas/2014-February/025702.html" target="_blank">https://mail.python.org/pipermail/python-ideas/2014-February/025702.html</a><br>
<br>
An examination of the Python standard library shows that, while the use<br>
of 'as' is fairly common (occurring in roughly one except clause in five),<br>
it is extremely *uncommon* in the cases which could logically be converted<br>
into the expression form.  Its few uses can simply be left unchanged.<br>
Consequently, in the interests of simplicity, the 'as' clause is not<br>
included in this proposal.  A subsequent Python version can add this without<br>
breaking any existing code, as 'as' is already a keyword.<br>
<br>
One example where this could possibly be useful is Lib/imaplib.py:568::<br>
        try: typ, dat = self._simple_command('LOGOUT')<br>
        except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]<br>
This could become::<br>
        typ, dat = (self._simple_command('LOGOUT')<br>
            except BaseException as e: ('NO', '%s: %s' % (type(e), e)))<br>
Or perhaps some other variation. This is hardly the most compelling use-case,<br>
but an intelligent look at this code could tidy it up significantly.  In the<br>
absence of further examples showing any need of the exception object, I have<br>
opted to defer indefinitely the recommendation.<br>
<br>
<br>
Rejected sub-proposals<br>
======================<br>
<br>
finally clause<br>
--------------<br>
The statement form try... finally or try... except... finally has no<br>
logical corresponding expression form.  Therefore the finally keyword<br>
is not a part of this proposal, in any way.<br>
<br>
<br>
Bare except having different meaning<br>
------------------------------------<br>
<br>
With several of the proposed syntaxes, omitting the exception type name<br>
would be easy and concise, and would be tempting. For convenience's sake,<br>
it might be advantageous to have a bare 'except' clause mean something<br>
more useful than "except BaseException". Proposals included having it<br>
catch Exception, or some specific set of "common exceptions" (subclasses<br>
of a new type called ExpressionError), or have it look for a tuple named<br>
ExpressionError in the current scope, with a built-in default such as<br>
(ValueError, UnicodeError, AttributeError, EOFError, IOError, OSError,<br>
LookupError, NameError, ZeroDivisionError). All of these were rejected,<br>
for severa reasons.<br>
<br>
* First and foremost, consistency with the statement form of try/except<br>
would be broken. Just as a list comprehension or ternary if expression<br>
can be explained by "breaking it out" into its vertical statement form,<br>
an expression-except should be able to be explained by a relatively<br>
mechanical translation into a near-equivalent statement. Any form of<br>
syntax common to both should therefore have the same semantics in each,<br>
and above all should not have the subtle difference of catching more in<br>
one than the other, as it will tend to attract unnoticed bugs.<br>
<br>
* Secondly, the set of appropriate exceptions to catch would itself be<br>
a huge point of contention. It would be impossible to predict exactly<br>
which exceptions would "make sense" to be caught; why bless some of them<br>
with convenient syntax and not others?<br>
<br>
* And finally (this partly because the recommendation was that a bare<br>
except should be actively encouraged, once it was reduced to a "reasonable"<br>
set of exceptions), any situation where you catch an exception you don't<br>
expect to catch is an unnecessary bug magnet.<br>
<br>
Consequently, the use of a bare 'except' is down to two possibilities:<br>
either it is syntactically forbidden in the expression form, or it is<br>
permitted with the exact same semantics as in the statement form (namely,<br>
that it catch BaseException and be unable to capture it with 'as').<br>
<br>
<br>
Bare except clauses<br>
-------------------<br>
<br>
PEP 8 rightly advises against the use of a bare 'except'. While it is<br>
syntactically legal in a statement, and for backward compatibility must<br>
remain so, there is little value in encouraging its use. In an expression<br>
except clause, "except:" is a SyntaxError; use the equivalent long-hand<br>
form "except BaseException:" instead. A future version of Python MAY choose<br>
to reinstate this, which can be done without breaking compatibility.<br>
<br>
<br>
Parentheses around the except clauses<br>
-------------------------------------<br>
<br>
Should it be legal to parenthesize the except clauses, separately from<br>
the expression that could raise? Example::<br>
<br>
    value = expr (<br>
        except Exception1 [as e]: default1<br>
        except Exception2 [as e]: default2<br>
        # ... except ExceptionN [as e]: defaultN<br>
    )<br>
<br>
This is more compelling when one or both of the deferred sub-proposals<br>
of multiple except clauses and/or exception capturing is included.  In<br>
their absence, the parentheses would be thus::<br>
    value = expr except ExceptionType: default<br>
    value = expr (except ExceptionType: default)<br>
<br>
The advantage is minimal, and the potential to confuse a reader into<br>
thinking the except clause is separate from the expression, or into thinking<br>
this is a function call, makes this non-compelling.  The expression can, of<br>
course, be parenthesized if desired, as can the default::<br>
    value = (expr) except ExceptionType: (default)<br>
<br>
<br>
Short-hand for "except: pass"<br>
-----------------------------<br>
<br>
The following was been suggested as a similar<br>
short-hand, though not technically an expression::<br>
<br>
    statement except Exception: pass<br>
<br>
    try:<br>
        statement<br>
    except Exception:<br>
        pass<br>
<br>
For instance, a common use-case is attempting the removal of a file::<br>
    os.unlink(some_file) except OSError: pass<br>
<br>
There is an equivalent already in Python 3.4, however, in contextlib::<br>
    from contextlib import suppress<br>
    with suppress(OSError): os.unlink(some_file)<br>
<br>
As this is already a single line (or two with a break after the colon),<br>
there is little need of new syntax and a confusion of statement vs<br>
expression to achieve this.<br>
<br>
<br>
Copyright<br>
=========<br>
<br>
This document has been placed in the public domain.<br>
<br>
<br>
..<br>
   Local Variables:<br>
   mode: indented-text<br>
   indent-tabs-mode: nil<br>
   sentence-end-double-space: t<br>
   fill-column: 70<br>
   coding: utf-8<br>
   End:<br>
_______________________________________________<br>
Python-Dev mailing list<br>
<a href="mailto:Python-Dev@python.org">Python-Dev@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/python-dev" target="_blank">https://mail.python.org/mailman/listinfo/python-dev</a><br>
Unsubscribe: <a href="https://mail.python.org/mailman/options/python-dev/eliben%40gmail.com" target="_blank">https://mail.python.org/mailman/options/python-dev/eliben%40gmail.com</a><br>
</blockquote></div><br></div></div>