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

John Roth newsgroups at jhrothjr.com
Thu Jul 22 08:30:53 EDT 2004


"Josef Dalcolmo" <dalcolmo at vh-s.de> wrote in message
news:20040722142305.0000373a at titan...
> 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.

As a general rule, the answer is no. The basic reason is
that there is a many-to-one relationship between the
names to which an object is bound, and the object itself.
In your example, the integer '33' could be bound to a
large number of different identifiers in different objects.

Python doesn't maintain that kind of a crossreference,
and even if it did, you'd still need to figure out the
context you were asking about.

If you know the context, you might consider
building an inverse dictionary so you can use
it to look up the object and find the name(s)
that it's bound to in that context. Timing is
important here!

John Roth

>
> Best regards - Josef Dalcolmo





More information about the Python-list mailing list