Proposed PEP for a Conditional Expression

James_Althoff at i2.com James_Althoff at i2.com
Mon Sep 17 12:30:11 EDT 2001


Tom Payne wrote:
>As far as I can tell, it doesn't work if x is a local variable.  Have
>you actually tried it?

Yes.  And the following example Python run was included in my original
post:

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 = -2
>>> abs = cond(x>=0, lambda:x, lambda:-x)
>>> abs
2
>>> l = [7,8,9]
>>> firstItem = cond(len(l)>0, lambda:l[0])
>>> firstItem
7
>>> l = []
>>> firstItem = cond(len(l)>0, lambda:l[0])
>>> print firstItem
None
>>>

Jim






More information about the Python-list mailing list