For review: PEP 308 - If-then-else expression

holger krekel pyth at devel.trillke.net
Sun Feb 9 02:39:43 CET 2003


Evan wrote:
> Michele Simionato wrote:
> > Not convincing. For multiple choices one should use a dictionary. I am favorable
> > to a ternary operator but against a "case" operator.
> 
> Please explain how the following could be implemented with a dictionary 
> (note that f and g have side-effects, and should only be called if we 
> need their value):
> 
> x = {if a == 1: f(),
>          g() == 'asdf': 'g',
>          c > 4.5: 'yep'
>          'nope'}

uh. that's a pretty contrived example and thus you wouldn't
want to do it with a dictionary but with

    if a==1:
        x = f()
    elif g() == 'asdf': 
        x = g
    elif c>4.5:
        x = 'yep'
    else:
        x = 'nope'

which has the advantages that there is a defined order in
which the non-exclusive conditions are checked <wink>. 

And let me try it with PEP308 just for amusement:

x = f() if a==1 else g if g()=='asdf' else 'yep' if c>4.5 else 'nope'

easy, isn't it. 

    holger





More information about the Python-list mailing list