Python id of name and '__main__' different

python

Solution

id() gives essentially the memory pointer to the data. Although strings are immutable, they are not guaranteed to be interned. This means that some strings with equal values have different pointers.

For integers (especially small ones), the pointers will be the same, so your `3` example works fine.

@KartikAnand: The way you're checking for 'same object' is valid, although the usual way is to use `x is y`. The problem is that they are not the same object, and not guaranteed to be. They simply have the same value. Note that when you do `"__main__"` you're creating a new object. Sometimes python does a nice optimization and re-uses a previously-created string of the same value, but it doesn't have to.

Kartik's goal is to "verify that assignment is in a way reference and objects are not created on the fly". To do this, avoid creating new objects (no string literals).

>>> __name__
'__main__'
>>> x = __name__
>>> id(__name__)
3078339808L
>>> id(x)
3078339808L
>>> __name__ is x
True

Problem

Normally if I assign a variable some value, and then check their ids, I expect them to be the same, because python is essentially just giving my object a "name". This can be seen in the below code: ``` >>> a = 3 >>> id(a) 19845928 >>> id(3) 19845928 ``` The problem is when I perform the same with "name" ``` >>> __name__ '__main__' >>> id(__name__) 19652416 >>> id('__main__') 19652448 ``` How can there ids be different, shouldn't they be the same? Because `__name__` should also be just a reference.

Original source