How do I get an object from the id()-identifier?

Tim Peters tim.one at home.com
Fri May 18 19:48:50 EDT 2001


[Mats Sjoberg]
> 	What I want to do is to store a reference to a python object in
> 	a tag in a normal Tkinter Text widget. Tags cannot be arbitrary
> 	objects (as far as I know) so I would have to store the references
> 	as the ids of the objects. I have considered using a dictionary
> 	for this but it doesn't seem that efficient.

What does "doesn't seem" mean?  Python dicts are very efficient.  Don't
dismiss it before you try it and determine that the dict is the true source
of perceived inefficiency.  It's going to consume a *lot* more time just to
get Tk to tell you which tags contain a cursor than it will to look up the
tags in a dict after you get them.

>     It would be easier, and faster, if I could just get the object
>     directly from the id.

You cannot, but we already covered that.  How do you think the implementation
could accomplish this?  An id is just a memory address.  If you save away
id(obj) and ask for the obj later, you're just handing Python an integer that
*at one time in the past* was the address of obj.  obj may not exist anymore,
and it's impossible to tell from a raw memory address whether or not that's
the case. The only way Python could support this without causing core dumps
is to maintain its own dict mapping addresses to objects.

> 	I might also have many different Text widgets with tags to the
> 	same object.

You can share a single dict, or give each widget its own dict, or define a
class abstracting all this away (pretend Python had the function you wanted,
then implement it -- we're not talking A Project here, this is about six
lines of dead-easy code).  Up to you, but it's going to run *fast* enough via
any of those ways.





More information about the Python-list mailing list