I want a function that can return the variable/object name as str like this :
def get_variable_name (input_variable):
## some codes
>>get_variable_name(a)
'a'
>>get_variable_name(mylist)
'mylist'
it looks like silly but i need the function to construct expression regarding to the variable for later on ‘exec()’. Can someone help on how to write the ‘get_variable_name’ ?
I’ve seen a few variants on this kind of question several times on SO now. The answer is don’t. Learn to use a
dictanytime you need association between names and objects. You will thank yourself for this later.In answer to the question “How can my code discover the name of an object?”, here’s a quote from Fredrik Lundh (on comp.lang.python):
Note: It is technically possible to get a list of the names which are bound to an object, at least in CPython implementation. If you’re interested to see that demonstrated, see the usage of the
inspectmodule shown in my answer here:Can an object inspect the name of the variable it’s been assigned to?
This technique should only be used in some crazy debugging session, don’t use anything like this in your design.