note on closing: this question has been suggested as a duplicate but the two questions actually ask different questions: find the name of a variable versus access a value by name. May Heaven bless readers who carefully review questions before pushing the dupe button.
Python - find the name of a variable that was passed to the function
Suppose I have a function to print a variable's contents:
def printVariable(varname, val):
print "%s: %s" % (varname, val)
printVariable('x', x)
How can I modify this to look at the calling stack and extract the variable's value?
def printVarible(varname):
val = WHAT MAGIC GOES HERE?
print "%s: %s" % (varname, val)
printVariable('x')
Variable resolution should be at the scope of the caller... if it's in a function and there's a local variable, it should be preferred over a global variable.