Explaining names vs variables in Python

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Wed Mar 2 04:35:16 EST 2016


Salvatore DI DIO writes:

[- -]

> But where is the consistency ? if I try :
>
>>>> v = 890
>>>> w = 890
>>>> v is w
> False

I think it goes as follows.

Python keeps a cached pool of some numbers that may occur relatively
often. When a numerical expression evaluates to a cached value, it
returns the cached object instead.

>>> 1 + 1 is 2
True
>>> 800 + 90 + 0 is 890
False

This way programs don't fill the memory with a large number of copies of
frequently occurring numbers like 2, and also don't keep rare numbers
like 890 around in the cache unnecessarily.

Python doesn't keep track of how often numbers actually occur. I think
it considers 0, 1, 2, ..., n, up to some rather small n, heuristically
frequent, and that's it. Also, this is an implementation detail.

Hm, -5, -4, -3, -2, -1 also seem cached when I try them, but -6 not.

The following are too delicate for me. I suppose the answers could have
been different, but I can't guess what mechanism actually leads to these
results. Just idle curiosity on my part.

>>> 890 is 890
True
>>> id(890) == id(890)
True

>>> 890 is 891
False
>>> id(890) == id(891)
False

Python 3.4.3 (default, Oct 14 2015, 20:33:09) 
[GCC 4.8.4] on linux



More information about the Python-list mailing list