missing 'xor' Boolean operator

MRAB python at mrabarnett.plus.com
Tue Jul 14 17:58:27 EDT 2009


Ethan Furman wrote:
> Robert Kern wrote:
>> On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:
>>
>>> != does do what I want, except that it doesn't indicate to someone 
>>> reading
>>> the code that the operands are being treated as logicals.  
>>> (Readability is
>>> supposed to be one of the major selling points of Python).  But, this is
>>> probably good enough.
>>
>>
>> In the words of those greater than myself, "Not every one-liner needs 
>> to be in the standard library."
>>
>> def xor(a, b):
>>     return bool(a) != bool(b)
>>
> 
> Let's see...
> 
>   and returns the last object that is "true"
>   or  returns the first object that is "true"
> 
> so should xor return the only object that is "true", else False/None?
> 
> def xor(a, b)
>     if a and b:
>         return None
>     elif a:
>         return a
>     elif b:
>         return b
>     else:
>         return None
> 
How about:

def xor(a, b):
     return not b and a or not a and b



More information about the Python-list mailing list