Name space quirk?

Alex new_name at mit.edu
Sun Jul 22 21:28:38 CEST 2001


Hi, Gangadhar.  I hope I'm addressing you appropriately. :)

The issue there is that the "if __name__ == '__main__':" block is not
executed when the module is imported, because in that case, "__name__"
is bound to the name of the module, in this case, "nspace".  As a
result, in the "nspace" namespace, nothing is bound to "myfile", so the
"myfile.write" command raises a NameError.  The "global" keyword only
means "global to the module" not "global to the entire program."  The
"myfile" you bound in the interpreter is in the "__main__" namespace.

Try this version:

#!/usr/bin/env python

from os import sys
 
def hello (outfile = sys.stdout):
        # We are writing to what should be an
        # unknown file descriptor:
        global myfile                         # <------- Added
        myfile.write ("Hello, world!\n")

print "Value of __name__ is", __name__
 
if __name__ == '__main__':
        f = sys.argv[0] + ".out"
        print "This line doesn't get executed"
        myfile = open (f, 'w')
        hello (myfile)

I'll leave it to the more erudite people on the list to debate the
merits of this arrangement.  I've been using it for years, and I'm too
familiar with it to really think critically about it, anymore,
anyway. :)

Alex.



More information about the Python-list mailing list