[Python-Dev] PEP 463: Exception-catching expressions

Chris Angelico rosuav at gmail.com
Sat Feb 22 06:34:40 CET 2014

On Sat, Feb 22, 2014 at 4:01 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> (Chris, I think that ought to go in the motivation section of the PEP.)

Added to my draft, and here's the peps diff:

diff -r c52a2ae3d98e pep-0463.txt
--- a/pep-0463.txt Fri Feb 21 23:27:51 2014 -0500
+++ b/pep-0463.txt Sat Feb 22 16:33:37 2014 +1100
@@ -43,6 +43,34 @@

 * statistics.mean(data) - no way to handle an empty iterator

+Had this facility existed early in Python's history, there would have been
+no need to create dict.get() and related methods; the one obvious way to
+handle an absent key would be to respond to the exception.  One method is
+written which signal the absence in one way, and one consistent technique
+is used to respond to the absence.  Instead, we have dict.get(), and as of
+Python 3.4, we also have min(... default=default), and myriad others.  We
+have a LBYL syntax for testing inside an expression, but there is currently
+no EAFP notation; compare the following::
+    # LBYL:
+    if key in dic:
+        process(dic[key])
+    else:
+        process(None)
+    # As an expression:
+    process(dic[key] if key in dic else None)
+    # EAFP:
+    try:
+        process(dic[key])
+    except KeyError:
+        process(None)
+    # As an expression:
+    process(dic[key] except KeyError: None)
+Python generally recommends the EAFP policy, but must then proliferate
+utility functions like dic.get(key,None) to enable this.


More information about the Python-Dev mailing list