问题
I know that variables in Python are really just references/pointers to some underlying object(s). And since they're pointers, I guess they somehow "store" or are otherwise associated with the address of the objects they refer to.
Such an "address storage" probably happens at a low level in the CPython implementation. But my knowledge of C isn't good enough to infer this from the source code, nor do I know where in the source to begin looking.
So, my question is:
In the implementation of CPython, how are object addresses stored in, or otherwise associated with, the variables which point to them?
回答1:
In module scope or class scope, variables are implemented as entries in a Python dict. The pointer to the object is stored in the dict. In older CPython versions, the pointer was stored directly in the dict's underlying hash table, but since CPython 3.6, the hash table now stores an index into a dense array of dict entries, and the pointer is in that array. (There are also split-key dicts that work a bit differently. They're used for optimizing object attributes, which you might or might not consider to be variables.)
In function scope, Python creates a stack frame object to store data for a given execution of a function, and the stack frame object includes an array of pointers to variable values. Variables are implemented as entries in this array, and the pointer to the value is stored in the array, at a fixed index for each variable. (The bytecode compiler is responsible for determining these indices.)
来源:https://stackoverflow.com/questions/61516096/how-is-variable-assignment-implemented-in-cpython