how do you get the name of a dictionary?

J

jojoba

Hello

Thanks Steven for laying out some interesting and compelling points.
I concede that my use of this would-be dictionary-name-asking is for
the most part useless (i am making a dictionary-editor-viewer in
python, and i would like to also be able to display the name of the
dictionary at the top of the data tree!)
Thank you for giving a pretty good reason why this inverse name-getting
(which is really not a true inverse, when none or many names exist) for
a dictionary has a poor cost benefit ratio.

However, regarding your comment about the phone book, I have a
question:
You say:
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".


By reverse phone book, do you mean something like listing all the
numbers in order, so as to optimize searching from phone number to
name...and the implicaiton being that for python, it is much faster to
find the data structure from the name, than the name from the data
structure?
If this is true, then you are quite right, and i am quite silly!
I guess i was just thinking that all else equal, searching for one side
(names) should be as fast as searching the other side (dictionaries),
and hence recovering the mappings of name(s) to dictionary is equally
fast both ways.
If this is not true, then certainly, you are correct in saying that
python need not spend its time managing a copious list of names and
dictionaries.
But does this really entail an overhaul of python to make such a thing
happen?
Thanks again for the insights,
very helpful
jojoba

o(-_-)o
 
P

Patrick Maupin

jojoba said:
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
 
S

Steven D'Aprano

However, regarding your comment about the phone book, I have a
question:
You say:



By reverse phone book, do you mean something like listing all the
numbers in order, so as to optimize searching from phone number to
name...

Something like that.
and the implicaiton being that for python, it is much faster to
find the data structure from the name, than the name from the data
structure?
If this is true, then you are quite right, and i am quite silly!
I guess i was just thinking that all else equal, searching for one side
(names) should be as fast as searching the other side (dictionaries),
and hence recovering the mappings of name(s) to dictionary is equally
fast both ways.
If this is not true, then certainly, you are correct in saying that
python need not spend its time managing a copious list of names and
dictionaries.
But does this really entail an overhaul of python to make such a thing
happen?

Yes. Python uses dictionaries as "namespaces". When Python compiles a line
like "y = len(x) + 1", it parses the line into something vaguely like this:

(name y) (equals) (name len)(name x) (operator +) (value 1)

Then at run-time it looks up the names. It does this by keeping names in a
Python dictionary:

{'str': (object id 45), 'math': (object id 991), 'x': (object id 5065),
'b': (object id 9120), 'len': (object id 23), 'y': (object id 237), ... }

Notice that virtually everything in Python is in a namespace dictionary,
including modules and built-in functions. Keep in mind that there isn't
just one such namespace dictionary, there are lots of them, one for each
level of code. Classes have their own namespaces, so do modules. You can
explore two of these namespaces with the functions locals() and globals().

Because the namespace is a dictionary, it is easy to go from the name to
the object, but it is hard to go from the object to the name. And there
may be objects which exist, but don't have names: you won't find them in
the namespace dictionary at all.

What I've described is a simplification of what really happens, but it
gives you an idea of the basic principles.
 
S

sjdevnull

jojoba said:
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. It'd be like having an open file descriptor in C and
then asking what filename(s) that file has, something that new
programmers also ask about but doesn't make much sense when you stop
and think about it.

The way name-binding works in python, names can exist in certain
scopes. They can be global to a module, local to a certain
class/function, etc. A name can refer to many different objects over
time. An object can have many different names in different scopes.

Suppose you have:

class a(object):
def __init__(self, something):
self.widget = something

class b(object):
def __init__(self, something):
self.gadget = something
def printStuff(self):
PrintPythonNames(self.gadget)

mything = dict()
aList = [ a(mything) ]
B = b(mything)
B.printStuff()

Does it really make sense to you to have names in class a's scope
available from inside B? What if it were a.__widget? Further, what
sense would it make? What if other threads had names referencing the
dict object that were changing during the b.printStuff() call? Are you
going to try to lock the entire namespace while you look to see what
things in every scope could hold references to the object you're trying
a reverse lookup on?

Going from a name to an object is inherently a one-way operation, and
trying to manufacture a reverse lookup just doesn't make sense in
general.
 
F

Fredrik Lundh

jojoba said:
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?

