Re: Help identifying

Tim Peters (tim@ksr.com)
Sun, 08 May 94 23:59:25 -0400

> [tommy]
> Ah, but Tim! You've forgotten to take advantage of one of our
> new (v1.0.2) features! [vars()]

Indeed I did! Although he could have gotten the effect of

> v = vars(__main__)

before via

v = __main__.__dict__

There are a lot of ways to do this!

> Who needs eval when you have vars?

Just because of this:

> | ...
> | A more general trick is to use 'eval' to map a variable's name (a string)
> | to the variable's current binding. E.g., ...

eval looks through the bindings of local, global, and builtin names,
while vars() only finds the local ones. In the interactive examples this
gets confused, because the local & global namespaces are the same when
typing stuff at Python at the top level. So I suspect eval has less
"gotcha" potential for beginners. E.g.,

>>> a = 12
>>> print eval('a')
12
>>> print vars()['a']
12
>>> def f():
... print eval('a')
... print vars()['a'] # blows up
...
>>> f()
12
Traceback (innermost last):
File "<stdin>", line 1
File "<stdin>", line 3
KeyError: a
>>>

Understanding why eval "works" in both contexts but vars() doesn't isn't
difficult, but probably isn't _obvious_ to a beginner either.

whatever!-ly y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp