Execfile issue

Dan Yamins dyamins at gmail.com
Tue Jun 17 18:21:50 EDT 2008


I'm having (what I assume is) a simple problem regarding the way import and
execfile interact.  I apologize in advance for my naivete.

Lets say I have the function:

   def Func1():
       print dir()
       execfile('testfile')
       print dir()
       X

and the file

   #file: testfile
      X = 3


Then,  when I run Func1 , I get the output:

   >>> Func1()
   []
   ['X']
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "<stdin>", line 5, in Func1
   NameError: global name 'X' is not defined


SO, I have three questions:
    1) Naively, I would think that the call to "execfile" in Func1 would act
as if the line was replaced with the lines of 'testfile'.  But obviously
not, in some way that has to do with the subtlety of the python compilation
process.   Can someone explain exactly what the problem is?
    2) Why would something show up in the dir() call, but not be defined
(e.g. like 'X' did in the second dir() call in Func1()) ?
    3) Is there any way to fix this that does not involved (essentially in
one way or another) importing "testfile" as a py module?   I would like to
avoid that scenario for a variety of reasons ...

Thanks!

Dan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080617/4f9fab95/attachment.html>


More information about the Python-list mailing list