473,327 Members | 2,055 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

how do you get the name of a dictionary?

Hello!

Does anyone know how to find the name of a python data type.

Conside a dictionary:

Banana = {}

Then, how do i ask python for a string representing the name of the
above dictionary (i.e. 'Banana')?

thanks to anyone who has time to answer this nube question!
jojoba

Aug 18 '06 #1
70 27238

jojoba wrote:
Hello!

Does anyone know how to find the name of a python data type.

Conside a dictionary:

Banana = {}

Then, how do i ask python for a string representing the name of the
above dictionary (i.e. 'Banana')?

thanks to anyone who has time to answer this nube question!
jojoba
here is an easy hack, I don't know if there is an explicit function.
for i in dir():
if eval(i) == Banana:
print i

Aug 18 '06 #2
Does anyone know how to find the name of a python data type.
>
Conside a dictionary:

Banana = {}

Then, how do i ask python for a string representing the name of the
above dictionary (i.e. 'Banana')?
AFAIK, there's no easy/good way of doing this because that name
is just a handle to an internal object. Observe:
>>banana = {}
spatula = banana
spatula[42] = 'drangle'
banana
{42: 'drangle'}
>>id(spatula)
10304800
>>id(banana)
10304800

What does it mean to ask for the name of object ID 10304800?
it's both "banana" and "spatula". One might be able to use the
decompiler libraries and wend one's way through the dark recesses
of python's internals to extract such information, but this is
certainly not a beginner's task.

How would you ask for the object?
>>print get_name(banana)
you might as well write
>>print "banana"
:)

Hope this makes sense...

-tkc
Aug 18 '06 #3
Andy Terrel wrote:
for i in dir():
if eval(i) == Banana:
print i
(sound of head hitting desk)

</F>

Aug 18 '06 #4
Fredrik Lundh wrote:
Andy Terrel wrote:
>for i in dir():
if eval(i) == Banana:
print i

(sound of head hitting desk)

</F>
lol
Aug 18 '06 #5
>>for i in dir():
>> if eval(i) == Banana:
print i
(sound of head hitting desk)

</F>
lol
As freakish as the solution was, it's not too far off from
something that actually works (mostly, kinda sorta):
>>banana = {}
spatula = banana
propane = {}
[name for name in dir() if id(eval(name)) == id(banana)]
['banana', 'spatula']
>>dir()
['__builtins__', '__doc__', '__name__', 'banana', 'name',
'propane', 'spatula']

While the original just compared on value (and thus, with the
original "solution", "propane" would also be found), it should be
pretty safe to compare on id() equality.

Okay, it's semi-obcene in my book, but it's an actual solution in
a way.

-tkc

Aug 18 '06 #6
Why bang your head? It was a stupid hack that has lots of problems,
but done in a way that is readable. Sure I could do something more
functional or one lined like:

Banana={}
names = filter(lambda x:id(eval(x))==id(Banana),dir())

but I am guessing that it is harder to read by many. Anywho I can
think of plenty of reasons it would fail, but it really depends on the
app.
Fredrik Lundh wrote:
Andy Terrel wrote:
for i in dir():
if eval(i) == Banana:
print i

(sound of head hitting desk)

</F>
Aug 18 '06 #7
Andy Terrel wrote:
Why bang your head?
Because there's no chance that the original request is sane.

If you want your objects to know their name, give them a name as an attribute.
It was a stupid hack that has lots of problems,
but done in a way that is readable. Sure I could do something more
functional or one lined like:

Banana={}
names = filter(lambda x:id(eval(x))==id(Banana),dir())

but I am guessing that it is harder to read by many. Anywho I can
think of plenty of reasons it would fail, but it really depends on the
app.
Georg
Aug 18 '06 #8

Georg Brandl wrote:
Andy Terrel wrote:
Why bang your head?

Because there's no chance that the original request is sane.

If you want your objects to know their name, give them a name as an attribute.
This is true but sometimes it is just fun to hack around.

Aug 18 '06 #9
You could do something like this:
>>class MyDict(dict):
.... pass
>>bananna = MyDict({"foo":"bar"}) #dict constructor still works
bananna.name = "bananna"
bananna.name
'bananna'
>>bananna
{'foo': 'bar'}

Or, you could also just do this:
>>bananna = {"name":"bananna"}
Depending on what you actually want to use it for the best solution is
to use the id instead of a name though.

-Matt

Aug 18 '06 #10
Tim Chase wrote:
How would you ask for the object?
>>print get_name(banana)

