Stringify object reference?

Jeff Epler jepler at unpythonic.net
Fri Oct 11 21:07:51 CEST 2002


On Fri, Oct 11, 2002 at 06:17:33PM +0100, Alan Kennedy wrote:
> Is there a specific reason why id()'s can't be turned back into objects?
> Is it an implementation specific thing? Or is it to stop people messing
> with pointers, etc?

Consider:

    >>> o = object()
    >>> del o

You want the storage for 'o' to be freed, since nothing can reference o
anymore.  (nothing else still holds a reference to 'o')

now consider
    >>> o = object()
    >>> i = id(o)
    >>> s = str(i)
    >>> del i
    >>> del o
    >>> i = int(s)
    >>> o = unid(i)

now you have taken the id of o, turned it into a string, deleted the
object (and the integer id, for good measure).  It's been garbage
collected.  How could unid() possibly work in this case?

On the other hand, if you don't mind that 'id(o)' makes o immortal, you
will have a program with unlimited growth in memory usage.  That's not
terribly useful either.

The only sane solution would be through a dictionary, where you have
some good way to clean out stale entries.  The way you do this will
probably be specific to your application.

Jeff

persmap = {}

def pid(o):
    persmap[id(o)] = o
    return id(o)

def pobj(id):
    return persmap[id]




More information about the Python-list mailing list