[Doc-SIG] Does the "is" operator only matter for mutable object?

Laura Creighton lac at openend.se
Mon Mar 7 02:29:51 CET 2011


In a message of Mon, 07 Mar 2011 10:30:08 +1000, Nick Coghlan writes:
>On Mon, Mar 7, 2011 at 9:08 AM, Laura Creighton <lac at openend.se> wrote:
>> Singleton objects such as ``True``, ``False``, and ``None`` are always
>> the same object. The canonical way to test whether an object is
>> a singleton is to test for object identity, not equality.  So:
>>
>>>>> if x is None:
>>    ... do something ...
>>
>> not
>>
>>>>> if x == None:
>>   ... do something ...
>
>Careful with that - "if x is True:" and "if x is False:" (along with
>s/is/==/) are almost always the wrong thing to do, but a reader could
>easily generalise the above to cover those two cases as well.
>
>Cheers,
>Nick.

Good point.  Indeed, that may be where people who write code like that
get the idea.  I've always wondered.

Ok.

Change to:

Testing the object identity of unmutable objects with the ``is``
or ``is not`` operators is rarely something you want to do, because the
result is implementation dependent.  But the canonical way to test
whether an object is None is to test for object identity, not equality.

so

>>> if x is None:	  # this is how we write it
    ... do something ...

not

>>> if x == None:        # don't do this.
    ... do something ...

-----------
I figure that the fact that None is a singleton is not actually relevant
to this.

Laura


More information about the Doc-SIG mailing list