Modules are essentially similar to header files in C, but not exactly, and modules are similar to libraries, but not exactly. All Python files only look like scripts until they are "imported" by another Python program. Importing allows you to include a Python script and all the functions and variables it contains inside of another script or program. Code reuse is one of the primary reasons for having Modules.
Modules also create namespaces, which may or may not mean something do you. Suffice it to lssay that modules create there own scope, kind of like global and local scope, or local and function scope.
Modules are useful for storing data that needs to be shared between several programs, or several parts of programs.
Python Modules: All Python code is a Module as I said before, although not all of it is actually useful. Let's build a simple example, this one keeps track of some simple objects (We'll cover those very soon, sorry to jump ahead!).
# Intro To Python: Modules
# book.py
"""
Class: Book( title, author, keywords )
Each book object takes a title, optional author, and optional keywords.
"""
class Book:
def __init__(self, title, author="Unknown", keywords=[]):
"""
Books take three arguments to their constructor
The first and only required argument is the title,
followed by the optional arguments, author, and a list
of keywords that can be used to look up a specific book.
"""
self.title = title
self.author = author
self.keywords = keywords
def setTitle(self, title):
"""
Takes one argument, the title of the book object.
"""
self.title = title
def setAuthor(self, author):
"""
Takes one argument, the author of the book object.
"""
self.author = author
def setKeywords(self, keywords):
"""
Takes one argument, the keywords list for this book object.
"""
self.keywords = keywords
# Overload print operation, print a specific format for books.
def __str__(self):
s = "+++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
s += "+" + self.title + "\n"
s += "+" + self.author +"\n"
s += "+" + str(self.keywords) + "\n"
s += "+++++++++++++++++++++++++++++++++++++++++++++++++++++"
return s
Let's also include some functions:
# map.py
def map( fun, list ):
nlist = []
for item in list:
nlist.append( fun( item ) )
return nlist
def rmap ( fun, list ):
if list == []:
return []
else:
return [fun( list[0] )] + rmap( fun, list[1:] )
def increment(x):
return x+1
Finally, let's do a little example of using modules. In this case we are just interested in reusing code:
# Modules.py
# Let's import some modules:
from book import * # Notice we omit the suffix ".py" from "book.py"
import map # this has the map function and a few other neat things.
print map
# Now I can Create Book Object:
abook = Book("Robert A. Heinlein", "Stranger In a Strange Land", ["Mars","Martians"])
print abook
# What if I didn't remember that definition for the Book object?
import book
#List's everything in the "book.py" module
dir(book)
# Enter the help system and read about the book object. This will remind you of
# all the definitions and everything. Very convenient when you're working at
# the command prompt.
#help(book) # Uncomment to got help on the Book Object
# Let's call some functions in map to quickly increment this list :~)
# <sarcasm>( Real exciting ! )</sarcasm>
l = range(12, 76)
for i in range(0,64):
l = map.map( map.increment, l )
print l
This is one of the coolest features of Python for people converting code from C/C++ or Fortran to Python. You can actually write compiled extension modules that look and act just like standard Python modules to the Interpreter. This is generally accomplished with the help of SWIG, which I'll talk about and go over some examples of later.