how to cast an instance id

Emile van Sebille emile at fenx.com
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()
> a.info()
> 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
        break

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

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 fenx.com

---------







More information about the Python-list mailing list