how can I get the name of a variable (or other object)?

Richard Oudkerk oudkerk at ma.man.ac.uk
Thu Jul 22 10:37:45 EDT 2004


Try

def printvars(varlist):
     allvars = globals()
     allvars.update(locals())
     for var in varlist:
         print [ n for n in allvars if allvars[n] is var ], "=>", var

a = 10
b = 20
c = 30
d = a
e = "hello"

printvars([a,b,e, 143, printvars, None])

It gives the output

['a', 'd'] => 10
['b'] => 20
['e'] => hello
[] => 143
['printvars'] => <function printvars at 0xa0c53e4>
['__doc__'] => None

Richard

Josef Dalcolmo wrote:
 > 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 together with it's name, for a list of variables, 
then it could make sense:
 >
 > def printvariables(varlist):
 > ....for var in varlist:
 > ........print var.__name__, var
 >
 > of course the attribute __name__ I just made up, and if this would always 
return 'var' it would not make any sense either.
 >
 > I am not sure if such a thing is at all possible in Python.
 >
 > Best regards - Josef Dalcolmo



More information about the Python-list mailing list