how do you get the name of a dictionary?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Aug 23 05:20:27 EDT 2006


On Wed, 23 Aug 2006 02:44:28 -0500, Robert Kern wrote:

>> But consider that when you get an
>> exception that says "a is too short", you often have to mentally change
>> gears and think about where a came from and what it is called in the
>> enclosing scope. After all, if the value of a is invalid, and the value of
>> a is set in the enclosing scope, it makes sense to refer to "the object
>> known locally as a" by the name it was known as when it was set.
> 
> That's what tracebacks are for. You don't have to mentally change gears; you 
> just look.

Here's a traceback. One of the arguments to spam() is too small. Can you
tell which one just by looking at the traceback?

>>> a, b, c, d = range(4)
>>> spam(a, b, c, d)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in spam
  File "<stdin>", line 5, in eggs
  File "<stdin>", line 4, in beans
ValueError: x is too small

Of course you can't. x could be any one of a, b, c or d, and the traceback
doesn't give you enough information to tell which.

>>> def spam(foo, bar, baz, qux):
...     def eggs(alpha, beta, gamma, delta):
...             def beans(w, x, y, z):
...                     raise ValueError("x is too small")
...             beans(alpha, beta, gamma, delta)
...     eggs(foo, bar, baz, qux)
...

Nesting the functions was an arbitrary choice -- the same issue occurs
regardless of whether they are nested or not. That's a relatively simple
example, with only three layers of nested scopes (four if you count the
global scope). I've seen tracebacks with twenty or thirty levels. Ouch.

I could have come up with a devilishly convoluted example if I wished,
reusing the same names for different purposes in different scopes, or
re-binding the names multiple times, or even simply moving the order of
arguments around from one function to another. But that would be overkill.

This is NOT a complaint against Python's object module, merely a call to
recognise that, in some instances, if objects knew their own name, it
would be useful. As I've already said, the benefit gained is probably less
than the cost required, so I'm not suggesting that Python work this way.
But the idea isn't totally pointless.


-- 
Steven D'Aprano 




More information about the Python-list mailing list