[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Thu Feb 20 17:17:53 CET 2014


On Fri, Feb 21, 2014 at 2:26 AM, Ron Adam <ron3200 at gmail.com> wrote:
> How about re-using the binary operators...
>
>        (except KeyError try d1[key] | d2[key] | d3[key] | None)
>
>
> It's not uncommon for symbols to mean different things in different places.
>
>    %, +, *
>
> There are probably others I'm not thinking of at the moment.
>
> I really like this actually and it makes the syntax even more concise.  :-)

That works really nicely when you can control the types returned. I've
written stuff that abuses magic methods (one of the most fun was
producing something that actually stored an indeterminate value in a
variable!), but it depends on writing the classes yourself. Can't be
used in the general sense.

But if you _can_ control it, all you need is to do this:

value = d1[key] | d2[key] | d3[key] | None

and then define d1[key] to return a special object which, when or'd
with something else, tries to look itself up, and if it fails, returns
the second object. Actually, here's an even cleaner way. Let's suppose
those are dictionary-like objects that you fully control. Just do
this:

value = (d1  | d2 | d3)[key]

and have the "cache | cache" return a helper object that will try one
and then the other. Could be beautifully clean... but isn't a
replacement for except-expressions.

ChrisA


More information about the Python-ideas mailing list