Identity inconsistency and unification of types and classes

Michael Chermside mcherm at
Tue Jul 1 23:30:57 CEST 2003

Rim writes:
> With the great unification of types and classes, what will happen to the
> following identity inconsistency?
> >>> class myint(int): pass
> ... 
> >>> a=int(1); b=int(1)
> >>> a is b
> 1
> >>> a=myint(1); b=myint(1)
> >>> a is b 
> 0

In all likelihood it will remain as it is. The current behavior is NOT what you 
think it is. For instance:

    ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on
    Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> a = int(32000)
    >>> b = int(32000)
    >>> a is b

The *actual* rule is this: if two objects x and y are not immutable, then
"x is y" will be false. Normally, you would want to use "x == y" instead,
to see if two objects were equal, but if what you REALLY want to know is
whether they will CONTINUE to be equal if one gets changed, then that's
what "is" is used for. (Plus occasionally for performance reasons, and
in the idiom "x is None", which isn't really any different from "x == None"
except if you redefine None, which you shouldn't do.)

For IMMUTABLE objects, there's no reason to EVER need "x is y"... since
you can't change either one, "x == y" will tell you whatever you need to
know. Thus Python is allowed to have "x is y" return either true OR
false, as an optimization. Programmers shouldn't rely on the result 
(except, as always, if you really know what you're doing). Right now,
Python allows "is" to return true between strings that are very short
and strings that appear in the source code, but sometimes not between
strings that are constructed at runtime. For integers, "is" will return
true between numbers in the range [-1..99], and may return false for 
numbers outside that range. Both of these rules are specific optimizations
and may change without warning.

What you CAN assume is that if you create a mutable subclass of int (why
would you do such a thing?), that "is" will return false on different
instances. If your subclass is immutable, you can't assume anything.

-- Michael Chermside

More information about the Python-list mailing list