[Python-ideas] [Fwd: Re: exception based conditional expression, similar to if-else conditional expression]
Jeff McAninch
mcaninch at lanl.gov
Thu Aug 20 16:52:27 CEST 2009
Jim Jewett wrote:
>
> Probably, but you don't have to use a comprehension.
>
> def g(seq):
> for e in seq:
> try:
> yield float(e)
> except:
> pass # whatever, even skipping the element
>
> If you don't need it in generator form, then just collect the results
> into a list and return that instead of yielding. (And obviously, that
> for loop doesn't even have to be in a separate (generator or) function
> at all.)
>
> -jJ
>
Certainly there are a number of ways to address this without using an
exception conditional expression. But it seems each of these would lead
to a proliferation of these special functions, as one tries to flexibly
address the different exception-value pairs that would be applied to
different operations.
I could for instance define the function Except:
def Except ( seq, nominal_function, function_lookup ):
for e in seq:
try:
yield nominal_function(e)
except:
(exception_type,exception_message) = sys.exc_info()[:2]
if (exception_type in function_lookup):
yield function_lookup[exception_type](e)
else:
raise exception_type, exception_message
Then I could write my simple example as:
xs = Except( ys, (lambda x: float(x)), {ValueError: (lamba x:
float('nan'))} )
So I agree, the behaviour can be produced with the language as-is. But
many of the evolutions in the language were not put in to address things
that "can't be done", but rather to let them be done in a more concise,
robust, and/or elegant way.
--
==========================
Jeffrey E. McAninch, PhD
Physicist, X-2-IFD
Los Alamos National Laboratory
Phone: 505-667-0374
Email: mcaninch at lanl.gov
==========================
More information about the Python-ideas
mailing list