how do you get the name of a dictionary?

Patrick Maupin pmaupin at gmail.com
Tue Aug 22 00:09:17 EDT 2006


jojoba wrote:
> hello
>
> im quite surprised at the arrogance laid out by some of the above
> posters:
>
> 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?
>
> I mean, i can enter the name of the dicitonary and python knows what i
> am talking about, so why can't i go backwards to get one or more
> strings that are the names of the dictionary?
>
> There may indeed be a lack of one-to-one correspondence between names
> of dictionaries and dictionaries, but who cares, it is WELL DEFINED
> (unless i am insane as some of the above posters claim)
>
> Please PROVE to me why my question is invalid (or certifiably crazy to
> some).
>
> Thanks to all who could answer me WITH or WITHOUT derision.
> jojoba

Jojoba:

One thing which you might be missing is that an object might not even
have a name bound to it.  Consider:

Banana = {}
Tree = [Banana, 0]
del Banana

At this point, the dictionary which was originally named Banana still
exists, and is referenced from the list which is bound to Tree, but
doesn't really have an associated name.  It can only be referenced as
the first element of the Tree list.

However, if you _know_ that an object has some named references, they
can be retrieved.  An easy example is if you know the object is
referenced from inside the current module:

>>> Banana = {}
>>>
>>> Sam = Banana
>>> Bill = {}
>>>
>>> print [x for (x,y) in globals().items() if y is Banana]
['Sam', 'Banana']
>>

If you don't know which namespace the object might be referenced from,
it gets trickier.  You can certainly search the entire object hierarchy
if you want (this is done for things like debugging sometimes), but
this is time-consuming, which is why you shouldn't typically organize
your program in such a way that you have to ask the Python interpreter
what the name of a particular object is.  As people point out, Python
doesn't really directly know.  On the other hand, IF the object DOES
have a name, you can certainly write a program to rummage around the
object hierarchy and figure it out, but you should probably have a
really good reason before you go to that trouble.

Regards,
Pat




More information about the Python-list mailing list