More clever (ab)use of and and or

February 25, 2006

In a comment on the last entry I mumbled yet again how I was annoyed that Python doesn't have an equivalent of C's '? :' conditional expression operator. Then some neurons in the back of my mind woke up and asked 'didn't Guido van Rossum say he was going to add this to Python 2.5?'

In the process of trying to figure out if this was still happening (it is), I read this message (via here) and found out about a trick (used in the standard library no less) that gets most of what I want. For 'A ? B : C', we can write:

A and B or C

(Python precedence rules make this equivalent to '(A and B) or C'. It works because both and and or return the value of the last expression they evaluated.)

This isn't quite a full emulation of ?:, because it gives you C if A is true and B is something that Python will consider false, but it is close enough for many uses. Often my code is such that the A expression isn't true unless B has a non-empty, non-zero value. And if your C is guaranteed to be true, you can always invert the expression.

(This doesn't help the code in the last entry, though, since we can't guarantee that blst will be considered true is the caller supplied it, and our C default value will be considered false.)

Another day, another useful trick, and it's all because of a comment. (Which makes me very glad I bothered to add comments to DWiki.)

Sidebar: Python 2.5 conditional expressions

From Guido van Rossum's message , the syntax will be 'B if A else C' (to use my ordering). I'm not really sure I like this; in general, I don't like out of order syntaxes because they make me backtrack on expressions when I read them. (I touched on this before back here.)

According to the Python 2.5 release schedule, Python 2.5 is supposed to come out around 30 September 2006, so we have a while to wait for this.

Written on 25 February 2006.
« A trick for handling mutable default arguments
The hassle of email (as compared to RSS) »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Sat Feb 25 20:14:46 2006
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.