Pragmatics of the standard is() function

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Nov 26 18:01:13 EST 2011


On Sat, 26 Nov 2011 22:20:36 +0100, candide wrote:

> In which cases should we use the is() function ? The is() function
> compares identity of objects rather than values so I was wondering in
> which circumstances comparing identities of objects is really vital.

`is` is not a function. It is a keyword and an operator.

You should always use `is` when you intend to test for object identity, 
and never use `is` when you do not intend to test for object identity. 
For example:

TASK: check whether a number is equal to 42.

    # WRONG don't do this
    if x is 42: ...
    # RIGHT use equality instead
    if x == 42: ...

Object identity is the wrong solution here, because you cannot control 
whether Python will re-use the same object for every instance of 42, or 
different objects each time.


TASK: check whether an object is a specific sentinel value, and no other 
value, even if it happens to compare equal to the sentinel. The most 
common sentinel is the singleton None.

    # WRONG don't do this
    if x == None: ...
    # RIGHT use is instead
    if x is None: ...


Use of equality is inappropriate, because it tests whether the object 
compares equal to None. Although there are no built-ins that compare 
equal to None, there could be any number of custom objects that do, and 
so your code contains a bug: you intend to branch *only* on None, but 
might branch on some other object by mistake.


> Examining well reputated Python source code, I realize that is()
> function is mainly used in the following set form :
> 
> spam is None
> 
> But how much "spam is None" is different from "spam == None" ?

Even if you can guarantee that your code base does not contain any object 
which compares equal to None except for None itself (and how would you do 
that? a full audit of every line of code in every library you use?), the 
use of `is` should be preferred because it signals your intention much 
better.

If your intention is to accept arbitrary objects which compare equal to 
None, than by all means use == for your comparison. But normally the 
intention is to accept None, and nothing else.


> is() function makes comparaison of (abstract representation of) adresses
> of objects in memory. Comparing addresses of objects is a low level
> feature performed by low level langages such as C but seldom needed in
> high level languages like Python, isn'it ?

That is correct. You probably should rarely use `is`. Apart from testing 
for None, use of `is` should be rare.



-- 
Steven



More information about the Python-list mailing list