Python's object model. an object has a value, a type, and an identity,
but no name.

required reading:

http://tinyurl.com/gxrdr (relevant faq entry)
http://effbot.org/zone/python-objects.htm
http://www.python.net/crew/mwh/hacks/objectthink.html

</F>
 
D

Duncan Booth

jojoba said:
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?

Some time back I posted some code which would do exactly that, but it is
not nice, and it is buggy, but if you want to play with it:
http://groups.google.co.uk/group/co..._frm/thread/394ba5b48f83ebfb/237dc92f3629dd9a
.... classFruit = [{}, Banana]
........ for s in varname.object_info(x):
.... print s
....__main__.C.classFruit[1]
__main__.Banana
__main__.names()x

The problem as others have said is that there are a lot of namespaces in
Python (module globals, classes, instances, local variables of active
functions, ...), and the only way to find which names refers to an object
is to search the relevant namespaces.

There is some information which can help: for any object you can get a list
of all objects that refer to it, and that can be used to trace backwards
until you find a namespace at which point you still have to search the
namespace to find out which name refers to the object. Of course doing all
this creates lots of new references and infinite loops both of which you
have to ignore.
 
J

jojoba

Hello again,

Fredrick said:
Python's object model. an object has a value, a type, and an identity,
but no name.

I say:

Thank you Fredrick for the reply!
However, although python's object model does not currently support what
i am asking for, how difficult would it be to assign a string name(s)
to an object upon creation (and upon referencing)?

please note:
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.

Sorry to ruffle everyone's feathers, but this is a fairly curious
problem.

Thanks to all,
jojoba
 
G

Georg Brandl

jojoba said:
Hello again,

Fredrick said:


I say:

Thank you Fredrick for the reply!
However, although python's object model does not currently support what
i am asking for, how difficult would it be to assign a string name(s)
to an object upon creation (and upon referencing)?

please note:
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.

Sorry to ruffle everyone's feathers, but this is a fairly curious
problem.

Why not add a "name" attribute to your objects? e.g.

class NamedDict(dict):
def __init__(self, _name_, *args, **kwargs):
self.name = _name_
dict.__init__(self, *args, **kwargs)

Georg
 
B

BartlebyScrivener

how difficult would it be to assign a string name(s)
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.

rd
 
J

jojoba

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?


Aha.....
my problem, (which as i said before, is not really an important
problem) is to take any dictionary and load it into a tree viewer AND
get the name(s) of that dictionary (if they exist, and if not, so be
it).
Now, that means that a given dictionary might not have the admittedly
super simple method of binding a name to itself (i.e. the
banana={"name":"banana"}).
This has been my issue. And there is no GENERAL solution that currently
exists.
I completely agree with everybody that a draconian solution is not
necessarily optimal, but i havent been convinced that it would
drastically, deleteriously affect python performance.
However, since i am not one of the wonderful people who commit time to
actually coding python, i dont really have a say. =)
I know i am harping on this, but no one of yet has really proven why
having such a feature would seriously affect python speed.
Any ideas?
jojoba

o(-_-)o
 
C

Carsten Haese

Hello again,

Fredrick said:


I say:

Thank you Fredrick for the reply!
However, although python's object model does not currently support what
i am asking for, how difficult would it be to assign a string name(s)
to an object upon creation (and upon referencing)?

please note:
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.

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

Gabriel Genellina

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.

Sorry to ruffle everyone's feathers, but this is a fairly curious
problem.

It's no problem at all: do you need a TITLE for your dictionary? Add
a "title" attribute and you're done. Do you want a class? Inherit
from dict and add your title attribute there.
That's pretty standard OO, and there is no need to modify the Python
language...



Gabriel Genellina
Softlab SRL



p4.vert.ukl.yahoo.com uncompressed Tue Aug 22 17:27:05 GMT 2006


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
 
J

jojoba

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
 
F

Fredrik Lundh

jojoba said:
However, although python's object model does not currently support what
i am asking for, how difficult would it be to assign a string name(s)
to an object upon creation (and upon referencing)?

if you want to add additional behaviour to an object, wrap it in custom
class, or use a subclass.

here's an example:
.... title = None
....
>>> d = dict_with_title()
>>> d.title = "this is the title"
>>> d["a"] = "hello"
>>> d {'a': 'hello'}
>>> d.title
'this is the title'

