Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Given an adress, how can I access the object in Python?

How can I access a Python object by it’s address that I get from id(self.__dict__)?

The background is the following, I want to access one class instance from the other (both classes mimic custom dictionaries):

class1:
    def __init__(self):
        self.a =  class2(self)
        # I also tried self.a = class2(self.__dict__) which also does not seem to be a good idea

class2:
    def __init__(self, parentobject):
        self.parentobject = parentobject     

As both class implement dictionaries, I can’t iterate over them due to infinite self-referencing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One way to get it working, I thought, would to pass and save only the address of the "parent" class instance.
But in order to access it, I would need to transform somehow the address into something I can access.

>Solution :

This is a way to do what you’re asking, but I’m not sure this works on just any implementation of Python besides the standard CPython, which uses the memory address of objects as their id. That’s an implementation detail entirely specific to CPython though. As for whether you should even be trying to do this, I’m not here to judge that:

import ctypes

# create an object
a = [1, 2, 3]

# get the id of the object
b = id(a)

# access the object by its id
c = ctypes.cast(b, ctypes.py_object).value

# print the object
print(c)  # output: [1, 2, 3]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading