[Python-ideas] except expression

Stephen J. Turnbull stephen at xemacs.org
Thu Feb 20 04:02:50 CET 2014


Yury Selivanov writes:

 > value = 42 if a[10] raises IndexError

"If EXPR raises EXCEPTION" is often interpreted to mean "EXPR may
raise EXCEPTION" following the usage in Java and other languages where
exceptions are part of function signatures.  Maybe it's just me, but
this ambiguity would be annoying every time I see this syntax.

 > 
 > # set 'value' to 42 if len(a) < 10
 > # or else, return 'spam'
 > value = 42 if a[10] raises IndexError else 'spam'
 > 
 > # same as above but if a[10] raises anything
 > value = 42 if a[10] raises

Please, no bare excepts.  They're bad enough in the statement form
where the colon immediately follows and it's painfully obvious they're
bare.

 > # another example
 > foo(None if dct['key'] raises)

And what's the value if dct['key'] quietly succeeds?  I suppose it's
dct['key'], but that is not at all what the English interpretation
would be!  At least in my dialect, the English interpretation would
correspond to

    try:
        dct['key']
        foo()
    except:
        foo(None)



More information about the Python-ideas mailing list