addressof object with id()
steve+comp.lang.python at pearwood.info
Sun Mar 24 03:01:22 CET 2013
On Sat, 23 Mar 2013 21:00:07 -0400, Roy Smith wrote:
> In article <mailman.3657.1364085583.2939.python-list at python.org>,
> Fabian von Romberg <fromberg100 at hotmail.com> wrote:
>> 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.
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"
> which actually surprised me. I had thought interning only affected
> string literals, but apparently it works for all strings! This works
>>>> a = "b" + "ar"
>>>> b = "ba" + "r"
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.
More information about the Python-list