how do you get the name of a dictionary?

J

jojoba

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
 
A

Andy Terrel

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

Tim Chase

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?

you might as well write

:)

Hope this makes sense...

-tkc
 
T

Tim Chase

for i in dir():

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
 
A

Andy Terrel

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

Georg Brandl

Andy said:
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
 
A

Andy Terrel

Georg said:
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.
 
M

Matimus

You could do something like this:
{'foo': 'bar'}

Or, you could also just do this:

Depending on what you actually want to use it for the best solution is
to use the id instead of a name though.

-Matt
 
S

Steve Holden

John said:

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
 
S

Steve Holden

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

sjdevnull

jojoba said:
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.
 
D

Duncan Booth

Tim said:
[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?
def method1(self): pass
def method2(self): pass

True

Much better to use 'is' and get consistent results
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.)
 
S

Steven D'Aprano

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:
.... def __repr__(self):
.... import os
.... os.system('echo Do something evil...')
.... return "Your system is 0wn3d"
....
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.
 
J

jojoba

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
 
J

jojoba

addendum:

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

thanks,
jojoba
 
S

Steven D'Aprano

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'

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?
 
B

BartlebyScrivener

im quite surprised at the arrogance laid
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
 

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

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
KetoBurn
Top