O'Reilly logo

Data Structures and Algorithms Using Python by Rance D. Necaise

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

Appendix B. User-Defined Modules

As you learned earlier, Python includes a standard library containing modules of functions and class definitions that can be used in our programs. By using modules, the language itself can remain relatively small while still providing extended functionality.

Structured Programs

Python programs can quickly become very large and unmanageable, especially if the entire user code is placed within a single source able. To help structure and manage large programs, Python allows the user to create their own modules. A module, which is a text file that contains Python source code and has a .py extension, can be used to group class definitions and related functions.

Typically, a large program consists of a top-level source file and one or more supplemental modules. The top-level file acts as the driver, which contains the statements for the main flow of execution, and the modules contain related components, which act as tools that are imported and used as needed.

The code segment below illustrates the use of modules in organizing a structured program. It consists of three Python source files: a top-level driver (grades.py), and two supplemental modules (iomod.py, and compmod.py). (Note, this is a small simple program used for illustration purposes. In practice, a short program like this would more likely be placed in a single module.)

# grades.py  ---------------------------------------------------------------------------------
# The driver module which contains ...

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