Chapter 6. Modules

A typical Python program is made up of several source files. Each source file is a module, grouping code and data for reuse. Modules are normally independent of each other, so that other programs can reuse the specific modules they need. Sometimes, to manage complexity, you group together related modules into a package—a hierarchical, tree-like structure.

A module explicitly establishes dependencies upon other modules by using import or from statements. In some programming languages, global variables provide a hidden conduit for coupling between modules. In Python, global variables are not global to all modules, but rather are attributes of a single module object. Thus, Python modules always communicate in explicit and maintainable ways.

Python also supports extension modules—modules coded in other languages such as C, C++, Java, or C#—for use in Python. For the Python code importing a module, it does not matter whether the module is pure Python or an extension. You can always start by coding a module in Python. Later, should you need more speed, you refactor and recode some parts of modules in lower-level languages, without changing the client code that uses those modules. Chapter 24 shows how to write extensions in C and Cython.

This chapter discusses module creation and loading. It also covers grouping modules into packages, and using Python’s distribution utilities (distutils and setuptools) to install distributed packages, and to prepare packages for distribution; ...

Get Python in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.