[Tutor] corresponding command in Python to "eval" in Matlab
Kent Johnson
kent37 at tds.net
Sun Oct 7 22:36:26 CEST 2007
Eric Brunson wrote:
> However, I didn't actually answer your question.
>
> As Kent has already mentioned, eval is quite dangerous in python and to
> be avoided when possible. I think it would be safer to do something
> like this:
>
> l = locals()
> for x, y in zip( varlist, data ):
> l[x] = y
>
> or, more tersely:
>
> [ locals()[x] = y for x, y in zip( varlist, data ) ]
>
>
> This will accomplish what you're trying to do, but a dict really gives
> you greater functionality than assigning to local variables.
This will only work at global scope where locals() is globals() and
writable. In function scope assigning to locals()[...] does not change
the local namespace:
In [27]: def foo():
....: locals()['x'] = 1
....: print x
....:
....:
In [28]: foo()
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
File "<ipython console>", line 3, in foo
<type 'exceptions.NameError'>: global name 'x' is not defined
Kent
More information about the Tutor
mailing list