I know variable is just a tag to an object
example num=10,
num becomes tag/reference
10 becomes the object stored in heap memory
where does num get stored?
1 Answer
Ultimately it's in heap memory too; either:
- It's a global, in which case the name it ends up as a key in the
dictcontaining the module globals, with the value storing the reference to the actual object, or - It's a local, in which case the "name" is described in the function metadata itself, and the reference to the value ends up in an array of local references stored in the frame object allocated on entering the function (and typically freed when the function returns, though closures and exception-triggered tracebacks can cause the frame to last beyond the lifetime of the function call itself). The actual bytecode doesn't really use the name, it's converted to the index into the array of locals for speed, but the same index can retrieve the name for debugging purposes from the function metadata.
Since dicts, functions, and frames are all heap allocated, the binding to the name is ultimately in heap allocated memory.
1 Comment
ShadowRanger
To be clear, I'm describing the CPython (the Python reference interpreter) implementation, which may not translate directly to other interpreters, e.g. the CPython concept of frames is not universal. The constraints of the language spec would lead to similar designs in other implementations though.
disin a REPL.