A = X > Y ? X : Y

Skip Montanaro skip at mojam.com
Thu Feb 10 09:24:10 EST 2000


    >> It can't be encapsulated into something that looks like a function
    >> call

    Michal> I betcha it can!... How about this?

    Michal> def  cStyleIIF(condition, iftrue, iffalse):
	    ...

This will only work if the variables being evaluated in the argument strings
are in the same module as the definition of cStyleIIF.  Otherwise they won't
be found.  To demonstrate this, place the following code in iif.py:

    def  cStyleIIF(condition, iftrue, iffalse):
	if eval(condition):
	    return eval(iftrue)
	else:
	    return eval(iffalse)


    x = 5
    y = 20
    a = cStyleIIF("x<y", "x", "y")

    def foo():
	q = 5
	r = 20
	a = cStyleIIF("q<r", "q", "r")

    foo()

then execute it.  You should get something like

    % python /tmp/iif.py 
    Traceback (innermost last):
      File "/tmp/iif.py", line 19, in ?
	foo()
      File "/tmp/iif.py", line 17, in foo
	a = cStyleIIF("q<r", "q", "r")
      File "/tmp/iif.py", line 4, in cStyleIIF
	if eval(condition):
      File "<string>", line 0, in ?
    NameError: q

nice-try-though-ly y'rs,

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
"Languages that change by catering to the tastes of non-users tend not to do
so well." - Doug Landauer




More information about the Python-list mailing list