[Baypiggies] Trip-up

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jul 28 23:22:03 CEST 2006


>> I keep reaching the point where I feel like I understand Python and
>> could even teach it, but then:
>>
>> >>> a = 123456
>> >>> b = 123456
>> >>> a is b
>> False
>> >>> 123456 is 123456
>> True


The confusion has to do with the misconception of numbers as somehow more 
special than other objects.  Numbers are objects in Python, just like 
anything else.

Just as list literals allocate new object instances:

############
>>> [] is []
False
############

we should expect the same behavior from the other literals.


It's only accidental (from the implementation) that the second case here 
that deals with numbers:

#######################
>>> 123456 is 123456
True
#######################

returns a true value.  If we change it to something else, we'll see 
something different:

################################
>>> 123000 + 456 is 123000 + 456
False
################################


If we wish to explicitely keep only one instance of a number at a time, we 
can intern these values in a cache:

############################################################
>>> cache = {}
>>> def internNumber(n):
...     if n not in cache:
...         cache[n] = n
...     return cache[n]
...
>>> internNumber(123000 + 456) is internNumber(123000 + 456)
True
############################################################


But this seems a bit of overkill to do this for numbers.  *grin* It might 
make more sense to take this effort for strings if we wanted to simulate 
the behavior that Lisp's symbols guarantee.


More information about the Baypiggies mailing list