[Tutor] id()

Michael P. Reilly arcege@speakeasy.net
Thu, 26 Apr 2001 18:40:00 -0400 (EDT)


Stephen Aichele wrote
> 
> I have a question regarding the use of id(): basically, I'd like to find a way to reverse this process- in otherwords, is there a way to access a specific instance's attributes from the id # alone?  
> 
> I need to do this because in my app, I may have several instances of the same class up concurrently - all with the same variable name...  (I'm using wxPython) - I know that by reusing the variable name, I won't have access to any but the last instance created; however, I'm wondering if the previous instance IDs will still exist and if so, how to use them to access previous instances/windows...
> 

The short answer is: you won't be able to do what you are trying to do,
at all (if it is what I'm gathering).

Objects are areas of memory, yes, but dynamic memory (read malloc()
with references counts to free up the memory.  Variables are just bindings
to objects, if you reassign, you decrement the reference to an object
and increment the reference count to the new value.  The 'sys' module
has a nice function called getrefcount() which returns the number of
references and object has, plus one for the function argument itself.

>>> import sys
>>> class A:
...   pass
...
>>> a = A()
>>> sys.getrefcount(a)
2             - one for the binding to 'a', and one for the function call
>>> b = a
>>> id(a), id(b)
(135094016, 135094016)
>>> sys.getrefcount(a)
3
>>> a = A()  # create a new instance and bind it to 'a'
>>> sys.getrefcount(a), sys.getrefcount(b)
(2, 2)
>>> id(a), id(b)
(135094192, 135094016)
>>>

Now when the reference count gets to 0 (no references to the object), the
memory is freed, and therefore the memory is usable for another object.

Basically, reusing variables won't give you access to old values because
those old values may be gone and overwritten.

In any event, Python does not have a mechanism for taking a "id" of an
object and getting back the object itself.  You might want to go thru
past discussions on this in the Python newsgroup archives on the website.
<URL: http://groups.google.com/groups?group=comp.lang.python.%2a&q=id%28%29>

What you might want to do instead is place the objects in a list (maybe
as a class member) to keep track of them.  Just beware of "circular
references" - you will need to remove the object from the list as well
before the memory can be freed.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |