When the same functionality belongs in several programs, place it in a Python module instead of repeating its implementation. A module lets code be reused, tested, maintained, and understood at a higher level. section 8.0
A module is a single file with a .py suffix. It can define data structures, functions, classes, or other Python objects, which importing programs access through the module’s namespace. section 8.10 section 8.2
Common import forms select how names become available:
- from os import * imports names selected by the module’s export behavior; __all__ can restrict that selection. section 8.10
A reusable sales-tax module
A module can hide a policy calculation behind a small function interface. In freedonia.py, RATES stores province data, time_percentage converts an hour to a fraction of 24, and calculate_tax combines those values. Another program can then write: from freedonia import calculate_tax; calculate_tax(100, 'Harpo', 12). Serious monetary calculations should use integers or Decimal rather than floats. section 8.2
Importing executes a module’s file from beginning to end. The __name__ value distinguishes direct execution, where it is __main__, from importing, where it is the module’s name; if __name__ == '__main__': therefore keeps test or demonstration code from running during import. section 8.7
A package groups one or more modules in a directory, allowing related files to be distributed and addressed through names such as mypackage.first. Packages can also be built and published with Poetry and PyPI. section 8.10
Practice modules by:
- Writing a menu module that maps user choices to callable functions and returns the selected result. section 8.6
- Adding direct-execution tests to an importable module with the __main__ guard. section 8.10 section 8.7
- Turning the module into a package and publishing it to PyPI. section 8.10
Table 8.1 What you need to know (view table figure)
| Re-imports an already loaded module, typically to update definitions during development |
|||
Use the reference table to compare import syntax, module reloading, package installation, and Decimal-based numeric handling. section 8.0


































