Mike
Mike

Reputation: 21

referencing a variable in another function?

I'm an experienced TCL developer and write my own procedures to help myself along. i.e. a proc i call putsVar, it prints out the value of the variable in a definitave format, so I know which variable it is and what the value is "set foo 1 ; putsVar foo" Result 'foo="1"' I'd like to do the same kind of thing in python, but not finding the answer :( . In TCL I use the upvar command since I pass the name of the variable in, then I upvar and can see the value.

I understand that python doesn't have an upvar type mechanism, but with its introspection capaility, I would think this is somewhat trivial, but I'm not finding the answer anywhere.

Here's how i think it should work:

def printVar(var):
    valVar = "some mechanism to look up 1 level here to get value of var"
    print str(var) + "=\"" + str(valVar) + "\""

x = "Hello"
printVar("x")
x="Hello"

and extended:

def foo():
    y = "Hello World"
    printVar("y")

foo()
y="Hello World"

Upvotes: 2

Views: 436

Answers (2)

Cat Plus Plus
Cat Plus Plus

Reputation: 130004

You can, but you shouldn't. If your code downright needs it, then something is wrong with your design, and you probably should be using explicitly passed dictionaries or objects with proper attributes.

But, to answer the question directly: you can use sys._getframe. Just be aware that this might not be portable across Python implementations (i.e. work only on CPython):

def get_object(name):
   return sys._getframe(1).f_locals[name]

x = 'foo bar'
print get_object('x')

def foo():
    y = 'baz baf'
    print get_object('y')

foo()

Upvotes: 1

user626998
user626998

Reputation:

Perhaps I'm not 100% clear on what you want but you can expand printVar a bit so that you pass in the name of the variable (as you want it printed) as well as the variable itself.

def printVar(var, var_name):
    print "{0} = {1}".format(var_name, var)

>>> x = 5
>>> printVar(x, "x")
x = 5
>>> y = "Hello"
>>> printVar(y, "y")
y = Hello

To my knowledge, there's no good way to get a string representation of a variable name. You'll have to provide it yourself.


I'll expand it to fit your example a bit better:

def printVar(var, var_name):
    if type(var) is type(str()):
        print '{0} = "{1}"'.format(var_name, var)
    else:
        print '{0} = {1}'.format(var_name, var)
>>> printVar(x, "x")
x = 5
>>> printVar(y, "y")
y = "Hello"

Upvotes: 0

Related Questions