9
>>> a = "zzzzqqqqasdfasdf1234"
>>> b = "zzzzqqqqasdfasdf1234"
>>> id(a)
4402117560
>>> id(b)
4402117560

but

>>> c = "!@#$"
>>> d = "!@#$"
>>> id(c) == id(d)
False
>>> id(a) == id(b)
True

Why get same id() result only when assign string?

Edited: I replace "ascii string" with just "string". Thanks for feedback

martineau
  • 119,623
  • 25
  • 170
  • 301
dohvis
  • 164
  • 2
  • 7
  • 4
    Those are both ascii strings ... – mgilson Mar 09 '17 at 01:23
  • 2
    Also note that the interning (caching) here is a CPython implementation detail and it depends on _lots_ of things. Notice that if you put this in a script, you'll get different results than if you were running it in the REPL... – mgilson Mar 09 '17 at 01:31

1 Answers1

11

It's not about ASCII vs. non-ASCII (your "non-ASCII" is still ASCII, it's just punctuation, not alphanumeric). CPython, as an implementation detail, interns string constants that contain only "name characters". "Name characters" in this case means the same thing as the regex escape \w: Alphanumeric, plus underscore.

Note: This can change at any time, and should never be relied on, it's just an optimization they happen to use.

At a guess, this choice was made to optimize code that uses getattr and setattr, dicts keyed by a handful of string literals, etc., where interning means that the dictionary lookups involved often ends up doing pointer comparisons and avoiding comparing the strings at all (when two strings are both interned, they are definitionally either the same object, or not equal, so you can avoid reading their data entirely).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thanks a lot. Can you explain more detail about "interning means" ? – dohvis Mar 09 '17 at 20:11
  • 2
    @ner0: Short-version: Interned strings are strings in a global lookup table that guarantees unique identity for each value. So while two-non-interned strings could have the same value, yet be completely different objects, that can't happen if both strings are interned, which means two interned strings can be compared for equality by a simple pointer comparison, rather than comparing length, then checking characters one by one. Python interns the name of every class, attribute, variable (though it's not used for local scope normally), function, etc., because pointer checks speed lookup. – ShadowRanger Mar 09 '17 at 22:33
  • It also auto-interns (or does something closely equivalent) the empty string, and all length 1 ASCII (possibly latin-1?) strings, so they're singletons no matter how you make them without explicitly interning them. Again, all of this is implementation detail; it could change at any time if they thought it would improve performance, memory use, code simplicity, etc. – ShadowRanger Mar 09 '17 at 22:37