Getting current variable name
Steven Bethard
steven.bethard at gmail.com
Wed Mar 16 11:17:08 EST 2005
pl wrote:
> 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])
What is the problem you're trying to solve here? Looking up the names
of an object is not usually something you want to do. If you provide a
little more detail on your use case, we might be able to help you
refactor this code.
STeVe
More information about the Python-list
mailing list