(test) ? a:b

Ben Finney ben+python at benfinney.id.au
Sun Oct 26 02:03:28 CET 2014

Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:

> I suspect that Guido and the core developers disagree with you, since
> they had the opportunity to fix that in Python 3 and didn't.

That doesn't follow; there are numerous warts in Python 2 that were not
fixed in Python 3. As I understand it, the preservation of bool–int
equality has more to do with preserving backward compatibility.

I agree with the decision, because this isn't an issue which often leads
to *incorrect* code. But I maintain that it's an unfortunate and
needlessly confusing wart of the language.

> One example of where treating True and False as 1 and 0 is useful is
> that it makes counting operations very simple, e.g. counting the
> number of blank lines:
> sum(not line.strip() for line in lines)
> sum(1 if not line.strip() else 0 for line in lines)
> sum({'': 0}.get(line.strip(), 1) for line in lines)

These all look ludicrous and explain nothing about intent, to my
reading. The ‘bool’ type exists precisely because there is a concept to
be represented which is distinct from integers.

Using a sum on non-numeric values just cracks the abstraction open
needlessly. Once I figure out what is going on, I'm left wondering why
the coder chose something so obfuscatory to their intent.

This is short and clear and needs no leaking of the underlying bool

    len(True for line in lines if line.strip())

> which I consider far less obvious than the straightforward summation
> of True values.

Why sum them at all? You aren't interested in them as numbers, you're
just asking how many objects meet a criterion. That calls not for ‘sum’,
but ‘len’. There's no need to rely on an underlying ‘int’ operation just
to count objects.

The fact that summing them gives the same answer as simply asking how
many there are, demonstrates that nothing is gained by peeking into the
implementation. The example I give above works exactly as well with no
‘int’ underlying the ‘bool’ type at all.

 \      “The way to build large Python applications is to componentize |
  `\             and loosely-couple the hell out of everything.” —Aahz |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list