1

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.

6
  • 'x' is supposed to be a global variable then, right? Commented Apr 27, 2014 at 19:01
  • 'x' should be whatever is in scope at the calling function, a local variable if one is defined. I'll update to make it more clear. Commented Apr 27, 2014 at 19:03
  • Is this question academic or do you have a use case in mind? Commented Apr 27, 2014 at 19:04
  • docs.python.org/2/library/inspect.html#the-interpreter-stack Commented Apr 27, 2014 at 19:07
  • I had implemented something like this in C. I used hash tables; you might want to consider using a global dict or something similar. {'x' : x}, I mean. Commented Apr 27, 2014 at 19:10

3 Answers 3

3

The inspect module will allow you to pull values out of the calling stack. This function will take a list of variables and print their values

import inspect
def printVaribles(*args):
    for arg in args:
        print "%12s:%s"%(arg, inspect.stack()[1][0].f_locals[arg])

printVariables('x','y','z')
Sign up to request clarification or add additional context in comments.

5 Comments

If this question was different, how is your answer so similar to this one in the referenced duplicate?
BTW, congratulations for the honorable mention in a meta post.
The answer is similar because the other poster was trying (and failing) to ask this question. But you're voting for a duplicate answer and not a duplicate question.
Where am I in the meta comment? I couldn't find it!! BTW did you know I'm the person responsible for setting up meta? I was having lunch with Jeff and telling him that no amount of hectoring would stop people from discussing the site on the site and that his only choice was to make another place for people to discuss the site.
This only fetches variables from the immediate scope, though --- if you're in a nested function it won't show variables from the enclosing static scopes (or globals).
0

You want to evaluate the variable, so just:

val = eval('x')

If you want to know what is defined, you can take a look at the dictionaries provided by locals() and globals().

Comments

0

It's a little weird, but you might could use **kwargs to achieve the desired effect.

def foo(**kwargs):
    return kwargs

In a use-case it'd be something like:

this = 13
foo(this=this) # returns {'this': 13}

If you use locals() you'll get whatever the name of the argument is in the definition of the function. For example...

def bar(your_arg):
    return locals()

The above will always return your_arg as the key of the dict, regardless of its name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.