python exec behaves inconsistent with respect to module imports

Daniel Larsson daniel.j.larsson at gmail.com
Wed Sep 5 09:47:18 EDT 2007


On 9/5/07, carl.dhalluin at gmail.com <carl.dhalluin at gmail.com> wrote:
>
> Hello
>
> I am completely puzzled why the following exec code does not work:
>
> mycode = "import math\ndef f(y):\n    print math.floor(y)\nf(3.14)"
> def execute():
>     exec mycode
> execute()
>
>
> I get the error:
>
> root at devmachine1:/opt/qbase# python error1.py
> Traceback (most recent call last):
>   File "error1.py", line 5, in ?
>     execute()
>   File "error1.py", line 4, in execute
>     exec mycode
>   File "<string>", line 4, in ?
>   File "<string>", line 3, in f
> NameError: global name 'math' is not defined


This is due to a namespace issue with exec, see
http://docs.python.org/ref/exec.html#l2h-569

The namespace used in an exec statement is the local scope. This scope is
different in your two cases. If you change the exec call to

def execute():
    exec mycode in globals()

It will work as you expect.


Note that the following code _does_ work:
>
> mycode = "import math\ndef f(y):\n    print math.floor(y)\nf(3.14)"
> exec mycode
>
>
> I have tested this in python 2.3 and 2.4.
>
>
> Regards
> Carl
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070905/86408454/attachment.html>


More information about the Python-list mailing list