On Sat, 23 Mar 2013 21:00:07 -0400, Roy Smith wrote: > In article <mailman.3657.1364085583.2939.python-l...@python.org>, > Fabian von Romberg <fromberg...@hotmail.com> wrote: > >> Hi, >> >> I have a single questions regarding id() built-in function. >> >> example 1: >> >> var1 = "some string" >> var2 = "some string" >> >> if use the id() function on both, it returns exactly the same address. > > Yup.
Nope. Did you actually try it? As far as I know, there is no Python implementation that automatically interns strings which are not valid identifiers. "some string" is not a valid identifier, due to the space. [...] > which is, of course, the result I expected. Then I tried: > >>>> z = "f" + "oo" >>>> id(z) > 3810944 > > which actually surprised me. 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 You're not actually testing what you think you're testing. In Cpython, which I assume you are using, there is a keyhole optimizer that runs when code is compiled to byte-code, and it folds some constant expressions like `a = "b" + "ar"` to `a = "bar"`. To defeat the keyhole optimizer, you need something like this: a = "bar" b = "".join(["b", "a", "r"]) although of course a sufficiently smart keyhole optimizer could recognise that as a constant as well. This, on the other hand, will defeat it: b = str("ba") + str("r") because the keyhole optimizer cannot tell whether str() is still the built-in function or has been replaced by something else. > but, again, none of this is guaranteed. Correct. -- Steven -- http://mail.python.org/mailman/listinfo/python-list