Making Your Own Modules 

A Byte of Python 

Go to the Table of Contents. Visit the Gifcom web site.

Creating your own modules is easy, you've been doing it all along! Every Python program is also a module. You just have to make sure it has a .py extension. The following example should make it clear.

Creating your own Modules

Example 8.3. How to create your own module

# Filename:

def sayhi():
	print 'Hi, this is mymodule speaking.'

version = '0.1'

# End of

The above was a sample module. As you can see, there is nothing particularly special about compared to our usual Python program. We will next see how to use this module in our other Python programs.

Remember that the module should be placed in the same directory as the program that we import it in, or the module should be in one of the directories listed in sys.path .

# Filename:

import mymodule

print 'Version', mymodule.version


$ python
Hi, this is mymodule speaking.
Version 0.1

How It Works

Notice that we use the same dotted notation to access members of the module. Python makes good reuse of the same notation to give the distinctive 'Pythonic' feel to it so that we don't have to keep learning new ways to do things.


Here is a version utilising the from..import syntax.

# Filename:

from mymodule import sayhi, version
# Alternative:
# from mymodule import *

print 'Version', version

The output of is same as the output of