addressof object with id()

Chris Angelico rosuav at gmail.com
Sat Mar 23 21:31:35 EDT 2013


On Sun, Mar 24, 2013 at 12:00 PM, Roy Smith <roy at panix.com> wrote:
> I had thought interning only affected
> string literals, but apparently it works for all strings!  This works
> too:
>
>>>> a = "b" + "ar"
>>>> b = "ba" + "r"
>>>> id(a)
> 3810152
>>>> id(b)
> 3810152
>
> but, again, none of this is guaranteed.

No, what that proves is that concatenation of literals is treated as a literal.

>>> a="foo"
>>> b="fo"
>>> b+="o"
>>> id(a)
14870112
>>> id(b)
15985760
>>> c="fo"+"o"
>>> id(c)
14870112

However, you can of course force the matter.
>>> a=sys.intern(a)
>>> b=sys.intern(b)
>>> c=sys.intern(c)
>>> id(a),id(b),id(c)
(14870112, 14870112, 14870112)

(In Python 2, use intern() rather than sys.intern().)

It seems that in CPython 3.3.0 on Windows 32-bit (and yes, I do need
to be that specific, though this probably applies to a broad range of
CPython versions), string literals are interned. But that's an
implementation detail.

ChrisA



More information about the Python-list mailing list