conventions/requirements for 'is' vs '==', 'not vs '!=', etc

Luis Zarrabeitia kyrie at uh.cu
Mon May 19 16:29:38 EDT 2008


On Monday 19 May 2008 03:39:36 pm destroooooy wrote:
> I'm wondering what is the canonical usage of the keywords 'is' and
> 'not' when you're writing conditionals and loops. The one I've been
> following is completely arbitrary--I use the symbols '==', '!=' for
> numerical comparisons and the words 'is', 'not' for everything else.

It's not arbitrary, and you shouldn't be using that convention.

The question is really about "equality" versus "identity". Two identical sized 
cubes may be equal, but they are certainly not the same cube. The main 
concept here: identity [usually] implies equality, but equality almost never 
implies identity (two objects that are equal may be distinct nonetheless).

More practical example, two angles with the same measure are equal by every 
mathematical concept, but opposing angles on a parallelogram are not the same 
one.

Sometimes, you need to test for equality, as in "is this user input equal 
to '1'?". Sometimes, you need to test for identity "is this user input 
this '1' that I have here?" (note: the second answer should be 'no', unless 
that by some dark magic the user manages to get that same '1' that is in your 
code).

The most common use case is equality. You test for equality with == and !=.
The darker case is identity. You test for identity with "is" and "is not". 
Whenever you use "is", ask yourself a question: does a negative answer makes 
sense if the objects are equal?

Personally, I like to use "is" with singletons. I find it easier to type and 
read "if param is None" than "if param == None", but some python developers 
dislike the first one because of the "dark magic" involved in knowing that 
None is a singleton.

When in doubt, test for equality. Use "is" only when you are certain that you 
know the difference. Python does some optimizations that may it seem like it 
is working with 'is' at first, but it really isn't:

In: a="hi"
In: b="hi"
In: a is b
Out: True        <-- dark magic here, python optimized the string storage,
In: a is "h"+"i" <-- by using the same object instead of creating a new one
Out: False       <-- but even that won't always work, so
                       

In: a="a very long string, at least longer than 'hi'"
In: b="a very long string, at least longer than 'hi'"
In: a is b
Out: False       <-- never, never rely on magic.

I hope I was useful.

Cheers,

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie



More information about the Python-list mailing list