[Python-ideas] *var()*
Guido van Rossum
guido at python.org
Fri Jan 3 01:16:39 CET 2014
On Thu, Jan 2, 2014 at 3:35 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> I would have guessed that you could get this working with eval, but if
> there is such a way, I can't work it out.
It's trivial if you directly invoke eval():
x = 42
def example():
print 'first:', eval('x')
y = 'hello world'
print 'second:', eval('y')
example()
will print
first: 42
second: hello world
Writing Liam's var() as a regular function would require using
sys._getframe() and won't access intermediate scopes; something like
this would at least find locals and globals:
def var(*args):
name = ''.join(map(str, args)) # So var('count', 1) is the same as
var('count1')
frame = sys._getframe(1) # Caller's frame
return eval(name, frame.f_globals, frame.f_locals)
Now this works as desired:
x = 42
def example():
print 'first:', var('x')
y = 'hello world'
print 'second:', var('y')
example()
All in all, agreed this doesn't need to be added to the language,
given that it's easy enough() to invoke eval() directly. (And advanced
programmers tend to use all kinds of other tricks to avoid the need.)
Two more things, especially for Liam:
(1) There was nothing stupid about your post -- welcome to the Python community!
(2) eval() is much more powerful than just variable lookup; if you
write a program that asks its user for a variable name and then pass
that to eval(), a clever user could trick your program into running
code you might not like to run, by typing an expression with a
side-effect as the "variable name". But if you're just beginning it's
probably best not to worry too much about such possibilities -- most
likely you yourself are the only user of your programs!
--
--Guido van Rossum (python.org/~guido)
More information about the Python-ideas
mailing list