(test) ? a:b

Dan Stromberg drsalists at gmail.com
Sat Oct 25 18:34:06 EDT 2014


On Sat, Oct 25, 2014 at 1:45 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
>> 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 don't like the (a, b)[True] thing, but I use the fact that True is 1
and False is 0 sometimes.

EG, if I have 3 mutually exclusive command line options, I'll do something like:

if option_a + option_b + option_c != 1:
   sys.stderr.write('{}: -a, -b and -c are mutually
exclusive\n'.format(sys.argv[0]))



More information about the Python-list mailing list