9
votes

Possible Duplicate:
Get object by id()?

>>> var = 'I need to be accessed by id!'
>>> address = id(var)
>>> print(address)
33003240

Is there any way to use address of var in memory, provided by id(), for accessing value of var?

UPD:
I also want to say, that if this cannot be done in standard Python, it also would be interesting, if this somehow could be implemented via hacking C++ internals of Python.

UPD2: Also would be interesting to know, how to change value of var.

1
You can't. The return value of id() is not a reference. The fact that cpython returns a memory address here is a implementation detail, and using this as a reference is not the goal of the function. - Martijn Pieters♦
Why on any deity's name would you want to do that? Martijn is correct, even if you could somehow hack it in CPython, it's just an implementation detail. - pcalcao
Why do you want to do this? - Keith
What are you trying to achieve? There are probably other ways to achieve whatever you are need done. - Martijn Pieters♦
First goal: fun; Second: passing-by-reference - sometimes its needed for more flexibility, despite its not pythonic. Its a zen-question, no practical background. - Gill Bates

1 Answers

9
votes

A solution, only for your case, would be:

var = 'I need to be accessed by id!'
address = id(var)
print(address)
var2 = [x for x in globals().values() if id(x)==address]

It also works from inside a function like

def get_by_address(address):
    return [x for x in globals().values() if id(x)==address]

var = 'I need to be accessed by id!'
address = id(var)
print(address)
var2 = get_by_address(address)

But as others pointed out: First make sure there is no better solution that better fits your needs