Get more out of Python – Modules

Following on from my post on functions in this post I am going to expand the usage by creating a module to hold the functions.  A module in the simplest form is a Python script accessible to you program.  Modules you create can either be stored in the same folder and the script you are importing into or if you include the folder you want to save them into the PYTHONPATH environment variable you can store and used them from there.  Modules can hold a lot of useful tools that you want to reuse without having to retype or copy a lot of  code.  They would normally have a set of functions that have a common purpose and the module would be names accordingly, like the string and math modules.

Have a look at the script below (called

# A Test module
import random
months ={1:'January',2:'February',3:'March',4:'April',
__mymonths ={1:'January',2:'February',3:'March',4:'April',

def joinLists(lst1,lst2):
    """ Join two lists together"""
    return lst1 + lst2

def quicksort(L):
    """ A common implementation of a quicksort routine """
    if not L : return L
    pivot = random.choice(L)
    def lt(x): return x<pivot
    def gt(x): return x>pivot
    return quicksort(filter(lt,L))+[pivot]*L.count(pivot)+quicksort(filter(gt,L))
#end of the script

This is a script with a couple of functions and types.  Some things to note:

  1. The random module has been imported as it is required by one of the functions in the module
  2. functions are defined as usual
  3. the triple quote forms the help documentation (eg when a use types functions.quicksort.__doc__)
  4. __mymonths (a dictionary) has a double underscore before it and this becomes a private variable only visible inside the module
  5. the can be imported just like any other module when stored in the same folder as the script calling it or in a path specified in the PYTHONPATH environment variable
To use this new module we could write a short script to test or use the interactive window:
#Test the function module
#We have defined PYTHONPATH and saved in there, so this script can live anywhere on this computer
#import our module
import functions,datetime
#create a list
lst = [3,7,8,6,5,3,2,9,-1,-3]
#sort the list
print functions.quicksort(lst)
# print out the name of the current month
print functions.months[]
#end of out code
When we run the code we would get the following output:
[-3, -1, 2, 3, 3, 5, 6, 7, 8, 9]

You can now create and reuse code without having to add any additional code to a new script, just import you module.


Stephen B

Got something to say?

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s