"constant sharing" works differently in REPL than in script ?
benjamin.kaplan at case.edu
Tue Jun 19 06:21:10 CEST 2012
On Mon, Jun 18, 2012 at 7:52 PM, <shearichard at gmail.com> wrote:
> Listening to 'Radio Free Python' episode 8 (http://radiofreepython.com/episodes/8/ - around about the 30 minute mark) I heard that Python pre creates some integer constants to avoid a proliferation of objects with the same value.
> I was interested in this and so I decided to try it out.
> First I did this at the prompt :
>>>> c = 1
>>>> print id(1)
>>>> print id(c)
>>>> c is 1
> So that matched what I'd heard and then I did this to test the limits of it :
>>>> c = 259
>>>> print id(259)
>>>> print id(c)
>>>> c is 259
> And that was reasonable too as the podcast mentioned it was only done for a small set of integers around zero.
> However when I wrote this script :
> c = 259
> print id(259)
> print id(c)
> if c is 259:
> print "%s - yes" % (c)
> print "%s - no " % (c)
> I got this output :
> C:\data\src\Python\foo>python untitled-2.py
> 259 - yes
> So what's going on here. The script seems to be sharing objects in a way the REPL isn't ?
> Can anyone explain please ?
> BTW this is all on : Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 .
Python the language doesn't specify anything about this sort of
behavior. CPython the implementation does all sorts of optimizations
to make code run more efficiently. Caching integers is one of those
optimizations. In the case where the code is compiled all at once (as
in the script) instead of one line at a time (the REPL), it can do
more optimizations. But as I said, none of this is in the
specification so you shouldn't rely on it. The general rule for the
"is" operator is that unless you specifically know that you need it,
don't use it.
More information about the Python-list