[Python-ideas] except expression

Steven D'Aprano steve at pearwood.info
Wed Feb 19 01:10:49 CET 2014


On Tue, Feb 18, 2014 at 12:01:29PM -0500, Alexander Belopolsky wrote:

> I disagree.  It is best to leave explicit selection of exceptions to catch
> outside of the expressions.  This is job for things like decimal or numpy
> fp contexts.

I don't understand what relevance fp contexts have here.


> Always requiring a long camel-case name inside an expression will kill most
> of the advantages.

I doubt that. And they're not typically that long. TypeError is nine 
characters, no longer than your name :-)

 
> For example, it would be nice to be able to write something like
> 
> x = d1[key] except d2[key] except 0

Which is harmful, because it masks bugs. If you want to save typing, 
define K = KeyError at the top of your module, and write:

x = d1[key] except K d2[key] except K 0


which by the way looks horrible without the colons (sorry Paul, you have 
not convinced me that the Tim Peters prohibition on grit applies here). 
Even with three levels of indentation, mandatory brackets, and 
colons, it still fits within 79 columns and reads quite well:

if condition:
    while something():
        for key in sequence:
            x = (d1[key] except KeyError: (d2[key] except KeyError: 0))

Take the colons and brackets out, and I think it is less readable:

            x = d1[key] except KeyError d2[key] except KeyError 0

and ambiguous.

By the way, I think this is a good example for the PEP (Chris are you 
reading?). You might be tempted to re-write this as:

            x = d1.get(key, d2.get(key, 0))

which is shorter, but the semantics are different. If the second case, 
you have to pre-calculate the fallback, which may be expensive, while in 
the exception form, you only calculate the fallback if the first lookup 
actually fails.


> but sprinkle this with repeated KeyError and what is important (d1 and d2)
> will be lost in the scaffolding.

I think that is wrong. I realise it is a matter of taste, but in this 
instance I think my taste is much closer to the rest of Python's syntax 
than yours is. (But you probably think the same, yes?)


-- 
Steven


More information about the Python-ideas mailing list