Permanent objects?

Tim Peters tim.one at comcast.net
Tue Dec 24 13:49:48 EST 2002


[Tom Zych]
> Here's an odd thing Python 2.2 does:
>
> >>> x = 0
> >>> y = 0
> >>> x is y
> 1
> >>> x = 99
> >>> y = 99
> >>> x is y
> 1
> >>> x = 100
> >>> y = 100
> >>> x is y
> 0

OTOH,

>>> def f():
...     x = 100
...     y = 100
...     print x is y
...
>>> f()
1
>>>

> >>> x = -1
> >>> y = -1
> >>> x is y
> 1
> >>> x = -2
> >>> y = -2
> >>> x is y
> 0

OTOH,

>>> def g():
...     x = -2
...     y = -2
...     print x is y
...
>>> g()
1
>>

> I'm guessing that Python keeps the integers from -1 to 99 as
> permanent objects so it doesn't have to create a brand new object
> for every piddling little [0] and such. Anyone know?

Yes, but it doesn't matter.  Python is free to optimize storage for
immutable objects under the covers, and code relying on whether it does is
broken.  For example, never use "is" to compare immutable objects, unless
you don't care what the result is <wink>.  The optimizations can (and do)
change across Python releases.





More information about the Python-list mailing list