(test) ? a:b

Ben Finney ben+python at benfinney.id.au
Sat Oct 25 16:45:30 EDT 2014


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.

> Although that's probably better written as a dict lookup:
>
> title = {'M': 'Mr', 'F': 'Ms'}[person.sex]
>
> which is then more easily extended to support intersex and
> non-traditional[1] gender identities.

It's true that gender is not a binary, but even if it were, this would
be a bad idea.

A schema which blurs the distinction between boolean versus integer is a
code smell: it speaks to the high likelihood that the “flag” really
represents an entity which will soon have more than two states, and
should never have been represented as a boolean.

-- 
 \     “As scarce as truth is, the supply has always been in excess of |
  `\                                       the demand.” —Josh Billings |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list