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

Grant Edwards grante at visi.com
Thu Jul 22 12:19:57 EDT 2004


On 2004-07-22, Josef Dalcolmo <dalcolmo at vh-s.de> 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:

Python doesn't have variables.  Python has objects.  Python has
dictionaries that map strings (names) to objects.  In your
example above, there is an integer object with a value of 33.

In your locals or globals dictionary you have placed an entry
with the key 'var' which points to the integer object with the
value 33.  The object doesn't actually have a name.  There may
be many dictionary entries with diffferent "names" that all
point to the same integer object.

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

What I suspect you're trying to do is something like the code
shown below.  How does one obtain a reference to the locals
dictionary for one's calling function?


def printvariables(varlist):
    g = globals()
    for v in varlist:
        if v in g:
            print "%s = %s %s" % (v,type(g[v]),g[v],)
        else:
            # we should try to look up v in the locals for the
            # caller, but I don't remember how to get that.
            print "%s undefined" % v
            
            
if __name__ == '__main__':
    x = 1
    y = 2.3
    z = 'howdy'
    d = {x:y, z:7.8}
    
    printvariables(['x','y','z','d'])
    

-- 
Grant Edwards                   grante             Yow!  I feel real
                                  at               SOPHISTICATED being in
                               visi.com            FRANCE!



More information about the Python-list mailing list