Name space quirk?

Will Ware wware at world.std.com
Sun Jul 22 14:41:46 CEST 2001


NANDYALA D Gangadhar (n_d_gangadhar at yahoo.com) wrote:
> ... the interactive python shell catches the 
> NameError (on "myfile"):

> from os import sys
>  
> def hello (outfile = sys.stdout):
>         # We are writing to what should be an
>         # unknown file descriptor:
>         myfile.write ("Hello, world!\n")
>  
> if __name__ == '__main__':
>         f = sys.argv[0] + ".out"
>         myfile = open (f, 'w')
>         hw (myfile)

> Is this behaviour desirable and correct? I guess it can lead to 
> unanticipated results. 

Yup, you actually want a NameError here. At the point where you
are defining hello(), you start talking about 'outfile' in a way
that totally makes sense, but then you call a method of 'myfile'.
hello() is not blessed with the gift of prophecy, and is unaware
that you will later declare a global variable called 'myfile'.
If you really want to write to 'myfile' rather than 'outfile',
then you might want something like:

def hello (outfile = sys.stdout):
        global myfile
        myfile.write ("Hello, world!\n")

This tells hello() that it should expect to find a global variable
called 'myfile', and should write to that. If you then forget to
create a global called 'myfile', you'll get another NameError.

It's a general rule of thumb among programmers, and particularly
so with object-oriented programming, that you want to avoid too
many global variables. Some people (or languages) get very excited
about this principle; Java doesn't allow global variables at all.
Others view it as a general guideline to be overridden if the
programmer has a good reason.

-- 
-----------------------------------+---------------------
 22nd century: Esperanto, geodesic | Will Ware
 domes, hovercrafts, metric system | wware at world.std.com



More information about the Python-list mailing list