== More clever (ab)use of _and_ and _or_ In a comment on the [[last entry DefaultArgumentsTrick]] 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 http://mail.python.org/pipermail/python-dev/2005-September/056846.html]]?' In the process of trying to figure out if this was still happening (it is), I read [[this message http://mail.python.org/pipermail/python-dev/2005-September/056798.html]] (via [[here http://www.amk.ca/diary/2005/09/conditional_expression]]) 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 http://mail.python.org/pipermail/python-dev/2005-September/056846.html]] , 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 ../programming/ACIdiomIAvoid]].) According to the [[Python 2.5 release schedule http://www.python.org/peps/pep-0356.html]], Python 2.5 is supposed to come out around 30 September 2006, so we have a while to wait for this.