This may help you understand what is going on:
In [1]: hex(id(1))
Out[1]: '0x109af50a0'
In [2]: hex(id(2))
Out[2]: '0x109af50c0'
In [3]: var = 1
In [4]: hex(id(var))
Out[4]: '0x109af50a0'
In [5]: var = 2
In [6]: hex(id(var))
Out[6]: '0x109af50c0'
Notice that the id
follows the value and not the variable.
It might also be helpful to look at the documentation for the id
built-in:
id(object)
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id()
value.
CPython implementation detail: This is the address of the object in memory.
When we write something like hex(id(var))
we are asking for the hexadecimal version of the address of the object stored in var
.
If we want to test if var
is immutable, our only option is to attempt to assign something to it and check if an exception occurs.
In fact, it is impossible to declare a variable that cannot be changed in Python. The closest you can get is to declare an instance of a class that throws an exception if you try to assign a value to its properties. For more information on that, see this question:
How do I create a constant in Python?