Is it possible to get the Physical memory address of a variable in python?
davea at ieee.org
Tue Nov 10 03:30:01 CET 2009
Benjamin Kaplan wrote:
> On Mon, Nov 9, 2009 at 7:47 PM, Ognjen Bezanov <Ognjen at mailshack.com> wrote:
>> Hello all,
>> Say I have a python variable:
>> a = "hello"
>> Is it possible for me to get the physical address of that variable (i.e.
>> where it is in RAM)?
>> I know that id(a) will give me it's memory address, but the address given
>> does not seem to correlate with the physical memory. Is this even possible?
>> Thank you!
> When you use Python, program in Python and not C. What do you need the
> memory location of a variable for? Python, like Java and .NET is a
> higher level language. You're not supposed to worry about things like
> the physical location in memory. There's probably some ugly hack using
> ctypes, or just writing the code in C but I don't know enough about
> Python's C API to know what it is.
> FWIW, even the id(x) == address of x is only an implementation detail
> of CPython. Other Python implementations don't use that scheme.
Following is for the CPython implementation. As Benjamin says, each
implementation can do different things, as long as the documented
semantics are preserved.
The "variable" aaa is not at any particular location, and will quite
likely move when you define a new "variable" bbb or ccc in the same
scope. aaa is just a dictionary entry after all, in some scope.
(Although it may be optimized, for locals, and for slots)
aaa is bound to a particular object, and that object won't move. That
object has an id() value, and I believe that id value is the address.
And when you bind aaa to a different object, there'll be a different
id() and address. But unless you're writing a C extension, the actual
address is kind of irrelevant, isn't it?
More information about the Python-list