Whoa! What is this is I see? was RE: [albatross-users] impedance mismatch 1

Andrew McNamara andrewm at object-craft.com.au
Thu Jul 3 17:02:40 EST 2003


>Okay, one thing I miss that python doesn't have is the ?: operator.  But
>then Matt writes:
>
>"name.index()%2 and 'red' or 'green'".
>
>Which from my quick tests in idle seem to be working like ?:; with the
>execption of:
>
>1 and 0 or 2 returns 2 ( 1 ? 0 : 2 would return 0)  Which I can see why
>and I could work around that with int(1 and '0' or 2) If I need a0 for a
>true value (rare case).
>
>So my question is, is this a hack of python, or can I always expect this
>to stay the same across past and new versions of python? [...]

The language reference has this to say:

    The expression x and y first evaluates x; if x is false, its value
    is returned; otherwise, y is evaluated and the resulting value
    is returned.

    The expression x or y first evaluates x; if x is true, its value
    is returned; otherwise, y is evaluated and the resulting value
    is returned.

So, yes, the behaviour is defined, and it will not change. There are,
however, some gotchyas:

  - as you note, unlike ?:, the second expression is evaluated - if
    the second expression evaluates to False, then the last expression
    is returned irrespective of the first expression. Your example is
    equivilent to:

        (1 and 0) or 2 => 0 or 2 => 2

    So.. if the 2nd expression is a non-zero constant, you're okay.

  - if you forget and type "<expr> or <expr> and <expr>", the results will
    not be what you expect, and it's visually hard to see what's wrong.

A number of the python ghods are in favour of the and/or idiom, but I
prefer not to use it.

-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/



More information about the Albatross-users mailing list