Result of ``a is b''

Carl Banks imbosol at aerojockey.invalid
Tue Mar 16 21:42:49 EST 2004


David MacQuigg wrote:
> On Tue, 16 Mar 2004 18:00:04 -0500, cookedm+news at physics.mcmaster.ca
> (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.

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.


-- 
CARL BANKS                      http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon



More information about the Python-list mailing list