I read https://stackoverflow.com/a/19721096/1661745 and it seems that in CPython, variables are simply names that are associated with references.
There are several things going on with the statement x=5:
- an int object with the value of 5 is created (or found if it already exists)
- the name x is created (or disassociated with the last object 'x' labeled)
- the reference count to the new (or found) int object is increased by 1
- the name x is associated with the object with the value '5' created (or found).
However, I'm still not clear with exactly how variables are implemented internally.
Namely:
- the name x is created (or disassociated with the last object 'x' labeled);
Then wouldn't the name also take up memory space? sys.sizeof(x)
equals sys.sizeof(5)
, and I get that sys.sizeof(x)
could only return the size of the associated reference, but then what is the size of the name x
?
- the name x is associated with the object with the value '5' created (or found)
How is this implemented internally? I think at a high level it can be done with a dict
, where the key is the variable name (str
?) and the value is the reference that it's associated with.