Re: [Info] PEP 308 accepted - new conditional expressions
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: [Info] PEP 308 accepted - new conditional expressions

From: Bengt Richter <bokr@oz.net>
Date: Sat Oct 01 2005 - 02:58:18 CEST

On Fri, 30 Sep 2005 20:25:35 +0200, Reinhold Birkenfeld <reinhold-birkenfeld-nospam@wolke7.net> wrote:

>Fredrik Lundh wrote:
>> Reinhold Birkenfeld wrote:
>>
>>> after Guido's pronouncement yesterday, in one of the next versions of Python
>>> there will be a conditional expression with the following syntax:
>>>
>>> X if C else Y
>>>
>>> which is the same as today's
>>>
>>> (Y, X)[bool(C)]
>>
>> hopefully, only one of Y or X is actually evaluated ?
>
>(cough) Yes, sorry, it's not the same. The same would be
>
>(C and lambda:X or lambda:Y)()
>
>if I'm not much mistaken.

I think you need to parenthesize, but also note that using lambda does not
always grab the currently-executing-scope X or Y, so I think the list container idiom
may be better to show the semantics of the new expression:

>>> X='this is global X'
>>> Y='this is global Y'
>>> C=False
>>> def foo():
 ... C = True
 ... class K(object):
 ... X='this is K.X'
 ... Y='this is K.Y'
 ... cv = (C and (lambda:X) or (lambda:Y))()
 ... return K
 ...
>>> def bar():
 ... C = True
 ... class K(object):
 ... X='this is K.X'
 ... Y='this is K.Y'
 ... cv = (C and [X] or [Y])[0]
 ... return K
 ...
>>> foo().cv
 'this is global X'
>>> bar().cv
 'this is K.X'

>
>>> C and X or Y (only if X is True)
>>
>> hopefully, "only if X is True" isn't in fact a limitation of "X if C else Y" ?
>>
>> /... snip comment that the natural order is C, X, Y and that programmers that
>> care about readable code will probably want to be extremely careful with this
>> new feature .../
>
>Yes, that was my comment too, but I'll not demonize it before I have used it.
>
Me too ;-)

Regards,
Bengt Richter
Received on Sat Oct 15 04:01:44 2005