(test) ? a:b

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Oct 25 20:10:05 EDT 2014


Ben Finney wrote:

> Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
> 
>> Of course it won't be clear to *everyone* but it should be clear
>> enough to people who are familiar with standard Python idioms. A
>> concrete example should be more obvious than the fake example:
>>
>> title = ('Mr', 'Ms')[person.sex == 'F']
>>
>> which should be clear to anyone who understands indexing in Python and
>> that True == 1 and False == 0.
> 
> I consider it an accident of history, and one which should not be
> necessary to understand Python code.
> 
> In other words, I consider code which exploits the equality of True with
> 1, or False with 0, is code with a leaky abstraction and should be
> fixed.

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.

Equating True with 1 and False with 0 is fundamental to many programming
languages, but more importantly Boolean Algebra itself normally identifies
True with 1 and False with 0. 

https://en.wikipedia.org/wiki/Boolean_algebra
http://mathworld.wolfram.com/BooleanAlgebra.html

Admittedly this is only a convention, and you're welcome to invent your own
convention, but when doing so you should be aware that Python's convention
is mathematically sound and, well, conventional.

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)

If you reject implicit or explicit bool-to-int conversions:

sum(1 if not line.strip() else 0 for line in lines)

or for compatibility with Python 2.4:

sum({'': 0}.get(line.strip(), 1) for line in lines)

which I consider far less obvious than the straightforward summation of True
values. Sometimes making things *too* abstract is worse than allowing an
abstraction to leak.


-- 
Steven




More information about the Python-list mailing list