Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the string representation of a variable in python?

I have a variable x in python. How can i find the string 'x' from the variable. Here is my attempt:

def var(v,c):
  for key in c.keys():
    if c[key] == v:
      return key


def f():
  x = '321'
  print 'Local var %s = %s'%(var(x,locals()),x)  

x = '123'
print 'Global var %s = %s'%(var(x,locals()),x)
f()

The results are:

Global var x = 123
Local var x = 321

The above recipe seems a bit un-pythonesque. Is there a better/shorter way to achieve the same result?

like image 954
Johan Avatar asked Nov 03 '09 07:11

Johan


2 Answers

Q: I have a variable x in python. How can i find the string 'x' from the variable.

A: If I am understanding your question properly, you want to go from the value of a variable to its name. This is not really possible in Python.

In Python, there really isn't any such thing as a "variable". What Python really has are "names" which can have objects bound to them. It makes no difference to the object what names, if any, it might be bound to. It might be bound to dozens of different names, or none.

Consider this example:

foo = 1
bar = foo
baz = foo

Now, suppose you have the integer object with value 1, and you want to work backwards and find its name. What would you print? Three different names have that object bound to them, and all are equally valid.

print(bar is foo) # prints True
print(baz is foo) # prints True

In Python, a name is a way to access an object, so there is no way to work with names directly. You might be able to search through locals() to find the value and recover a name, but that is at best a parlor trick. And in my above example, which of foo, bar, and baz is the "correct" answer? They all refer to exactly the same object.

P.S. The above is a somewhat edited version of an answer I wrote before. I think I did a better job of wording things this time.

like image 180
steveha Avatar answered Oct 20 '22 04:10

steveha


I believe the general form of what you want is repr() or the __repr__() method of an object.

with regards to __repr__():

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object.

See the docs here: object.repr(self)

like image 25
Gabriel Hurley Avatar answered Oct 20 '22 03:10

Gabriel Hurley