how to get back an object from its id() value

Gary Herron gherron at islandtraining.com
Wed Apr 8 12:14:38 EDT 2009


TP wrote:
> Hi everybody,
>
> I have a data structure (a tree) that has one constraint: I can only store
> strings in this data structure.
>
> To know if an object foo already exists in memory, I store "str(id(foo))" in
> the data structure.
> OK.
>
> But how do I get a usable reference from the id value?
> For example, if "foo" has a method "bar()", how can I call "foo.bar()"
> from "str(id(foo))" (say, 149466208).
>   


Short answer:  You can't!

Longer answer:  You still can't, but you may be able to work around it:

(1)  Build up a dictionary in parallel to the structure:
        idMapper[id(foo)] = foo
      and later, index with
        idMapper[int(idString)] to get foo back

(2)  Get a different data structure.  This one is clearly not satisfying 
your needs.

(3)  Pickle (or marshal or serialize as it's also called) your object 
into a (perhaps) long string to store.  When the string is retrieved, 
unpickle to reconstruct an equivalent object.  This new version of the 
original foo may or may not be adequate for your use.



Gary Herron



> Thanks in advance,
>
> Julien
>
>   




More information about the Python-list mailing list