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
The first step is to examine what modules really are and how they work.
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, ...