klenwell information services : PywellModules

Pywell Lesson: Modules

return to Tutorial Index



Modules serve as a logical unit of code in Python, such as a library or plugin. Modules can be a single file or part of a nested directory. An example of a very simple module in a single file:

    A stupid simple Python module  

def simple():
    print "simple (but not very useful)"
def test():
    assert "simple" in simple()
if __name__ == "__main__":

Assuming the file was named stupid.py and on your PYTHONPATH*, you could use it from the interpreter like so:

>>> import stupid
>>> stupid.simple()

If you were developing a more complex library, you'd probably want your module to have multiple files organized into a directory. To do that, create a directory with your module name and add your python files to that. Then to inform the interpreter that you want this directory to be treated as a module that can be imported, simply add an empty file named init.py. The resulting directory tree will look something like this:

|-- simple.py
|-- hard.py
\-- __init__.py

The simple module could then be imported by a Python script in a couple different ways:

# as part of the stupid namespace
import stupid

# or directly using from... import syntax
from stupid import simple


As you venture into Python, you'll see this mysterious __init__.py file a lot. You can even include code in it. But it's primary function is to say to the interpreter, "Hey! This directory is a Python module."

The beauty of modules is that they provide a rather elegant and intuitive way to organize your code. You may remember the final line from the Zen of Python:

Namespaces are one honking great idea -- let's do more of those!

Modules define namespaces, which keep your code neatly organized and help avoid naming collisions.

Batteries Included

Python comes with many builtin modules, such as the sys module to which you've already been introduced. Other builtin modules include os, math, and re for regular expressions. Because of the breadth and utility of its builtin modules, Python is often touted as coming "batteries included," a feature that has been famously satirized here:


* See references section below


Create a module named antigravity that includes a submodule named flying which includes the following function:

def fly():
	print "Oh, if only it were this easy."

Extra Credit

  1. What is happening in the __name__ == "__main__" block of the stupid module above?
  2. Either write a script or from the command line import your flying module and call the fly function. (Hint: if you're working in the interactive interpreter, the sys module's path attribute may be of some help.)