dictionary – How can you print a variable name in python?

dictionary – How can you print a variable name in python?

If you insist, here is some horrible inspect-based solution.

import inspect, re

def varname(p):
  for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
    m = re.search(rbvarnames*(s*([A-Za-z_][A-Za-z0-9_]*)s*), line)
    if m:
      return m.group(1)

if __name__ == __main__:
  spam = 42
  print varname(spam)

I hope it will inspire you to reevaluate the problem you have and look for another approach.

To answer your original question:

def namestr(obj, namespace):
    return [name for name in namespace if namespace[name] is obj]

Example:

>>> a = some var
>>> namestr(a, globals())
[a]

As @rbright already pointed out whatever you do there are probably better ways to do it.

dictionary – How can you print a variable name in python?

If you are trying to do this, it means you are doing something wrong. Consider using a dict instead.

def show_val(vals, name):
    print Name:, name, val:, vals[name]

vals = {a: 1, b: 2}
show_val(vals, b)

Output:

Name: b val: 2

Leave a Reply

Your email address will not be published. Required fields are marked *