Interesting behaviour of the assignment
Alex Martelli
aleaxit at yahoo.com
Thu Dec 28 09:12:57 EST 2000
"June Kim" <junaftnoon at nospamplzyahoo.com> wrote in message
news:92f4gk$qk6$2 at news.nuri.net...
> >>> a=100
> >>> b=100
> >>> a is b
> 0
> >>> a=99
> >>> b=99
> >>> a is b
> 1
>
> Is this an intended/expected result? What is the lying structure beneath
> this?
The current Python interpreter uses a special-trick (just
simple caching, actually) for the representation of small
integers, up to a certain threshold. This just shows the
threshold is now 100 (excluded).
A similar case:
>>> y="aufwiedersehen"
>>> y is "aufwiedersehen"
1
>>> z="arrivederci Roma, good-bye, au revoir!"
>>> z is "arrivederci Roma, good-bye, au revoir!"
0
>>>
Here, the special-trick is "intern'ing", not that it makes
much difference to the application-coder except that intern
IS exposed and available for (doubtful!) application code
direct use...:
>>> intern
<built-in function intern>
>>> z=intern("arrivederci Roma, good-bye, au revoir!")
>>> z is "arrivederci Roma, good-bye, au revoir!"
0
>>> z is intern("arrivederci Roma, good-bye, au revoir!")
1
>>> z
'arrivederci Roma, good-bye, au revoir!'
>>>
I think the correct level of awareness of these internals
issues is the following: 'is' is ``not fully reliable''
(or rather, not fully applicable from an application POV)
when the objects involved may be small integers or string
constants, in the following specific sense: a!=b ensures
not "a is b", but, if a==b, then whether "a is b" or not
depends on internals/implementation issues that you don't
really want to know about.
Thus, limit your use of 'is' to cases in which you know
"object-identity" is indeed meaningful: None, lists, tuples,
dictionaries, object instances, type-objects, etc.
(Actually, in the case of None, the semantics of is and
== are identical, but 'is' can be a tiny little bit faster).
In practice I find myself using == almost by reflex, e.g.
if type(x)==type(0):
when I KNOW I could safely and reliably write, instead:
if type(x) is type(0):
and perhaps gain a 1/1000th of a second if this is at
the heart of a heavily-executed loop... '==' is just a
by-far-too-more-frequent case, except perhaps in the
specific idion "x is None"!-)
Alex
More information about the Python-list
mailing list