How to print original variable's name in Python after it was returned from a function?

Short answer: no.

Long answer: this is possible with some ugly hacks using traceback, inspect and the like, but it's generally probably not recommended for production code. For example see:

  • http://groups.google.com/group/comp.lang.python/msg/237dc92f3629dd9a?pli=1
  • http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/330294

Perhaps you can use a workaround to translate the value back to a name/representational string. If you post some more sample code and details about what you're wanting this for maybe we can provide more in-depth assistance.


There is no such thing as a unique or original variable name http://www.amk.ca/quotations/python-quotes/page-8

The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)...

....and don't be surprised if you'll find that it's known by many names, or no name at all!

Fredrik Lundh, 3 Nov 2000, in answer to the question "How can I get the name of a variable from C++ when I have the PyObject*?"


To add to @Jay's answer, some concepts...

Python "variables" are simply references to values. Each value occupies a given memory location (see id())

>>> id(1)
10052552

>>> sys.getrefcount(1)
569

From the above, you may notice that the value "1" is present at the memory location 10052552. It is referred to 569 times in this instance of the interpreter.

>>> MYVAR = 1
>>> sys.getrefcount(1)
570

Now, see that because yet another name is bound to this value, the reference count went up by one.

Based on these facts, it is not realistic/possible to tell what single variable name is pointing to a value.

I think the best way to address your issue is to add a mapping and function to your enum reference back to a string name.

myEnum.get_name(myEnum.SomeNameA) 

Please comment if you would like sample code.