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

Jeff McAninch mcaninch at lanl.gov
Thu Aug 6 00:22:30 CEST 2009

I'm new to this list, so please excuse me if this topic has been 
discussed, but I didn't
see anything similar in the archives.

I very often want something like a try-except conditional expression similar
to the if-else conditional. 

An example of the proposed syntax might be:
    x = float(string) except float('nan')
or possibly
    x = float(string) except ValueError float('nan')

Here's a simple example: Converting a large list of strings to floats 
where there may be errors
that I want returned as nan's.

Currently I would write the function:
    def safe_float_function(string):
            result = float(string)
            result = float('nan')
        return result
and get my list of floats using the list comprehension:
    xs = [ safe_float_function(string) for string in strings ]

With a try-except conditional I would instead define the following lambda:
    safe_float_conditional = lambda string : float(string) except 
leading to:
    xs = [ safe_float_conditional(string) for string in strings ]

My understanding is that the second would be faster at run time, and, 
like if-else conditional expressions,
possibly more easily read by the human.

Again, please excuse me if this has been discussed previously.  If so, 
I'd appreciate being pointed to the discussion.

Please also excuse me if for there is some currently (pre-python 3.0) 
idiom that I could use to efficiently get this
same behaviour.  If so, I'd appreciate being educated.

Jeff McAninch

Jeffrey E. McAninch, PhD
Physicist, X-2-IFD
Los Alamos National Laboratory
Phone: 505-667-0374
Email: mcaninch at lanl.gov

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20090805/2d0ea125/attachment.htm>

More information about the Python-Dev mailing list