Proposed PEP for a Conditional Expression
James_Althoff at i2.com
James_Althoff at i2.com
Fri Sep 14 17:52:41 EDT 2001
Terry J. Reedy wrote:
><James_Althoff at i2.com> wrote in message
>> Why not just start with something simple like a builtin "cond"
>function
>> approximating the following:
>> >>> def cond(expr, iftrue, iffalse=lambda:None):
>> ... if expr: return iftrue()
>> ... return iffalse()
>
>Because, as explained before, both iftrue and iffalse expressions are
>always both evaluated, which defeats one of the purposes of
>conditional expressions, which is to not evaluate expressions that
>will raise an exception.
>
>Terry J. Reedy
Even though Michael tried to clarify this confusion already, I guess I will
try again since it has come up twice now.
Key Point: the workaround I proposed does *not* have the problem mentioned
above because the "cond" function takes *functions* for arguments.
Observe:
Python 2.2a1 (#21, Jul 18 2001, 04:25:46) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>>
>>> from __future__ import nested_scopes
>>>
>>> def cond(expr, iftrue, iffalse=lambda:None):
... if expr: return iftrue()
... return iffalse()
...
>>> x = 0
>>> xinv = cond(x!=0, lambda:1/x)
>>> print xinv
None
>>>
Notice that lambda:1/x is not a problem. It is not evaluated when x==0.
This "cond" function is using the same idea as the "cond" special form in
Lisp and the ifTrue:ifFalse: method in Smalltalk -- i.e., pass in
unevaluated "result" expressions and only evaluate the appropriate one
according to the controlling "conditional" expression.
Hope this makes it clearer.
Jim
More information about the Python-list
mailing list