0

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?

4

1 Answer 1

4

Ultimately it's in heap memory too; either:

  1. 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
  2. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.