execfile: NameError exception thrown for things in locals()

Robin Thomas robin.thomas at starmedia.net
Thu Apr 5 17:03:46 EDT 2001


At 06:52 PM 4/5/01 +0000, Anthony Seward wrote:
>I'm missing something subtle about the use of execfile.  All that
>I want to do is something like
>
>   execfile(fn)
>   spam = Spam()

Yes, it is very subtle, and not your fault at all. As a workaround, insert 
the following line in test_execfile:

def test_execfile(fn):
     """
     Try to use 'execfile' to load a class definition
     """
     exec "pass"  # <<< THIS MAKES IT ALL OK
     execfile(fn)
     print '  %s' % str(locals())
     if 'Spam' in locals().keys():
         # __ 'Spam' is in locals() so why does this produce a NameError
         spam = Spam()

I'll try to avoid an overly specific explanation of the glitch:

Python compiles functions with a special optimization: that the only local 
variables that can be loaded by name are variables named as arguments or 
with an assignment = statement. This optimization helps function code run 
MUCH faster; the drawback is that if you dynamically execute code in the 
function's locals environment, any variable names added by that executed 
code won't be accessible, and a NameError will be raised.

So Python does *not* use the optimization if the function's code contains 
any exec statement. But Python does not turn off the optimization if you 
use execfile(), for various reasons not worth getting into here. That 
sucks, but the workaround is to throw in an exec that does nothing. Also, 
you can make sure that execfile() does not use the current locals 
namespace, by passing in a new namespace of your own.

Hey, everyone, is this a known bug with a planned fix?


--
Robin Thomas
Engineering
StarMedia Network, Inc.
robin.thomas at starmedia.net





More information about the Python-list mailing list