</F>
 
M

Marc 'BlackJack' Rintsch

Aha.....
my problem, (which as i said before, is not really an important
problem) is to take any dictionary and load it into a tree viewer AND
get the name(s) of that dictionary (if they exist, and if not, so be
it).

How do you take "any" dictionary? Don't you have to know a name to refer
to it? Just pass this very name as additional argument to your tree
viewer.
I know i am harping on this, but no one of yet has really proven why
having such a feature would seriously affect python speed.
Any ideas?

You have to attach a name to a dict every time it's assigned to a name and
delete a name from the dictionary every time such a name is deleted or
rebound to some other object. And all this is unnecessary extra work and
memory consumption in 99.99% of most programs.

And why do you want to special case dictionaries? If Python is doing it
for dictionaries, sooner or later someone will ask for the names of lists
or any arbitrary object.

Ciao,
Marc 'BlackJack' Rintsch
 
J

jojoba

How do you take "any" dictionary? Don't you have to know a name to refer
to it? Just pass this very name as additional argument to your tree
viewer.

I know i must be driving python purists to their limits...but

I'm not sure how to dynamically pass the name of the dictionary without
hard coding it.
You have to attach a name to a dict every time it's assigned to a name and
delete a name from the dictionary every time such a name is deleted or
rebound to some other object. And all this is unnecessary extra work and
memory consumption in 99.99% of most programs.

But this is 2006, and my computer can do 50 googlillion computations a
second.
So what does attaching or removing a title matter to my computer. What
searching has to happen? I know where the dictionary reference points,
so i have immediate accesss to that data structure, don't I? Please
excuse me if i am way oversimplifying.
Also, i am sure there are many computations going on in any python
program, that technically, might not be needed for that program per se,
but that doesn't invalidate those computations' presence in general.
> And why do you want to special case dictionaries? If Python is doing it
for dictionaries, sooner or later someone will ask for the names of lists
or any arbitrary object.

Good question. Indeed I am not limiting this to dicitonaries, as other
data types, lists, tuples, etc. could use this as well.


jojoba
 
F

Fredrik Lundh

jojoba said:
I know i must be driving python purists to their limits...

no, you're just wasting a lot of bandwidth making it clear that you just
cannot be bothered to learn how things actually work.

do you behave this way in real life too, or is it just something you're
doing on the internet ?

</F>
 
J

jojoba

no, you're just wasting a lot of bandwidth making it clear that you just
cannot be bothered to learn how things actually work.


Wow Fredrick! Are you serious? Hey man, come on.I got lambasted on this
topic from the beginning. Everyone keeps saying i dont know what im
talking about, but no one actually gives me a reason why. Every counter
argument i gave was either shrugged off or followed up with a "no,
that's wrong" statement. Also, why are my PYTHON QUESTIONS wasting
bandwidth, while yours and others RIDICULING STATEMENTS not?
do you behave this way in real life too, or is it just something you're
doing on the internet ?

You sure you wanna go there. I have great respect for you and all you
have done for python. I use your modules often (thank you!). But im
not sure why my persistence on a this topic means i refuse to learn how
python really works.
If you dont agree with me, fine, PROVE your answer....forget about
links.
Tell me what you know or dont know, but please dont mock me.
What is this grade school?
As a community, we can choose to share or not.
We should not bicker, or chide the ignorant (such as myself on this
matter).
Of course i try to learn how python works, just as i am sure you do to.
We all have different levels of expertise (or lack of).
Im just trying to learn man.
Im not asking for a spoon feeding either.
Im just trying to get CLEAR information from people about this "issue"
but that has actually been quite difficult.
And yes, i do inquire about things i dont understand in real life. And
in fact, if i dont get a reasonable, sufficient answer, i will press
the other side until a CLEAR argument sways me one way or the other
(sorry if that bothers you) Thats one of my strong suits. In fact, its
what led me to study and pursue science.
But i digress.
Please be nice to me, thats all im asking.
I will try to be more concise and do "more" research before bothering
others with apparent inadequecies.
Thanks,
jojoba
 

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,781
Messages
2,569,615
Members
45,297
Latest member
EngineerD

Latest Threads

Top