Equivalent code to the bool() built-in function

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Apr 19 04:43:22 EDT 2011


On Tue, 19 Apr 2011 16:26:50 +1000, Chris Angelico wrote:

> On Tue, Apr 19, 2011 at 4:23 PM, Kushal Kumaran
> <kushal.kumaran+python at gmail.com> wrote:
>>> if a + b + c + d != 1:
>>>    raise ValueError("Exactly one of a, b, c or d must be true.")
>>>
>>>
>> Unless you're sure all of a, b, c, and d are boolean values, an int
>> with a negative value slipping in could result in the sum equaling 1,
>> but more than one of the variables evaluating to True in boolean
>> contexts.
> 
> If they're all expressions, then you can easily guarantee that.

*raises eyebrow*


Either of these should do the job:

    sum(map(bool, (a, b, c, d)))

    sum(bool(x) for x in (a, b, c, d))

but I don't see how 

(arbitrary expression) + (another expression) + ... + (last expression)

can have any guarantees applied. I mean, you can't even guarantee that 
they won't raise an exception. Can you explain what you mean?


-- 
Steven



More information about the Python-list mailing list