execfile: NameError exception thrown for things in locals()

Anthony Seward seward.dont.spam.me at nospam.ieee.org
Thu Apr 5 14:52:22 EDT 2001


I'm missing something subtle about the use of execfile.  All that
I want to do is something like

  execfile(fn)
  spam = Spam()
  
where 'fn' is the name of a file that has a definition of
the class Spam.  It doesn't seem to work because a NameError
gets thrown.  The class definition of Spam is in the local
dictionary, however.  Everything works OK if I read the file
and hand a string representing the file data to 'exec'.  I've
appended a python script that demonstrates what is happening.
Could someone please explain to me what is happening.

Thanks,
Tony

-----------
#!/usr/bin/python

import os
import tempfile

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

def test_exec(string):
    """
    Try to use 'exec' to load a class definition
    """
    exec string
    print '  %s' % str(locals())
    spam = Spam()

def test_homemade_execfile(fn):
    """
    Try to use a homemade version of execfile to load a class definition
    """
    file = open(fn)
    string = file.readlines()[0]
    file.close()
    exec string
    del file
    del string
    print '  %s' % str(locals())
    spam = Spam()

if __name__ == '__main__':
    string = 'class Spam:pass\n'
    fn = tempfile.mktemp('Spam.py')
    file = open(fn, 'w')
    file.write(string)
    file.close()
 
    try:
        print 'Trying execfile:'
        test_execfile(fn)
    except NameError, msg:
        print '  NameError:', msg
    else:
        print "  'execfile' worked"

    try:
        print 'Trying exec:'
        test_exec(string)
    except NameError, msg:
        print '  NameError:', msg
    else:
        print "  'exec' worked"

    try:
        print 'Homemade execfile:'
        test_homemade_execfile(fn)
    except NameError, msg:
        print '  NameError:', msg
    else:
        print "  Homemade execfile worked"

    os.remove(fn)



More information about the Python-list mailing list