else on the same line - howto

Alex Martelli aleax at aleax.it
Wed Oct 15 12:22:12 EDT 2003


Peter Hansen wrote:

> Terry Reedy wrote:
>> 
>> "Helmut Jarausch" <jarausch at remove.igpm.rwth-aachen.de> wrote in
>> message news:bmj859$iph$1 at nets3.rz.RWTH-Aachen.DE...
>> > Since Python lacks conditional expression
>> > like
>> >
>> > k+= (dy >= 0 ? 1 : -1)
>> 
>> For this specific example:
>> 
>> k+= (dy >= 0 and 1 or -1)
>> 
>> But don't do this unless and until you 1) understand why this works
>> and why the and branch must be non-null and what happens if it is null
>> (this is discussed both in the FAQ and PEP 308) AND 2) accept
>> responsibility for always remembering the caution.
> 
> Is it "non-null" or "non-false"?

Non-false.  Anyway, if one really wants to obfuscate, why not:

    k += 1 - 2*(dy<0)

???  Now THAT is clever -- none of those plebeian, obvious

    if dy>=0: k += 1
    else: k -= 1

TWO-liners... first of all, if even your boss can understand
what your code is doing, you're not being clever enough and your
next raise or even your job could be at risk; second, with the
cost of lines these days, obviously saving a WHOLE line _IS_
worth all of the obfuscation in the world.


Alex

PS: I did think about inserting smilies, but I think colons and
closed parentheses are going up in price, too, so, in the same
spirit as the saving-one-line above, I decided I'd better not.





More information about the Python-list mailing list