[Python-ideas] except expression

Ron Adam ron3200 at gmail.com
Thu Feb 20 14:23:34 CET 2014



On 02/20/2014 02:36 AM, Chris Angelico wrote:
>> >By adding a __bool__ attribue to exceptions that always returns False, you
>> >can get some of that, but it has the same issues that logic operators have
>> >when a normally False item is also valid data.
>> >
>> >To get around that we would need a differently based logic system where the
>> >caught exception(s) are the only False values.
>> >
>> >Exception logic with False as an exception.
>> >
>> >     e1 and e2 or e3
>> >
>> >Translate to this...
>> >
>> >     try:
>> >         e1
>> >         e2
>> >     except False:
>> >         e3
>> >
>> >
>> >Then with IndexError.
>> >
>> >     (except IndexError: things[i] or None)

> I've read your post a few times and am still a bit lost. How would the
> above be evaluated?

Yes, I was just showing how the logic would work, not the exact executable 
code.  Here's a more complete examples.  It still needs the parser to 
translate the 'or's and 'and's in the except expression to the correct calls.

        def _except_or(self, e1, e2):
            try:
                _ = e1()
            except exc:
                _ = e2()
            return _

        def _except_and(e1, e2):
            e1()
            return e2()


Then this ...

        value = (except exc: e1 and e2 or e3)

Would translate to:

        value = _except_or(exc,
                           lambda: _except_and(lambda: e1, lambda: e2),
                           lambda: e3)

and this ...

        value = (except IndexError: things[i] or None)

would be:

        value = _except_or(exc, lambda: things[i], lambda: None)


The expression doesn't need to be just too terms, it could be something 
more complex.

       (except KeyError: d1[key] or d2[key] or d3[key] or None)


Would give the first dictionary lookup that doesn't raise KeyError or None.

Because the exception paths and data paths don't overlap, they could be 
dictionaries containing exception instances and it would still work.


Does that help?

cheers,
     Ron




More information about the Python-ideas mailing list