<div dir="ltr"><br><br><div class="gmail_quote">On Tue, Apr 21, 2009 at 9:13 PM, Chris Rebert <span dir="ltr"><<a href="mailto:clp2@rebertia.com">clp2@rebertia.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<div><div></div><div class="h5">On Tue, Apr 21, 2009 at 9:08 AM, Doron Tal <<a href="mailto:doron.tal.list@gmail.com">doron.tal.list@gmail.com</a>> wrote:<br>
> Hi,<br>
><br>
> Recently I tried to execute a python file using execfile (exec performed<br>
> just the same for that reason).<br>
> I encountered the behavior below:<br>
><br>
> """<br>
> $ cat execme.py<br>
> a = 2<br>
> $ python<br>
> Python 2.4.3 (#1, May 24 2008, 13:57:05)<br>
> [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2<br>
> Type "help", "copyright", "credits" or "license" for more information.<br>
>>>> def execfile_func():<br>
> ...     execfile('execme.py')<br>
> ...     print 'locals() = %s' % str(locals())<br>
> ...     print a<br>
> ...<br>
>>>> execfile_func()<br>
> locals() = {'a': 2}<br>
> Traceback (most recent call last):<br>
>   File "<stdin>", line 1, in ?<br>
>   File "<stdin>", line 4, in execfile_func<br>
> NameError: global name 'a' is not defined<br>
>>>><br>
> """<br>
><br>
> After execfile, the a variable can be found in locals(), however any direct<br>
> reference (e.g., print a) fails.<br>
> Is it expected?<br>
<br>
</div></div>Yes. See <a href="http://docs.python.org/library/functions.html#locals" target="_blank">http://docs.python.org/library/functions.html#locals</a> (emphasis mine):<br>
<br>
locals()<br>
    [...]<br>
    Warning: The contents of this dictionary should not be modified;<br>
***changes may not affect the values of local variables used by the<br>
interpreter***.<br>
    [...]<br>
<br>
Cheers,<br>
Chris<br>
<font color="#888888">--<br>
I have a blog:<br>
<a href="http://blog.rebertia.com" target="_blank">http://blog.rebertia.com</a></font></blockquote><div>(Chris - sorry for the multiple replies, I forgot to reply all)<br><br></div></div>I actually did not attempt to modify this dictionary (the one which locals() returns) explicitly.<br>
The simplest assignment command, such as 'a = 2' modifies this dictionary implicitly, and it's working perfectly well.<br>
I expected exec to work the same, but apparently I was wrong. Is there
is a way to exec a file "more" correctly? thus avoid the need to resort
to awkward solutions such as using the locals() dictionary?</div>