(test) ? a:b
Chris Angelico
rosuav at gmail.com
Sat Oct 25 20:01:40 EDT 2014
On Sun, Oct 26, 2014 at 10:53 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
> Dan Stromberg <drsalists at gmail.com> writes:
>
>> 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]))
>
> That is an excellent illustration of why exploiting this accidental
> property of True and False leads to obfuscated code. The above test
> gives me no clue that we're operating on boolean values, nor that we're
> testing for exclusive options.
Would it be more readable thus?
if len([opt for opt in (option_a, option_b, option_c) if opt]) != 1:
Because that's what it's doing. I think treating bools as numbers is
fine. Matter of opinion I guess.
ChrisA
More information about the Python-list
mailing list