how do you get the name of a dictionary?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Mon Aug 21 22:34:45 EDT 2006


On Mon, 21 Aug 2006 16:59:30 -0700, 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.

No, it doesn't seem reasonable for objects to know the names they are
known as. It would require extremely major changes to Python, for minimal
benefit. Do you have a practical example of where this would be useful? I
can't think of any other language that has such a feature, except in very
limited areas (e.g. classes and functions know the name they were defined
as, not necessarily the names they are bound to).

And how would you use it? Let's suppose there is such a function,
GetObjectName(). What do you suggest?

>>> mydict = {}
>>> print GetObjectName({}) # but this dict is not the same as mydict
''
>>> print GetObjectName(mydict)
'mydict'

But if you have to type mydict as the argument to the function, why not
just wrap it in quotes (two characters instead of 15) and use that?

And what should GetObjectName(notmydict) return? Raise an exception?


> 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?

If you know a person's name, you can look up their number in the phone
book easily. If you know their phone number, it is much, much harder to
look up their name -- unless you go to the time and effort of keeping a
"reverse phone book".

For phone numbers, the phone companies keeps a reverse phone book because
it is useful to them; for Python, it isn't clear that there is any
practical use. Unless there is a practical use for that "reverse phone
book" , why should Python go to all the effort of keeping it?



-- 
Steven D'Aprano 




More information about the Python-list mailing list