Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variable by id? [duplicate]

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.

like image 465
Gill Bates Avatar asked Jan 10 '13 11:01

Gill Bates


People also ask

How do you find the ID of a variable in Python?

Python id() Function The id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created.

What is ID of a variable?

An ID variable is a variable that identifies each entity in a dataset (person, household, etc) with a distinct value. This article lists five properties of ID variables that researchers should keep in mind when creating, collecting, and merging data.


1 Answers

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

like image 145
Thorsten Kranz Avatar answered Oct 12 '22 00:10

Thorsten Kranz