bool behavior in Python 3000?

Alexander Schmolck a.schmolck at gmail.com
Thu Jul 12 17:19:37 EDT 2007


Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> writes:

> Expressions like (i == j) used to return 0 and 1, and it was to avoid
> breaking hacks like the above that bools were implemented as a subclass of
> int, not because being able to write the above was a specific feature
> requested. In the hypothetical bright new world of Python with bools that
> are actually bools, the above are good cases for explicit being better than
> implicit:
>
>     int(x < b) * f(x)
>     -1 ** int(i == j)
>
> It makes more sense to explicitly cast bools to ints when you want to
> do integer arithmetic on them, rather than explicitly casting bools to
> bools to do boolean arithmetic! I feel strongly enough about this that I
> believe that being able to write (x < b) * f(x) is a DISADVANTAGE -- it
> gives me a real WTF moment to look at the code.

Just because it looks funny to you doesn't mean it is a hack. It turns out
that many mathemtical formulas can be written more clearly using this notation
(see e.g. at knuth et al's "concrete mathematics"), and in mathematics limited
and often ambiguous ad hoc notation that is neatly subsumed by this scheme is
widely established.

And I don't think adding int is an improvement: ``(x < b) * f(x)`` is plenty
clear (not easily misread as something else and, I believe, not even
particularly difficult to figure out even for mediocre python programmers) but
adding padding just obscures formula structure. Of course it doesn't in the
above examples with less than half a dozen terms, but IMO for something longer
the int-litter, even it may be soothing the psyches of the anally retentive,
is counterproductive.

'as



More information about the Python-list mailing list