Explain modules to me PLEASE

Skip Montanaro skip at pobox.com
Thu Aug 16 01:05:33 EDT 2001


    >> Can some one explain to a very new newbie how to use modules?

Modules are the standard way of structuring a Python program so it does not
grow into a monolithic mess.  (Python also provides packages, but they are
just modules in fancy dresses... ;-) Modules foster code reuse by isolating
functions, classes and data objects sharing common functionality into
discrete chunks.  They also provide a single level of hierarchy in naming
objects.  (Packages can provide arbitrary levels of namespace isolation.)

Consider the list of modules documented for the Python distribution:

    http://www.python.org/doc/current/lib/modindex.html

Take a look at the atexit module.  It's very small, just exporting a single
function: register.  Instead of having to reimplement its functionality in
my programs I can just import the atexit module and call its register
function to register any number of functions I want executed at program
exit.

Here's a trivial program that is implemented as three files, a.py:

    import atexit

    def work():
      print "whew! work is hard"

    def exit():
      print "module a is cleaned up"

    atexit.register(exit)

b.py:

    import atexit

    def work():
      print "not as hard as it might be"

    def exit():
      print "module b is spic and span"

    atexit.register(exit)

and a main program, prog.py:

    import a
    import b

    print "taking a nap..."
    import time
    time.sleep(5)

    print "maybe I should do some work..."
    a.work()
    b.work()

then run it, it prints out the nap message, then after a five second nap it
does its "work" by calling a.work and b.work, and when execution falls off
the end of prog.py and the Python interpreter is about to exit, your exit
functions are executed:

    % python prog.py
    taking a nap...
    maybe I should do some work...
    whew! work is hard
    not as hard as it might be
    module b is spic and span
    module a is cleaned up

Note that modules provide me with a way to keep pieces of my program from
conflicting with one another.  Both modules a and b defined functions named
"exit" and "work", but there was no conflict because the contexts of the two
modules were separate.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list