you might as well write
>>print "banana"
Or there used to be a guy in this group who said it was like asking a
cat for its name. He headbanged himself unconscious though, or so they
say.

http://tinyurl.com/hql6d

rd

Aug 19 '06 #11
John Salerno wrote:
Fredrik Lundh wrote:
>>Andy Terrel wrote:

>>>for i in dir():
if eval(i) == Banana:
print i

(sound of head hitting desk)

</F>
lol
Right. Plus it's fun to imagine the effbot hitting itself as hard as
some people would obviously have liked to hit it in the past :-)

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Aug 19 '06 #12
BartlebyScrivener wrote:
Tim Chase wrote:
>>How would you ask for the object?
>>print get_name(banana)

you might as well write
>>print "banana"

Or there used to be a guy in this group who said it was like asking a
cat for its name. He headbanged himself unconscious though, or so they
say.

http://tinyurl.com/hql6d

rd
We need to take this discussion to a meta-level. Once we find out what
the dictionary's name is, we will then need the name's name.

with-apologies-to-lewis-carroll-and-in-contravention-of-the-don't-post-while-intoxicated-rule-ly
y'rs - steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Aug 19 '06 #13
jojoba wrote:
Does anyone know how to find the name of a python data type.

Conside a dictionary:

Banana = {}

Then, how do i ask python for a string representing the name of the
above dictionary (i.e. 'Banana')?
The reason people are banging their heads is because the question
doesn't make sense in general.

If you need to track a name of some sort, the suggestion to have a name
attribute (e.g. your own MyDict class inheriting from dict) may be
reasonable.

But an object may be bound to many names, or none:

Consider:
Banana = {}
# I guess you want the name of the dictionary to be "Banana" now?
Apple = Banana
# What is the name of the dictionary now? Apple or Banana?
Banana = 3
print Apple
{}
print Banana
3
# What is the name of the dictionary now? Apple?
Strawberry = [ Apple ]
Apple = "hello"
print Strawberry
[ {} ]
print Apple
hello
# What is the name of the dictionary now? It's not bound to any name.
Aug 19 '06 #14
Tim Chase wrote:
>[name for name in dir() if id(eval(name)) == id(banana)]
['banana', 'spatula']
Please, if you are going to do something like this, then please at least
use the 'is' operator. Using id(expr1)==id(expr2) is just plain stupid: it
will actually work in this case, but as soon as you get into a mindset of
testing for the same object by comparing object ids you are going to shoot
yourself in the foot.

