Get the instance name from a list by Reflection

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Oct 22 09:24:41 CEST 2007


--- sccs cscs <zorg724 at yahoo.fr> escribió:

> Thank you, but i believe that i could get all
> variables names that reference an instance: i need
> it for a special debug tool... It seems that
> knowledge exists somewhere into the Python
> interpreter...

Please read first the FAQ item posted previously, and this article:
http://effbot.org/zone/python-objects.htm
Then it should be clear that any object may be referenced by one name,
many names, or no name at all. By example:

py> a = [1, 2, 3]
py> b = "four"
py> a.append(b)
py> a
[1, 2, 3, 'four']
py> b = 5
py> c = b
py> id(b)
10049608
py> id(c)
10049608
py> b is c
True

In this case there is only one name referencing the list (a), two
names referencing the number 5 (b and c), and no name referencing the
string "four", altough it was earlier known as b.
Python is built around namespaces: mappings FROM names TO objects. A
name refers to a single object, but the inverse is not true. You can
invert the relation examining possible namespaces and seeing if the
object is referenced, and by which names. Something like this:

py> def invert(obj, namespace):
...   result = []
...   for key,value in namespace.iteritems():
...     if value is obj:
...       result.append(key)
...   return result
...
py> invert(a, globals())
['a']
py> invert(5, globals())
['c', 'b']
py> invert(123, globals())
[]
py> invert([1, 2, 3, 'four'], globals())
[]

You can pass globals(), locals(), vars(some_object) as the namespace
argument.

--
Gabriel Genellina




More information about the Python-list mailing list