Test None for an object that does not implement ==

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Dec 25 19:52:16 EST 2011


On Sun, 25 Dec 2011 15:45:10 -0800, Larry Hudson wrote:

> On 12/24/2011 11:09 PM, GZ wrote:
>> Hi,
>>
>> I run into a weird problem. I have a piece of code that looks like the
>> following:
>>
>> f(...., a=None, c=None):
>>      assert  (a==None)==(c==None)
>>
> <...>
> 
> At first glance this looked like it should be a simple boolean "and",
> but then I realized that when a and c are both unequal to None, the
> result would also be True.  This implies the logical approach would be
> exclusive-or (^).  Try this expression:
> 
>       not ((a==None) ^ (c==None))

^ is *bitwise* xor, not boolean xor. Python doesn't offer boolean xor 
directly, although != comes close.


> OTOH, if what you really want is simply to check that both are None (my
> first impression), then it's simply:
> 
>       (a==None) and (c==None)

Replace == with 'is'.

> Most of the replies you're getting here seem unnecessarily complicated.

== is a more complicated operator than the 'is' operator. That's why the 
is operator is to be preferred when testing for None -- it is guaranteed 
to do the right thing, while == is not.


-- 
Steven



More information about the Python-list mailing list