Bug in execfile?

Ian Clark iclark at mail.ewu.edu
Thu Aug 2 16:57:29 EDT 2007


Fernando Perez wrote:
> Hi all,
> 
> (snip)
> 
> I'm really, really puzzled by this.  From reading the execfile() docs, I had
> the hunch to change the call to:
> 
>     execfile(fname,{})
> 
> and now the problem disappears, so I can keep on working.
> 
> But I'm still very bothered by the fact that changing that first call 'if 0'
> to 'if 1' has any effect on the later call to runscript().  That really
> doesn't feel right to me...

First an example:

#foo.py

from math import sin

#EOF

 >>> dir()
['__builtins__', '__doc__', '__name__']
 >>> execfile('foo.py')
 >>> dir()
['__builtins__', '__doc__', '__name__', 'sin']

New session:
 >>> dir()
['__builtins__', '__doc__', '__name__']
 >>> execfile('foo.py', {})
 >>> dir()
['__builtins__', '__doc__', '__name__']
 >>> help(execfile)
Help on built-in function execfile in module __builtin__:

execfile(...)
     execfile(filename[, globals[, locals]])

     Read and execute a Python script from a file.
     The globals and locals are dictionaries, defaulting to the current
     globals and locals.  If only globals is given, locals defaults to 
      it.

By default execfile works on the *current* namespace. So exec'ing a 
script that modified it's global namespace will also modify the global 
namespace of the calling module (see my first example). If you specify a 
dictionary then execfile will use that as the global and local (maybe) 
namespace of the file that it is running (hence the global namespace of 
the calling module stays in tact per the second example). That is why 
execfile(fname, {}) works for you, it doesn't pollute your current 
namespace. It uses a different namespace when calling the file then is 
being used by the calling module.

No idea why your function failed though. *shrug*

Ian




More information about the Python-list mailing list