You can’t, but the reason is so fundamental that I think it worth posting anyway. In C, a pointer can be formed to any variable, including another pointer. (Another pointer variable, that is: you can write &p
, but not &(p+1)
.) In Python, every variable is a pointer but every pointer is to an object.
A variable, not being an object, cannot be the referent of a pointer. Variables can however be parts of objects, accessed either as o.foo
or o[bar]
(where bar might be an index or a dictionary key). In fact, every variable is such an object component except a local variable; as a corollary, it is impossible to assign to a local variable from any other function. By contrast, C does that regularly by passing &local
to whatever other function. (There is an exception to the "any other function": nonlocal
variables can be assigned, but every local variable used in a nested function is implemented by implicitly creating a cell
object as the underlying value of the variable and interpreting usage of the variable as referring to an attribute of it!)
This distinction is readily illustrated by C++ containers: they typically provide operator[]
to return a reference (a pointer that, like a Python reference, is automatically dereferenced) to an element to which =
can be applied, whereas the Python equivalent is to provide both __getitem__
(to return a reference) and __setitem__
(which implements []=
all at once to store to a variable).
In CPython’s implementation, of course, each Python variable is a PyObject*
variable, and a PyObject**
to one can be used for internal purposes, but those are always temporary and do not even conceptually exist at the Python level. As such, there is no equivalent for id
for them.