Effects of caching frequently used objects, was Re: Explaining names vs variables in Python
Peter Otten
__peter__ at web.de
Wed Mar 2 04:12:48 EST 2016
Salvatore DI DIO wrote:
> Hello,
>
> I know Python does not have variables, but names.
> Multiple names cant then be bound to the same objects.
>
> So this behavior
>
>>>> b = 234
>>>> v = 234
>>>> b is v
> True
>
> according to the above that is ok
>
>
>
> But where is the consistency ? if I try :
>
>>>> v = 890
>>>> w = 890
>>>> v is w
> False
>
> It is a little difficult to explain this behavior to a newcommer in Python
>
> Can someone give me the right argument to expose ?
You should not bother with object identity for objects other than None.
Some small integers are used a lot, e. g.
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getrefcount(0)
606
>>> sys.getrefcount(1)
918
>>> sys.getrefcount(256)
31
>>> sys.getrefcount(-1)
51
therefore as an optimization the Python developers decided to put -5...256
(actual range may vary across interpreter versions) into a cache and reuse
them rather than build a new object for every instance. This may save both
time and memory, but is otherwise irrelevant.
Something similar is done for strings:
>>> a = "hello"
>>> b = "hello"
>>> a is b
True
>>> a = "hello, world"
>>> b = "hello, world"
>>> a is b
False
But:
>>> a = "hello, world"; b = "hello, world"
>>> a is b
True
Again this is an optimization (mostly targeted at attribute names) which
should not affect the behaviour of a properly written Python program.
More information about the Python-list
mailing list