Understanding memory location of Python variables

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jun 17 06:45:42 EDT 2018


On Sun, 17 Jun 2018 11:01:41 +0100, Bart wrote:

> So, how /do/ you obtain the memory address of those values are located?

You don't. There is no implementation-independent Python function to get 
the memory address of an object.

The concept of a fixed memory address for objects is not even a sensible 
one. In Python, all objects conceptually live in the heap, but there is 
no concept that they must have a fixed address, or any address at all.

Depending on the memory management used by the Python virtual machine, 
the objects can move about as needed to free up blocks of unused memory. 
That's what IronPython and Jython do. Or, they could be like PyPy, where 
objects can conceptually disappear from existence and reappear when you 
look for them, a bit like quantum mechanics.

PyPy can replace objects with low-level native data structures like ints, 
perform a bunch of calculations, and then recreate any needed objects. So 
long as none of this has any visible semantic differences from CPython 
(it is allowed to be faster :-) the PyPy interpreter is allowed to do 
almost anything it likes: move objects, destroy them and reallocate them, 
convert them to native data and back, push them onto the call stack, 
whatever it takes.


> For example, in order to pass it to some foreign C function that 
> takes a void* parameter.

That's up to the implementation.

Jython and IronPython have little or no facility for calling C functions, 
hardly surprising since they are built on the JVM and .Net framework 
respectively.

In CPython, there is probably a ctypes interface to do this, but ctypes 
is implementation-dependent and not portable (PyPy supports it, but other 
implementations probably won't).

https://docs.python.org/3/library/ctypes.html

Or you can use the CPython C API to write an extension class.

https://docs.python.org/3/c-api/index.html




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list