how do you get the name of a dictionary?

Duncan Booth duncan.booth at invalid.invalid
Tue Aug 22 03:57:48 EDT 2006


jojoba wrote:

> However, does it not seem reasonable to ask python:
> 
> Given a dicitionary, Banana = {}
> return one or more strings,
> where each string is the name(s) of the reference(s) to Banana.
> 
> why is this not sane?!?!
> what am i missing here?

Some time back I posted some code which would do exactly that, but it is 
not nice, and it is buggy, but if you want to play with it:
http://groups.google.co.uk/group/comp.lang.python/tree/browse_frm/thread/394ba5b48f83ebfb/237dc92f3629dd9a

>>> import varname
>>> Banana = {}
>>> class C:
...    classFruit = [{}, Banana]
...
>>> def names(x):
...     for s in varname.object_info(x):
...         print s
...
>>> names(Banana)
__main__.C.classFruit[1]
__main__.Banana
__main__.names()x

The problem as others have said is that there are a lot of namespaces in 
Python (module globals, classes, instances, local variables of active 
functions, ...), and the only way to find which names refers to an object 
is to search the relevant namespaces.

There is some information which can help: for any object you can get a list 
of all objects that refer to it, and that can be used to trace backwards 
until you find a namespace at which point you still have to search the 
namespace to find out which name refers to the object. Of course doing all 
this creates lots of new references and infinite loops both of which you 
have to ignore.




More information about the Python-list mailing list