[Python-ideas] (try-except) conditional expression similar to (if-else) conditional (PEP 308)

Dj Gilcrease digitalxero at gmail.com
Thu Aug 6 15:21:33 CEST 2009

I figure I would write up the PEP draft, I have never tried writing a
pep before, but i did read PEP 1 and tried to follow it's formating
guides. If there are no additions to the idea, then it seems there
just needs to be a consensus on the syntax before submitting it to the
peps list

  PEP: <pep number>
  Title: try-except conditional expressions
  Version: <svn version string>
  Last-Modified: <svn date string>
  Author: Jeff McAninch <mcaninch at lanl.gov>, Dj Gilcrease
<digitalxero at gmail.com>
  Discussions-To: python-ideas at python.org
  Status: Draft
  Type: Standards Track
  Content-Type: text/plain
  Created: 06-Aug-2009
  Python-Version: 2.7/3.2
  Post-History: <dates of postings to python-list and python-dev>

    I very often want something like a try-except conditional
    expression similar to the if-else conditional instead of resorting
    to a multi-line try-except block.

Design Goals:
    The new syntax should
        * Be simple to read
        * Be intuitive so people who may use it infrequently dont need
            to go lookup the format every time
        * Make it obvious what is happening

    Often when doing calculations or string recasting (to int, float,
    etc) it is required to wrap the section in a simple try-except
    where the exception just assigns a default value. It would be more
    readable and consise if these type of try-excepts could be written
    on a single line.


    All 3 components would just be ordinary expressions. The exception
    definition would be allowed to resolve to a single exception or a
    tuple of exceptions, just as it is in a normal try/except

Syntax Ideas:
    Option 1:
        x = float(string) except float('nan') if ValueError
        op(float(string) except float('nan') if ValueError)

    Option 2:
        x = float(string) except ValueError: float('nan')
        op(float(string) except ValueError: float('nan'))

    Option 3:
        x = float(string) except ValueError else float('nan')
        op(float(string) except ValueError else float('nan'))

More information about the Python-ideas mailing list