class a(object):
    pass

b = a()
print id(b)
20441744

Is it possible to get the instance from this number/address?

Dani AI

Generated

Short answer: not in a portable, reliable way. is right that, for CPython, id() is the object identity (in CPython that is the memory address), but that identity is only guaranteed to be unique during the object's lifetime — there is no built-in, portable API that takes an id integer and returns the original object id() docs.

Practical options:

  • Track objects yourself. 's dictionary approach works but keeps strong references and prevents garbage collection; prefer a weak-value mapping so objects can still be collected:
import weakref

_by_id = weakref.WeakValueDictionary()

class MyClass:
    def __init__(self):
        _by_id[id(self)] = self

# later: obj = _by_id.get(target_id)

(see weakref docs).

  • Debugging/hacks for CPython only: you can scan gc.get_objects() and compare id() values (slow and only sees tracked objects), or reconstruct an object from an address using ctypes — both are CPython-specific and unsafe:
# scan (slow)
import gc
for o in gc.get_objects():
    if id(o) == target_id:
        found = o
        break
# unsafe: may crash if address is invalid
import ctypes
obj = ctypes.py_object.from_address(target_id).value

(see gc docs and ctypes docs).

Cautions: these techniques are implementation-specific, can crash or return garbage if the id was reused, and are not recommended for production code. If you need to look up objects by identity, the robust pattern is to maintain a (weak) registry when objects are created.

Recommended Answers

All 2 Replies

I don't think there's a built-in way to do this. Of course you can roll your own with a dictionary, viz:

class a(object):
	IDmap = {}
	def __init__(self):
		a.IDmap[id(self)] = self

b = a()
print id(b)           #  13975472
print a.IDmap[id(b)]  #  <__main__.a object at 0x00D53FB0>

Of course, 0x00D53FB0 == 13975472

Isn't the number just an arbitrary pointer to a place in the memory that has been allocated for the given instance?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.