O'Reilly logo

Beginning Python®: Using Python 2.6 and Python 3.1 by James Payne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 10. Building a Module

As you saw in Chapter 7, modules provide a convenient way to share Python code between applications. A module is a very simple construct, and in Python, a module is merely a file of Python statements. The module might define functions and classes, and it can contain simple executable code that's not inside a function or class. And, best yet, a module might contain documentation about how to use the code in the module.

Python comes with a library of hundreds of modules that you can call in your scripts. You can also create your own modules to share code among your scripts. This chapter shows you how to create a module, step by step. This includes the following:

  • Exploring the internals of modules

  • Creating a module that contains only functions

  • Defining classes in a module

  • Extending classes with subclasses

  • Defining exceptions to report error conditions

  • Documenting your modules

  • Testing your modules

  • Running modules as programs

  • Installing modules

The first step is to examine what modules really are and how they work.

Exploring Modules

A module is just a Python source file. The module can contain variables, classes, functions, and any other element available in your Python scripts.

You can get a better understanding of modules by using the dir function. Pass the name of some Python element, such as a module, and dir will tell you all of the attributes of that element. For example, to see the attributes of __builtins__, which contain built-in functions, classes, and variables, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required