how do you get the name of a dictionary?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Aug 22 20:36:24 EDT 2006


On Tue, 22 Aug 2006 10:12:00 -0700, BartlebyScrivener wrote:

>>> how difficult would it be to assign a string name(s)
>>> to an object upon creation (and upon referencing)?
> 
> Exactly the point that's being made. It's so easy just do it yourself:
> 
> banana={"name":"banana"}
> 
> Hey what is the name of my dictionary?
> 
> banana["name"]
> 
> But why build it into Python and force everyone else to do it, when
> most of the time nobody cares what the name is, or they already know?
> 
> It's like forcing everybody everywhere always and forever to wear
> "Hello My Name Is" tags.

On reflection, I'm wondering if we've been too harsh on Jojoba and not
thought this through, simply because "that's the way it's always been".

Functions have a __name__ attribute. So do classes and modules. Why are
these three objects "special" that they know the name they were created
with, when other objects don't? Python doesn't attempt to track what name
they are known at *now*, just the name they were born with.

The obvious downside of giving all objects a __name__ attribute is that it
will increase the size of all objects.

But an upside is that it would enable more useful error messages, at least
sometimes. Here's some trivial pseudo-code:

def foo(a):
    assert len(a) > 10, "%s is too short" % a.__name__

y = "hello"
foo(y)

would display "AssertionError: y is too short".

Of course, this could lead to misleading messages too:

y = "hello"  # y.__name__ is "y"
# lots of code
z = y # z.__name__ is "y"
foo(z)

prints "AssertionError: y is too short", probably not helpful.

And what should foo("no name") do?

On balance, I think the benefit for giving all objects a __name__ is
minimal, and the costs significant. But it isn't a completely stupid idea,
since some objects do know the name they were created with, so there are
uses for it, sometimes.



-- 
Steven D'Aprano 




More information about the Python-list mailing list