CSC401: Modules

Creating Modules

Any Python file can be loaded as a module using import module

File called xyz.py becomes module xyz

Statements executed as program loads

Libraries typically just define constants and functions

Module contents referred to as module.content

E.g. sys.argv

Can also use

from module import name1, name2

from module import *

# stuff.py
value = 123
def printVersion():
    print "Stuff Version 2.2"
# loader.py
import stuff
print stuff.value     # note: modulename dot thing
stuff.printVersion()  # note again
$ python stuff.py
$ python loader.py
123
Stuff Version 2.2

Telling Them Apart

Special variable __name__ is module's name

Set to "__main__" when the file is run from the command line

Set to the module's name when it is loaded by something else

Often used to include self-tests in module

Tests use assert when module run directly

Self-Test Example

def double(val):
    return val * 2

if __name__ == '__main__':
    print "testing double"
    assert double(0) == 0
    assert double('a') == 'aa'
    assert double([1]) == [1, 1]
    print "tests passed"

Slides originally created by Greg Wilson. Adapted for CSC401 by David James. Revisions by Michelle Craig, Michael Szamosi, Karen Reid, and David James.