namespaces in eval(): spot error in 3 line program
Just
just at xs4all.nl
Wed May 25 12:38:14 EDT 2005
In article <1117035976.997084.305310 at g47g2000cwa.googlegroups.com>,
"pasa" <harri.pasanen at trema.com> wrote:
> I'm an old time python user, but just got bitten by namespaces in eval.
> If this is an old discussion somewhere, feel free to point me there.
>
> Based on the documentation, I would have expected the following to
> work:
>
> def foo(k): print k; print a
>
> ns = {'a':1, 'foo': foo}
> eval('foo(2)', ns)
>
> But it does not, complete session:
>
> [harri at labsdevgrid1 ~]$ python
> Python 2.4 (#2, Feb 13 2005, 22:08:03)
> [GCC 3.4.3 (Mandrakelinux 10.1 3.4.3-3mdk)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def foo(k): print k; print a
> ...
> >>> ns = {'a':1, 'foo': foo}
> >>> eval('foo(2)', ns)
> 2
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<string>", line 0, in ?
> File "<stdin>", line 1, in foo
> NameError: global name 'a' is not defined
> >>>
>
> huh? I'd almost be tempted to call this a bug?
>
> Playing with locals() and globals() I see that this one works,
> which I would not have expected to work:
>
> def foo(k): print k; print ns['a']
>
> ns = {'a':1, 'foo': foo}
> eval('foo(2)', ns)
>
> Prints out
> 2
> 1
>
> Do functions carry their own pointer to global namespace,
> which gets defined at function compile time, or what is
> happening here?
Function definition time. Your code is more or less equivalent to:
# A.py:
def foo(k): print k; print a
# B.py:
from A import foo
a = 1
foo()
That will fail with a NameError just the same.
Just
More information about the Python-list
mailing list