The first of the following tests returns True, which looks sensible at
first glance (even though it shouldn't), but what of the second one?
>>class C:
def method1(self): pass
def method2(self): pass

>>inst = C()
id(inst.method1)==id(inst.method1)
True
>>id(inst.method1)==id(inst.method2)
True

Much better to use 'is' and get consistent results
>>inst.method1 is inst.method1
False

(In case I didn't make it clear, the problem in general with comparing the
result of calling 'id' is that as soon as the first call to id returns, any
object created when evaluating its parameter can be freed, so the second
call to id can reuse memory and get the same answer even though the objects
are different.)
Aug 19 '06 #15
On Fri, 18 Aug 2006 11:45:05 -0700, Andy Terrel wrote:
here is an easy hack, I don't know if there is an explicit function.
for i in dir():
if eval(i) == Banana:
print i

Let's just hope that there is no way for black-hats to remotely inject
code objects into your namespace:
>>class Killer:
.... def __repr__(self):
.... import os
.... os.system('echo Do something evil...')
.... return "Your system is 0wn3d"
....
>>x = Killer()
Now x is sitting there in your namespace like a mine, just waiting for
you to call eval('x').

Okay, so maybe it isn't the most likely security threat in the universe,
but it is a reminder that eval() can have side-effects. In this specific
instance, if repr() has a side-effect (e.g. an object that knows how many
times it has been printed), so will your code. That's probably not a good
thing to do.

--
Steven D'Aprano

Aug 21 '06 #16
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

Aug 21 '06 #17
addendum:

when asking python for the name of a dictionary,
it shold return ONE, MANY, or NO strings

thanks,
jojoba

Aug 22 '06 #18
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

Aug 22 '06 #19
>im quite surprised at the arrogance laid
>out by some of the above
Oh, nobody is being arrogant. They're having fun while answering your
question. Most remember having the same question, or at least making
the same discovery after careful reading.

rd

Aug 22 '06 #20
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

Aug 22 '06 #21

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.

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

Aug 22 '06 #22
On Mon, 21 Aug 2006 20:53:38 -0700, jojoba wrote:
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...
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.

--
Steven D'Aprano

Aug 22 '06 #23
jojoba wrote:
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.

Aug 22 '06 #24
jojoba wrote:
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>

Aug 22 '06 #25
jojoba wrote:
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/com...7dc92f3629dd9a
>>import varname
Banana = {}
class C:
.... classFruit = [{}, Banana]
....
>>def names(x):
.... for s in varname.object_info(x):
.... print s
....
>>names(Banana)
__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.

Aug 22 '06 #26
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

Aug 22 '06 #27
jojoba wrote:
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.
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
Aug 22 '06 #28
>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.

rd

Aug 22 '06 #29
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

Aug 22 '06 #30
On Tue, 2006-08-22 at 12:34, jojoba wrote:
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.
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.
Aug 22 '06 #31
At Tuesday 22/8/2006 13:34, jojoba wrote:
>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

Aug 22 '06 #32


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

Aug 22 '06 #33
jojoba wrote:
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:
>>class dict_with_title(dict):
.... 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>

Aug 22 '06 #34
In <11**********************@75g2000cwc.googlegroups. com>, jojoba wrote:
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
Aug 22 '06 #35
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

Aug 22 '06 #36
jojoba wrote:
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>

Aug 22 '06 #37
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.

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

Aug 22 '06 #38
jojoba wrote:
>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?
yes.

</F>

Aug 22 '06 #39


Wow Fredrick! Are you serious?

yes.
</F>
Thank you for the clear answer.
no, you're just wasting a lot of bandwidth making it clear that you just
cannot be bothered to learn how things actually work.
By the way, what exactly led you to this conclusion?

jojoba

Aug 22 '06 #40
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

Aug 23 '06 #41
On Tue, 22 Aug 2006 09:34:36 -0700, jojoba wrote:
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.
--
Steven D'Aprano

Aug 23 '06 #42
thanks Steven!
that does help!
cheers,
jojoba
o(-_-)o

Aug 23 '06 #43
Steven D'Aprano wrote:
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.
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
Aug 23 '06 #44
jojoba wrote:
>>>no, you're just wasting a lot of bandwidth making it clear that you just
cannot be bothered to learn how things actually work.

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>

Aug 23 '06 #45
Steven D'Aprano wrote:
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>

Aug 23 '06 #46
"jojoba" <jo******@hotmail.comWrote:

| 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

Aug 23 '06 #47
On Wed, 23 Aug 2006 08:56:54 +0200, Fredrik Lundh wrote:
Steven D'Aprano wrote:
>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" ?
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.

--
Steven D'Aprano

Aug 23 '06 #48
Steven D'Aprano wrote:
On Wed, 23 Aug 2006 08:56:54 +0200, Fredrik Lundh wrote:
>Steven D'Aprano wrote:
>>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" ?

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

Aug 23 '06 #49
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

Aug 23 '06 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Josef Dalcolmo | last post by:
If I have a Python variable like var = 33 can I get the name 'var' as a string? Obviously this does not make much sense when using a single variable, but if I want to print the variable...
0
by: adamc | last post by:
hi, I'm currently debugging a crash occurring in the Python interpreter. I've got a Dictionary object in the form of a (PyObject *) I can cast it to (dictobject *) in the debugger watch...
5
by: David Rasmussen | last post by:
If I have a string that contains the name of a function, can I call it? As in: def someFunction(): print "Hello" s = "someFunction" s() # I know this is wrong, but you get the idea... ...
3
by: Brett Romero | last post by:
if I have a public static property such as: //Class1 public class Class1 { public static Dictionary<string, string> Prop1{...} public static Dictionary<string, string> Prop2{...} } ...
1
by: mehdi_mousavi | last post by:
Hi folks, Consider a string that's defined under VS2005 resource editor as myField with the value of myValue. To access the value, I could easily use the Properties.Resources class, for example:...
1
by: Andy Wu | last post by:
Hi All, I've been working on a domain parking project where we need to analyze a domain name, say "bookhotel", and get keywords(book, hotel) out of it, then use these keywords to do some search....
15
by: Dave Young | last post by:
I'm trying to replicate the behaviour of the Commerce.Dictionary object that was found in Commerce Server 3.0 By using a hashtable or creating a custom class that implements IDictionary, you...
3
by: Dmitry Nogin | last post by:
Hi, I would like to use dictionaries to implement my property value storing mechanics. (I have a lot but many of them are just about to keep <nullmost of the time, so it might save a lot of...
12
by: Shannon Mayne | last post by:
I would like to create objects with algorithmically determined names based on other object names and use object names for general algorithm input. How would one extract the name of an object...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.