Getting current variable name

pl ladam at smbh.univ-paris13.fr
Wed Mar 16 09:34:32 EST 2005


Hi all,
I followed the mails entitled 'How to turn a variable name into a
string?' in march 2005 posts as I have a similar problem.

I have to get some list variable names at some point in my program. So
I ended up looking into globals() to get them with a small function like
this:

#!/usr/bin/python

l1 = ['r', 'r', 't']
l2 = ['r', 't', 't']
l3 = ['t', 't', 't']	# Two equivalent lists but...
l4 = ['t', 't', 't']	# with different names

def nameofObj(obj):
#	print locals()
	globdict = globals()
	var = globals().keys()
	for i in var :
		if globdict[i] == obj:
			print i


print '-'*20 ,'\n'
nameofObj(l1)

print '-'*20 ,'\n'
map(nameofObj, [l1, l2, l3, l4])

--------------------------------------------------------------------
If you try this, with 2 equivalent lists
(here l3 and l4 when using map) the function will return both
possibilities l3 and l4 which I understand. 
So this solution is limitated to unique lists, unfortunately I do have
equivalent lists in my case...

The problem comes from the fact that locals() and globals() have
in common their values but not the keys which then can't be tested.

The only solution I see would be to link the list and its name (in
a dictionary for instance) but that does not sound elegant to me?
If you guys can help a newbie...

Thank you
-- 
------------------------------------------------------------------
| Patrick LADAM                   |                               |
| Laboratoire CSSB                |     THE BIG BANG THEORY:      |
| UFR SMBH                        |                               |
| 74 rue Marcel Cachin            |   In the begining there was   |
| 93017 Bobigny CEDEX             |        nothing at all.        |
| >>> NEW e-mail: <<<             |                               |
| ladam at smbh.smbh.univ-paris13.fr |      Then, it exploded...     |
| Tel: 01 48 38 77 26 / 76 85     |                               |
| Fax: 01 48 38 77 77             |                               |
------------------------------------------------------------------







More information about the Python-list mailing list