how do you get the name of a dictionary?

S

Steven D'Aprano

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.
 
S

Steven D'Aprano

i don't want to do anything sophisticated with this, i am really only
looking for a TITLE for my dictionary when i throw it in a tree editor
that i have built. And i do realize that its not possible now. I am just
pressing a point here.

Something like this might help.

def get_object_title(object, namespace=None):
"""Returns a possible title/name for object, in the given namespace."""
if namespace is None:
namespace = globals()
try:
return object.__name__ # works for functions, classes, modules
except AttributeError:
# search the namespace
for key,value in namespace.items():
if object is value: # do NOT use ==
return key
# not found in the namespace either
# maybe an unnamed object?
return "Object ID %d" % id(object)

Hope this helps.
 
D

Dennis Lee Bieber

I'm not sure how to dynamically pass the name of the dictionary without
hard coding it.
Well, how are you passing the dictionary itself? You must have a
hard-coded name at that point... Or at some point prior to that call you
performed some operation using a hard-coded name. IE:

treeViewer(aDictionary)

is a hard-coded reference already, and requires very little extra to do

treeViewer(aDictionary, "aDictionary")

{Hmm, wonder if it is possible to write a decorator type operation that
would take a single "word" and generate the reference and the string}
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
H

Hendrik van Rooyen

| > At the risk of stating the obvious, why don't you simply add a parameter
| > for the title in the invocation of the tree editor? I.e. instead of
| > invoke_tree_editor(somedict)
| > do
| > invoke_tree_editor(somedict, "somedict")
| > HTH,
| > Carsten.
|
|
| Thanks Carsten.
| This would indeed allow me to assign a title for my dicitonaries, but i
| am looking for something more general......
| specfically:
| given any dictionary, get a name for it.
|
| But yeah, your way would totally work!
| Thanks,
| jojoba
|

At the risk of asking the even more obvious - "given any dictionary" - How is it
given - just print whatever it is that causes you to believe that you are
dealing with a dictionary..

- Hendrik
 
G

Georg Brandl

Steven said:
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.

Because they're not created by simple assignment, because they are
usually created once, because new names are bound to them rarely,
and because it's crucial to know their name in debugging, introspection etc.

Georg
 
F

Fredrik Lundh

jojoba said:
By the way, what exactly led you to this conclusion?

the fact that despite all attempts to explain how things work, you're
still haven't realized that if you want the names of things, you should
pass *namespaces* to your object viewer, not individual objects.

</F>
 
F

Fredrik Lundh

Steven said:
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".

why not "a is too short" ?

or for that matter, "x is to short" ?

</F>
 
S

Steven D'Aprano

why not "a is too short" ?

or for that matter, "x is to short" ?

These are all valid responses too. 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.

Of course, this leads to greater complexity, it still doesn't deal well
with objects known by multiple names, or no name at all, and it would
require a lot of overhead for something which is only of value
occasionally. In other words, the downside outweighs the upside
significantly.
 
R

Robert Kern

Steven said:
These are all valid responses too. 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.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
S

Sybren Stuvel

Steven D'Aprano enlightened us with:
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".

That's simply a very bad example. If you use a real-world function,
you notice that the current error messages are just fine:

def update(title):
assert len(title)> 10, "Title too short"

update("hello")

would display: "AssertionError: Title too short". Seems fine to me.

Sybren
 
S

Steven D'Aprano

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

Michael Janssen

jojoba said:
given any dictionary, get a name for it.

You do not want to open your text editor and hardcode the name (neither
as a variable name nor a name-attribute), do you? Your script is
hopefully capable to determine the dict-to-be-displayed from
user-input? Perhaps name of a file to be parsed?

Even when you can display the name of the variable the dictionary is
assigned to you yield 'anydict'. That's not that compelling. When you
really intend to hardcode the variable's name to something meaningful,
how is your script supposed to do sensible work after your work is done
with it?

When you want to have a programm that can display arbitrary
dictionaries you end up with a variable name that is (hopefully ;-)
meaningful in the context of the programm but not meaningful in respect
of the content of the dictionary: at programming-time you can't know
what dictionaries are to be displayed so you don't have meaningful
names. You might want to take the name of the file to be parsed or
something else from userinput as the name of the dict - but the
variables name is the wrong place to store this information. Did I miss
anything?

regards
Michael
 
F

Fredrik Lundh

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

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.

for some reason, your example gives a different error on my machine:

StrawManError: Attempt to construct Reductio ad absurdum argument failed

</F>
 
J

jojoba

Fredrik said:
the fact that despite all attempts to explain how things work, you're
still haven't realized that if you want the names of things, you should
pass *namespaces* to your object viewer, not individual objects.


And what im saying is that isnt it silly that we need pass an entire
namespace, when a much simpler notion would be to have each object know
its own name(s) (even if that name doesnt exist).
Now, here's where everyone tells me this isnt possible, and how my
statement implies that i have no idea whatsoever of how python
works....

jojoba
 
S

Simon Brunning

And what im saying is that isnt it silly that we need pass an entire
namespace, when a much simpler notion would be to have each object know
its own name(s) (even if that name doesnt exist).
Now, here's where everyone tells me this isnt possible, and how my
statement implies that i have no idea whatsoever of how python
works....

It's not inconcevable that Python could behave that way, it's just
that it would impose an overhead on the 99.999% of Python users who
would have no use for the feature. It's a price not worth paying.
 
J

jojoba

And what im saying is that isnt it silly that we need pass an entire
namespace, when a much simpler notion would be to have each object know
its own name(s) (even if that name doesnt exist).


please note: in my above comment, i was completely disregarding any
notions of added costs that would be incurred to have such a feature,
and that in fact, such costs might actually nullify any other benefits
from having such a feature. Purely a what-if idea from a nascent python
programmer.

jojoba
 
G

Georg Brandl

jojoba said:
please note: in my above comment, i was completely disregarding any
notions of added costs that would be incurred to have such a feature,
and that in fact, such costs might actually nullify any other benefits
from having such a feature. Purely a what-if idea from a nascent python
programmer.

Even from such a point of view, the concept isn't clearly enough defined.
What name would be assigned to the dict below?

l = [1,2,3]
a = "some_str"
l[0] = {'foo': 'bar'}

Some immutable objects, such as small integers, exist only once. Would you
assign names to them? They're likely to be completely meaningless.

When a name goes out of scope, but the object continues to live (e.g.
because it's returned by some function), the name is void.

Etc.


Georg
 
R

Robert Kern

jojoba said:
And what im saying is that isnt it silly that we need pass an entire
namespace, when a much simpler notion would be to have each object know
its own name(s) (even if that name doesnt exist).

No, it's silly to avoid a very well-defined, heavily optimized strategy used
everywhere in the language in favor of a new, vague strategy that is usually
uninformative and frequently undefined.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,614
Members
45,287
Latest member
Helenfem

Latest Threads

Top