Whoa! What is this is I see? was RE: [albatross-users] impedance mismatch 1
Matt Goodall
matt at pollenation.net
Thu Jul 3 19:13:01 EST 2003
There is a good description of the and or trick at diveintopython.org,
sepcifically http://diveintopython.org/apihelper_andor.html. Be sure to
read the "when end-or trick fails" section!
I admit to using this more than I should and Albatross has the
<al-lookup> tag which is a much better way of doing what I wanted in the
example I posted.
Cheers, Matt
Andrew McNamara wrote:
>>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.
>
>
>
--
Matt Goodall, Pollenation Internet Ltd
e: matt at pollenationinternet.com
t: 0113 2252500
More information about the Albatross-users
mailing list