How are variable names stored and displayed internally?

I am reading https://stackoverflow.com/a/4646269/ and it seems that in CPython, variables are just names associated with links.

Several things happen with the statement x = 5:

  • an int is created with a value of 5 (or found if it already exists)
  • the name x is created (or disabled with the last object 'x' marked)
  • reference counter for a new (or found) int object increased by 1
  • name x is associated with an object with a value of '5' created (or found).

However, I still do not understand how exactly the internal variables are implemented.

Namely:

  1. name x is created (or not associated with the last object "x");

Then will this name occupy memory? sys.sizeof(x) equals sys.sizeof(5) , and I get that sys.sizeof(x) can only return the size of the linked link, but then what is the size of the name x ?

  1. name x is associated with an object with a value of '5' created (or found)

How is this implemented domestically? I think that at a high level this can be done using dict , where the key is the name of the variable ( str ?), And the value is the link with which it is associated.

+10
source share
1 answer

I think that at a high level this can be done using dict, where the key is the name of the variable (str?), And the value is the link with which it is associated.

This is how it works inside. In CPython, the variable names and the objects they point to are usually stored in the Python dictionary; the same data structure that you can use when writing Python code.

When you write x = 5 , the name x is set as the key in the global names dictionary with 5 as the corresponding value. You can return and check this dictionary using the globals() function, which returns the contents of the current area namespace.

So you are also right that the name x takes place. It exists as a string somewhere in memory, and Python stores a reference to it for the dictionary key.

If you want to look deeper into the source of CPython to see where x gets the value 5, you can take a look at ceval.c. Writing x = 5 starts the operation code LOAD_CONST (to put the integer 5 on the stack), as well as the operation code STORE_GLOBAL * (to set the name x as the key in the dictionary with the value 5 as the value).

Here is the code for STORE_GLOBAL operation STORE_GLOBAL :

 TARGET(STORE_GLOBAL) { PyObject *name = GETITEM(names, oparg); PyObject *v = POP(); int err; err = PyDict_SetItem(f->f_globals, name, v); Py_DECREF(v); if (err != 0) goto error; DISPATCH(); } 

You can see the PyDict_SetItem call to update the global variable dictionary.


* If you check the bytecode generated by x = 5 (for example, using dis ), you can see the STORE_NAME operation code STORE_NAME . This opcode functions in the same way (see here for a brief description).

+8
source

All Articles