how to cast an instance id

Emile van Sebille emile at
Tue Sep 17 15:34:33 CEST 2002

Eric Texier:
> It there a way to create a new reference of  an object
> from the string representation of its id?
> Thanks for any help.
> class foo:
>     def info(self):
>         print self
> a = foo()
> ccc = "newa = 0x%x" % id(a)
> exec(ccc)

There are ways of walking the object hierarchy checking ids, eg:

ccc = id(a)
for ii in locals().values():
    if id(ii) == ccc:
        ccc = ii

Or, you can set things up specifically to support this if you know in

class foo(object):
    objlist = {}
    def __init__(self):
        foo.objlist[id(self)] = self
    def info(self):
        print self

a = foo()
ccc = id(a)
ccc = foo.objlist[ccc]
print ccc

That said,  there's probably a better way, ie, setting ccc to a instead
of the id of a in the first place.  Otherwise, you risk retaining ccc
when a could have been refcounted away.


Emile van Sebille
emile at


More information about the Python-list mailing list