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).
source share