How to access variable by id?

14,088

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

Share:
14,088
Gill Bates
Author by

Gill Bates

Updated on June 15, 2022

Comments

  • Gill Bates
    Gill Bates almost 2 years

    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.

  • jimhark
    jimhark over 11 years
    See also stackoverflow.com/a/1396690/514485. And like almost everyone else I caution you, you probably don't want/need to do this.