how to get memory location of a variable in Python

Question:

When we look at the following code,

my_var = "Hello World"
id(my_var)

The statement id(my_var) returns the address/location of the string-object "Hello World"

I was wondering if we have any command, with which I can get the address/location of my_var


I am trying to understand memory in Python. For example, in C-programming I can get the address of variable and pointer in following way

int var;
int *var_ptr = &var;

printf ("%d", var_ptr);  % Prints address of var
printf ("%d", &var_ptr); % Prints address of var_ptr

Answers:

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.

Answered By: Davis Herring

You can easily get address of any variable in python using id(var) function

a=5
print(id(a))
Answered By: Prathamesh Sable
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.