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![]()
![]()
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
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"