next up previous contents
Next: Classes and Object Oriented Up: Writing Modules Previous: An Example   Contents


Test Programs for Modules

When you write a collection of functions, it's a very good idea to write a test program, to make sure that the functions are doing what you expect. That way, if you decide to make changes to the functions at some point in the future, you can quickly check to see if the functions still work. Of course, one way to create a test program would be to write the program in a separate file from the module itself. However, Python provides a convenient way to keep your test program in the same file as the module itself.

Remember that when you import a module into a Python program that the contents of the module are executed when the import statement is encountered. Thus, you can't just include your test program in your module, or it will be executed every time the module is imported. But Python provides a builtin variable called __name__, which will be equal to the name of a module when the module is imported, but will be equal to the value ``__main__'' when a program is executed directly. Thus, we could include a test program for the strfunc module by including the following lines in the file strfunc.py after the function definitions:

if __name__ == '__main__':
    import sys
    files = sys.argv[1:]
    for f in files:
        print 'Processing %s' % f
        print ' Longest line is %d characters' % lline(f)
        print ' File contains %d lines, %d words, and %d characters' % wcount(f)
        print ' The file contains %d spaces' % ccount(f,' ')
        print
Now when the program is invoked directly (for example through the execfile function, or by typing the program's name at a shell prompt), the test program will be run, but when the module is imported into another program, the test program is ignored. Notice that in this example, since the sys module is not needed for the functions defined in the fileutil module, the import statement for that module was placed after the if statement which checks for the value of __name__.


next up previous contents
Next: Classes and Object Oriented Up: Writing Modules Previous: An Example   Contents
Phil Spector 2003-11-12