[Chicago] newbie says HI; needs help

Ian Bicking ianb at colorstudy.com
Fri Jan 20 18:44:38 CET 2006


Atul Varma wrote:
> On 1/20/06, Andrew Dudzik <adudzik at gmail.com> wrote:
> 
>>What I meant was:
>>
>>stock = (2,1)[texture in ["flakey","caked"]]
> 
> 
> Whoa.  Uh, I've been using Python fairly regularly for almost 3 years
> and a co-worker had to tell me that this was an index into a tuple for
> me to understand it--at first I thought it was some sort of language
> construct I'd never encountered before.
> 
> The same co-worker told me that he thought it was "clever", but that
> if I ever saw him writing code like that, I should shoot him. ;)
> 
> Aside from being difficult to read, though, I also think it's a "hack"
> in the same way Andrew's original "hack" was, in that it relies on the
> fact that the boolean result "False" maps to 0 and "True" maps to 1. 
> Even if this is defined in the Python language specification, I think
> that using a boolean as an integer by using it as an index into a list
> (or subtracting it from an integer) is conceptually unclear.

Indeed it is bad style.  It can also be buggy -- many expressions aren't 
required to return exactly True or False, just truish or falsish values 
(e.g., None for false, or "t" for true).  "and" and "or" notably will 
often result in something other than True and False, e.g., "5 or 3 == 5" 
and "'' and True == ''".

Boolean operators can also be made to return non-booleans, but this is 
less common.  So if you really need to make sure something is True or 
False, you have to use bool() on the value.  Though "in" in particular 
does seem to always return True or False.

If you really need conditional expressions (before Python 2.5) I would 
recommend this function:

def test(cond, t, f):
     if cond:
         return t
     else:
         return f

Recognizing that t and f will always be evaluated (whereas "a and b" 
will only evaluate "b" if "a' is false).  I find this convenient in 
templates sometimes, where there are places where statements aren't allowed.


-- 
Ian Bicking  /  ianb at colorstudy.com  /  http://blog.ianbicking.org


More information about the Chicago mailing list