Repost: execfile() confusion

Nathaniel Gray n8gray at caltech.edu.is.my.e-mail.address.com
Sat Sep 29 03:14:34 CEST 2001


Nathaniel Gray wrote:
> So once again, execfile() isn't doing what I thought it did.

Even stranger:

"""
#### test2.py ####
print 'My Locals:', locals().keys()
print
x = 'spam'

#### test.py ####
def doit():
    joe = 99
    execfile( 'test2.py' ) # x = 'spam'
    print x
    
doit()
"""

These two files give:

[n8gray at charter-DHCP-162 tmp]$ python test.py
My Locals: ['joe']
 
Traceback (most recent call last):
  File "test.py", line 7, in ?
    doit()
  File "test.py", line 5, in doit
    print x
NameError: global name 'x' is not defined

So the locals when x = 'spam' is executed are indeed the locals of test.doit, 
but x doesn't get added to the namespace.  execfile seems to have read-only 
access to the locals.

Because my mind wasn't yet completely melted, I tried it at the interactive 
prompt with the same test2.py file:

[n8gray at charter-DHCP-162 tmp]$ python
Python 2.1.1 (#2, Jul 31 2001, 14:10:42)
[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> execfile( 'test2.py' )
My Locals: [ ... all the convenience functions in my startup file ... ]
>>> # No error!  It worked!
>>> print x
spam
>>> del x
>>> # But if I define a function:
>>> def doit():
...     joe = 99
...     execfile( 'test2.py' ) # x = 'spam'
...     print x
...
>>> doit()
My Locals: ['joe']
 
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in doit
NameError: global name 'x' is not defined
>>> # No dice

Please, somebody, anybody, what's going on??

-n8

-- 
Nathaniel Gray

California Institute of Technology
Computation and Neural Systems
--




More information about the Python-list mailing list