This is part of an ongoing series on learning the Python programming language. If you haven't read them yet, I advise you to catch up on parts one, two, three, four, five and six before reading this article.

In this tutorial, we'll deal with modules. A module is a collection of objects, like functions, classes and even other modules. In Python a module is simply a file with a .py extension. This allows you to reuse those objects by including the module file with your program.

Python has a huge library of built-in modules. Whenever you use Python these modules are available to your program. To use modules or objects within modules in your program you need to import them using the import statement.

Using Standard Python Modules

Let's try to use one of the built-in modules, the sys module. The sys module in Python contains a collection of system-related objects that you can use to determine some settings which most operating systems have.

import sys
print 'The name of this program is', sys.argv[0]

As you can see, in order to use the module it had to be imported. Once it was imported the argv object within the module was used in the print statement. The argv object is a list of the command line arguments which is set up by Python. The first item (item 0 - we'll deal with lists in a later tutorial) in the list is always your program name.

$ python
The name of this program is

Some modules are huge, and at times one might want to import a single object from a module rather than the entire module. For that you can use the "from" syntax in your import statement like so:

from sys import argv
print 'The name of this program is', argv[0]

Since we only imported the argv object, we don't need to refer to it via the module name.

Creating Your Own Modules

Creating your own modules is not difficult; as previously explained, a module is simply a Python file. In the same directory on your computer as your Python programs, add a file called, "" and put the following function in it.

def say_hello():
    return 'Hello world'

Then in your program, let's call it type in the following:

from sayings import say_hello
print say_hello()

Run your program and your output should simply be:

Hello world

And there you have your first module.


Setting up submodules is slightly different to simply creating a new Python file. A true submodule is a Python file inside a directory which has been turned into a module.

Turning a directory into a module is actually fairly simple. Create a directory with the name of your module, and then add a file named inside your directory. This specially named file converts your directory into a module and is where you can place any module-level functions and objects.

To actually create a submodule do what you did before and drop a Python file into your module directory and it automatically becomes a submodule. You can import it via the dotted notation:

import module.submodule

Or just the submodule:

from module import submodule

Or a single object from within the submodule:

from module.submodule import myfunc

Specifying Wildcard Import Module Objects

Sometimes when you are using many objects from a module you don't want to have to specify them individually in your import statement. One way to get around this is to use the wildcard import. This is a very dangerous way to import objects, but may be required if you are importing a large number of objects from your own module.

To limit the potential damage of the wildcard import you make use of the special _all__ module level attribute. This gives you the ability to specify which objects should be imported. For example:

def greet(name):
    return 'Hello ' + name

def hello_world():
    return greet('world')

__all__ = ['hello_world']

In your program:

from mymodule import *
print locals()

You should see the hello_world function but not the greet function.

Using The dir() Function

Python has a special function for inspecting the contents of modules. The dir function returns a list of objects from within the specified module.

>>> import sys
>>> print dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']

This function is very useful when working with 3rd party modules where there isn't necessarily any good documentation. The dir function can be used on classes, functions and other Python objects.

Modules are a great way to store a set of functions you often use, and you'll find that most 3rd party Python libraries started out as a module of common functions for someone.

Don't understand? Got a question? Use the comments section below.

Update: Part 8


comments powered by Disqus