[Tutor] inquire
alan.gauld@bt.com
alan.gauld@bt.com
Fri, 12 Jan 2001 10:58:40 -0000
> Does python offer any method or function to return the name
> of any object?
> >>>aaa=None
> >>>print Wanted_Function(aaa)
> 'aaa'
I don't know of any such but it might look like:
def getname(var, scope=dir()):
for name in scope:
if eval(name) == var: return name
foo = None
print getname(foo)
The problem is that because variables in Python are references if you
have two variables pointing to the same object then getname retiurns
the name of the first one. Thus in the case of None any name in the
current scope pointing to None will cause the first one to be printed.
Also using a default parameter isn't great since they are only set once.
You probably need to pass dir() in as scope on each call.
I'm sure some of the Python experts will have a better way...
But that might give you a starter for 10?
Alan G.