Interesting behaviour of the assignment

Tim Peters tim.one at home.com
Thu Dec 28 20:48:43 CET 2000


[June Kim]
> >>> a=100
> >>> b=100
> >>> a is b
> 0
> >>> a=99
> >>> b=99
> >>> a is b
> 1
>
> Is this an intended/expected result?

Python doesn't define when it will and won't reuse the same object for an
integer literal, or, indeed, for any immutable object.  If you want to
compare immutable objects, use "==".  If you want to get *really* scared
<wink>, consider function f() here:

>>> a = 100
>>> b = 100
>>> a is b
0
>>> a = 99
>>> b = 99
>>> a is b
1
>>> def f():
	a = 100
	b = 100
	return a is b

>>> print f()
1
>>>

> What is the lying structure beneath this?

Internal optimizations, that can and do vary across implementations.  In
2.0, it just so happens that CPython always stores positive ints < 100
uniquely, and reuses other int objects if and only if the literals appear in
the same code block (which is why f() reused 100, but the one-at-a-time
bindings at the interactive prompt didn't -- each chunk of code entered at
the prompt is compiled into its own, new code block).   None of that can be
counted on across releases, though, and if you think you *need* to figure it
out you're confused about something deeper <0.5 wink>.

so-if-it's-not-just-idle-curiosity-tell-us-what-you're-trying-to-
    accomplish-ly y'rs  - tim





More information about the Python-list mailing list