Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you print a variable name itself in Python?

Python print variables using a comma “,”: This method is another commonly used method in Python to print variables. This method is quite similar to the string concatenation method; however, here we use “,” between the variables. Additionally the “,” itself adds a space to the string and you would not have to add it.

How do you print a variable name instead of a value?

Then you just have to change the print line from: print(name[6:-1] , ':' , var) , to , print(name[2:-1] , ':' , var) . Enjoy!

How do you retrieve a variable in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do you print an object name in Python?

Print an Object in Python Using the __repr__() Method It, by default, returns the name of the object's class and the address of the object. When we print an object in Python using the print() function, the object's __str__() method is called.


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.


Yes.

In your case with enums, it's easy:

>>> from enum import Enum
>>> class Type(Enum):
...   AB, SBS, INTERLACED, SPLIT = range(4)
...
>>> Type.AB
<Type.AB: 0>
>>> print(Type.AB)
Type.AB
>>> Type.AB.name
'AB'
>>> Type.AB.value
0
>>> Type(0)
<Type.AB: 0>

In general, it could be ambiguous:

>>> def varname(v): d = globals(); return [k for k in d if d[k] == v]
...
>>> def varnameis(v): d = globals(); return [k for k in d if d[k] is v]
...
>>> foo = {'a':'aap'}
>>> bar = {'a':'aap'}
>>> varname(foo)
['foo', 'bar']
>>> varnameis(foo)
['foo']

Or even misleading:

>>> foo = "A"; bar = "A"
>>> varnameis("A")
['foo', 'bar']
>>> foo = "An immutable value."; bar = "An immutable value."
>>> varnameis("An immutable value.")
[]
>>> foo = "An immutable value."; bar = "An immutable value."; varnameis("An immutable value.")
['foo', 'bar']
>>> import sys; sys.version
'3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 02:47:15) [MSC v.1900 32 bit (Intel)]'

To search in any scope, use this:

>>> def varname(v, scope=None): d = globals() if not scope else vars(scope); return [k for k in d if d[k] == v]
...
>>> import time
>>> time.timezone
-3600
>>> varname(-3600)
[]
>>> varname(-3600, time)
['timezone']

To avoid ambiguity, wrap your name with the data.


Python 3.8 added a new and probably a LITTLE better solution to this:

my_nice_variable_name = 'test'
print(f'{my_nice_variable_name=}')

# Output:
# my_nice_variable_name='test'

Here you could work with the string output. Still not advisable but maybe a little better than other ways of doing it.


Just use the text you want to print as the value of the enum, as in

class MyEnum (object):
    valueA = "valueA"
    valueB = "valueB"

comparing strings for identity is almost as efficient in Python as is comparing integer values (this is due to the fact the strings are immutable as have a hash value)

Of course there are easier ways to create the enum in the first place:

class Enum (object):
    def __init__(self, *values):
        for v in values:
            self.__dict__[v] = v

Then, create you enumeration like this:

MyEnum = Enum("valueA", "valueB")

ans access the same way as above:

MyEnum.valueA