if/elif chain with assignment expressions

Peter Abel PeterAbel at gmx.net
Mon Jul 12 21:40:53 CEST 2004


Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote in message news:<7xvfguflq1.fsf_-_ at ruckus.brouhaha.com>...
> Sometimes you want to compute an expression, then do something with
> the value if it meets a certain criterion; otherwise, try a different
> expression (and maybe different criterion) instead, etc.  With := as
> an assignment expression operator, you could write:
> 
>    if (y := f(x)) < 5:
>        fred(y)
>    elif (y := g(x)) < 7:
>        ted(y)
>    elif (y := h(x)) < 9:
>        ned(y)
>    etc.
> 
> Of course there are alternative ways of doing the same thing, but they
> all seem to be messier.

When I started learning C, I remember there were big efforts to
be done to comprehend that an assignment returns a value that could
be used for a boolean decision. Once I had understood it I was glad
to have it. But always there was a little pitfall cause an assignment
and a comparison of equality were legal C-code. And the compiler did
what I wrote and not alway what I wanted it to do. So Python forces
me to say excactly what to do and there are solutions for any case.
Let me change your lines to the followings:

>    if (assign('y',f(x)) < 5:
>        fred(y)
>    elif (assign('y',g(x)) < 7:
>        ted(y)
>    elif (assign('y',h(x)) < 9:
>        ned(y)

And I think this code is clear enough to be readable and
self-documenting. Python gives us the utils to do so as the
following snippet shows:

>>> def assign(symbol,value):
... 	globals()[symbol]=value
... 	return value
... 
>>> x=2
>>> f=lambda val:val*val
>>> if assign('y',f(x))<5:
... 	print 'y<5; y=',y
... else:
... 	print 'y>=5; y=',y
...
y<5; y= 4
>>> if assign('y',f(4))<5:
... 	print 'y<5; y=',y
... else:
... 	print 'y>=5; y=',y
...
y>=5; y= 16
>>> 

Hope it helps a bit.

Regards
Peter



More information about the Python-list mailing list