Result of ``a is b''

David MacQuigg dmq at
Wed Mar 17 17:28:36 CET 2004

On Wed, 17 Mar 2004 02:42:49 GMT, Carl Banks
<imbosol at aerojockey.invalid> wrote:

>David MacQuigg wrote:
>> On Tue, 16 Mar 2004 18:00:04 -0500, cookedm+news at
>> (David M. Cooke) wrote:
>>>Personally, almost all my uses of 'is' are of the form 'x is None' or
>>>'x is not None'.
>> Here are some more test results (averaging 10,000 evaluations in a
>> tight loop):
>>        time (sec)    %
>> Test 1: 3.68E-007   100.0 F is False
>> Test 2: 4.87E-007   132.1 F == False
>> Test 3: 3.71E-007   100.0 N is None
>> Test 4: 5.51E-007   148.6 N == None
>> The '== None' test is 49% slower than 'is None', but in absolute time,
>> the difference is only 180nec (on my new, but not top-speed PC).  So
>> it would take about 10 million of these comparisons in a short time to
>> make a noticable difference to the user.
>> I can't see where the 'is' test would *ever* be needed for the above
>> comparisons.
>Say you define the following class:
>    class SomeRankedObject:
>        def __init__(self,rank):
>            self.rank = rank
>        def __cmp__(self,other):
>            return cmp(self.rank,other.rank)
>Now, try to test it against None with "==":
>    x = SomeRankedObject()
>    x == None
>Oops, the Python interpretter just chewed you out for trying to access
>the nonexistent 'rank' attribute of the None object.

Here is the test using Python 2.3.3:

>>> x = SomeRankedObject()
TypeError: __init__() takes exactly 2 arguments (1 given)  <== AS
>>> x = SomeRankedObject(17)
>>> x == None
False                         <== AS EXPECTED
Which version of Python are you using?

>If you want to test whether two expressions are the same object, use
>"is".  Otherwise, use "==".  Period.  It's as close to an absolute
>rule as you'll ever find in programming.

Your missing the point.  The question is why do we ever need to test
'x is None' instead of 'x == None'.

We should keep the definitions of 'is' and '==' as they are, but
discourage the use of 'is' unless you really do care if the tested
objects are the same objects in memory.

The importance of this is that implementation can change, even for
something as simple as the None object.  We just had a long discussion
on enhancing the Reload() function, and concluded that the desired
change (updating all references to reloaded objects) would require
preserving a unique identity for simple objects like 'a = 2', 'b =
None', etc., in the reloaded module.  So if this change is made, you
might find in some future version of Python that 'b is c' returns
False even though they have both been set to None.

Here is my "is" rule:

    Use 'is' to compare two references only if it is important that
    they refer to the same object in memory.

and its corrolary:

    Use '==' if all you are concerned about is equality of value.

-- Dave

More information about the Python-list mailing list