Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: execfile (exec?) create non consistent locals() state

Reply
Thread Tools

Re: execfile (exec?) create non consistent locals() state

 
 
Chris Rebert
Guest
Posts: n/a
 
      04-21-2009
On Tue, Apr 21, 2009 at 11:25 AM, Doron Tal <> wrote:
> On Tue, Apr 21, 2009 at 9:13 PM, Chris Rebert <> wrote:
>>
>> On Tue, Apr 21, 2009 at 9:08 AM, Doron Tal <>
>> wrote:
>> > Hi,
>> >
>> > Recently I tried to execute a python file using execfile (exec performed
>> > just the same for that reason).
>> > I encountered the behavior below:
>> >
>> > """
>> > $ cat execme.py
>> > a = 2
>> > $ python
>> > Python 2.4.3 (#1, May 24 2008, 13:57:05)
>> > [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
>> > Type "help", "copyright", "credits" or "license" for more information.
>> >>>> def execfile_func():
>> > ...Â*Â*Â*Â* execfile('execme.py')
>> > ...Â*Â*Â*Â* print 'locals() = %s' % str(locals())
>> > ...Â*Â*Â*Â* print a
>> > ...
>> >>>> execfile_func()
>> > locals() = {'a': 2}
>> > Traceback (most recent call last):
>> > Â* File "<stdin>", line 1, in ?
>> > Â* File "<stdin>", line 4, in execfile_func
>> > NameError: global name 'a' is not defined
>> >>>>
>> > """
>> >
>> > After execfile, the a variable can be found in locals(), however any
>> > direct
>> > reference (e.g., print a) fails.
>> > Is it expected?

>>
>> Yes. See http://docs.python.org/library/functions.html#locals (emphasis
>> mine):
>>
>> locals()
>> Â* Â*[...]
>> Â* Â*Warning: The contents of this dictionary should not be modified;
>> ***changes may not affect the values of local variables used by the
>> interpreter***.
>> Â* Â*[...]
>>
>> Cheers,
>> Chris
>> --
>> I have a blog:
>> http://blog.rebertia.com

>
> (Chris - sorry for the multiple replies, I forgot to reply all)
>
> I actually did not attempt to modify this dictionary (the one which locals()
> returns) explicitly.


Well, it can be reasonably inferred that execfile() does.

> The simplest assignment command, such as 'a = 2' modifies this dictionary
> implicitly, and it's working perfectly well.


While the exec'd file may run fine using the locals() dict (or any
dict for that matter), that doesn't say anything about whether the
changes to locals() will actually be reflected in the local namespace
it came from, which indeed, as documented, it's not. execfile() may
use the locals() dict for all its variable lookups, but the plain
toplevel interpreter is allowed not to.

> 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?


I don't know personally. Perhaps a kind soul will chime in.

Cheers,
Chris

--
I have a blog:
http://blog.rebertia.com
 
Reply With Quote
 
 
 
 
Peter Otten
Guest
Posts: n/a
 
      04-22-2009
[original post is not on my news server]

[Doron Tal]

>>> > Recently I tried to execute a python file using execfile (exec
>>> > performed just the same for that reason).


Not not over here here:

Python 2.4.4 (#2, Aug 1 2008, 00:04:43)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():

.... execfile("execme.py")
.... print "locals:", locals()
.... print a
....
>>> f()

locals: {'a': 2}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in f
NameError: global name 'a' is not defined
>>> def g():

.... exec open("execme.py").read()
.... print "locals:", locals()
.... print a
....
>>> g()

locals: {'a': 2}
2

The reason is that while execfile() is just an ordinary function the exec
statement affects the function's bytecode (LOAD_NAME instead of LOAD_GLOBAL
or LOAD_FAST). This leads to the following Voodoo:

>>> def h():

.... exec ""
.... execfile("execme.py")
.... print "locals:", locals()
.... print a
....
>>> h()

locals: {'a': 2}
2

While this is certainly not the most regular behaviour it allows to avoid
going through a dictionary for every assignment in functions that don't
have an exec statement, thus giving you faster code in the vast majority of
cases at the cost of a few quirks like the one you encountered.

Peter

 
Reply With Quote
 
 
 
 
Peter Otten
Guest
Posts: n/a
 
      04-22-2009
[original post is not on my news server]

[Doron Tal]

>>> > Recently I tried to execute a python file using execfile (exec
>>> > performed just the same for that reason).


Not over here:

Python 2.4.4 (#2, Aug 1 2008, 00:04:43)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():

.... execfile("execme.py")
.... print "locals:", locals()
.... print a
....
>>> f()

locals: {'a': 2}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in f
NameError: global name 'a' is not defined
>>> def g():

.... exec open("execme.py").read()
.... print "locals:", locals()
.... print a
....
>>> g()

locals: {'a': 2}
2

The reason is that while execfile() is just an ordinary function the exec
statement affects the function's bytecode (LOAD_NAME instead of LOAD_GLOBAL
or LOAD_FAST). This leads to the following Voodoo:

>>> def h():

.... exec ""
.... execfile("execme.py")
.... print "locals:", locals()
.... print a
....
>>> h()

locals: {'a': 2}
2

While this is certainly not the most regular behaviour it allows to avoid
going through a dictionary for every assignment in functions that don't
have an exec statement, thus giving you faster code in the vast majority of
cases at the cost of a few quirks like the one you encountered.

Peter

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
With non-risk and non-misgiving to gain cheap obscene DVD video or clips! (Non-Mask, Only cost 6 $ / per disc) huglig Computer Support 0 10-09-2007 01:42 AM
With non-risk and non-misgiving to gain cheap obscene DVD video or clips! (Non-Mask, Only cost 6 $ / per disc) huglig DVD Video 2 10-06-2007 02:30 PM
TypeError: Cannot create a consistent method resolution order (MRO) for bases object digitalorganics@gmail.com Python 8 06-27-2006 06:57 AM
(const char *cp) and (char *p) are consistent type, (const char **cpp) and (char **pp) are not consistent lovecreatesbeauty C Programming 1 05-09-2006 08:01 AM
Unable to serialize the session state. Please note that non-serializable objects or MarshalByRef objects are not permitted when session state mode is 'StateServer' or 'SQLServer'. Mike Larkin ASP .Net 1 05-23-2005 12:33 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57