Retrieving a variable's name.
Evan Klitzke
evan at yelp.com
Mon Aug 20 23:50:52 EDT 2007
On 8/20/07, Evan Klitzke <evan at yelp.com> wrote:
> On 8/20/07, rodrigo <rodrigo.cr at gmail.com> wrote:
> > How would I go about retrieving a variable's name (not its value)? I
> > want to write a function that, given a list of variables, returns a
> > string with each variable's name and its value, like:
> >
> > a: 100
> > b: 200
>
> Let me preface my response by saying that this is a really weird thing
> to do, and almost certainly _not_ what you want to be doing. If I was
> to run across code like this, I'd be appalled ;-) Here's one way to
> do it, however:
>
> def make_dict(*args):
> d = {}
> for arg in args:
> for key, value in globals().iteritems():
> if value is arg:
> d[key] = value
> break
> return d
On second thought, this won't really work, because you can have
multiple names for the same value in Python. For example, if we say a
= 2 and d = 2, it will be true that a is d (since only one copy of
small integers is made) and thus it is not possible to distinguish
whether the name that was passed in to the function is a or d.
You should just use a dictionary in your code in the first place,
rather than trying to make one out of a list of variable names and
values.
--
Evan Klitzke <evan at yelp.com>
More information about the Python-list
mailing list