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?
Asked
Active
Viewed 569 times
0

Jorge Luis
- 813
- 6
- 21

Sonam Dorjit
- 9
- 2
-
[Feel free to browse the cpython source code if you're interested in looking into these things yourself](https://github.com/python/cpython). You might also get a better picture of how the memory management of your program works by playing around with [`dis`](https://docs.python.org/3/library/dis.html) in a REPL. – Green Cloak Guy Aug 23 '20 at 05:24
-
Note that python makes no guarantees about memory layout. Are you asking about a specific implementation? Are you asking about the *name* num, the *reference* num or the *value of* num? – MisterMiyagi Aug 23 '20 at 05:41
-
reference num in cpython. value of num i know is stored as an object in the heap. Is the reference num stored inside the stack? – Sonam Dorjit Aug 23 '20 at 09:57
-
Does this answer your question? [Does Python have a stack/heap and how is memory managed?](https://stackoverflow.com/questions/14546178/does-python-have-a-stack-heap-and-how-is-memory-managed) – Jorge Luis May 16 '23 at 11:25
1 Answers
4
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
dict
containing 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 dict
s, functions, and frames are all heap allocated, the binding to the name is ultimately in heap allocated memory.

ShadowRanger
- 143,180
- 12
- 188
- 271
-
1To 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. – ShadowRanger Aug 23 '20 at 05:35