Overview

9 Modules and packages

This chapter presents modules and packages as Python’s simple, powerful tools for code reuse and namespacing. By moving shared variables, functions, and classes into modules, you DRY up code across programs, make maintenance easier, and avoid name collisions through separate namespaces. Python’s “batteries included” standard library and the vast ecosystem on PyPI become available via import statements that load code and bind names in your current namespace.

The chapter covers the main import forms and when to use them: import module, import module as alias for brevity, and from module import name to bind specific attributes; star-import is discouraged because it pollutes the global namespace, though leading underscores and an __all__ list influence what’s exported. It demystifies how Python finds and caches modules (sys.path and sys.modules), and shows how importlib.reload aids iterative development. Good module hygiene is emphasized: clear APIs, careful naming to avoid clashes, focused abstractions, accurate numerics where needed (e.g., Decimal for money), and robust error handling with custom exceptions. The ubiquitous if __name__ == '__main__' pattern is explained as a way to run tests or demos without affecting import-time behavior.

Hands-on exercises illustrate these ideas: a freedonia module encapsulates a time-dependent sales-tax policy behind a single calculate_tax function, and a menu module builds a dispatch table from **kwargs to invoke user-selected callables in a loop. The chapter closes by distinguishing modules (single files) from packages (directories of modules, optionally initialized by __init__.py), showing different import styles for packages, and outlining how to make distributable packages and publish them on PyPI with modern tooling and isolated environments. The overarching message is that modules and packages make programs shorter, clearer, and easier to maintain, and that leveraging the standard library and well-chosen third-party packages is central to effective Python.

FAQ

What is a Python module, and why should I use one?A module is a single .py file that groups related variables, functions, and classes so they can be reused across programs. Modules help you DRY up code, improve maintainability and testability, and hide implementation details behind a simple interface.
How do modules provide namespaces and prevent name collisions?Each module (file) has its own global namespace. When you import, you reference its contents via the module name (for example, os.sep), which keeps identifiers from different files from clashing.
How does import find and load a module?- import MODULENAME defines a variable referencing the loaded module object; it’s not a function call.
- Python searches directories listed in sys.path and loads the first matching file (typically .py or a compiled form).
- Already loaded modules are tracked in sys.modules; subsequent imports reuse the existing module object and just bind the name again.
- You can influence search paths via PYTHONPATH or .pth files in site-packages.
What’s the difference between “import X”, “from X import Y”, “import X as A”, and “from X import *”?- import X: Access via X.name; keeps the namespace clear; generally preferred.
- import X as A: Same as above, but with a shorter alias (for example, import numpy as np).
- from X import Y: Binds Y directly in your namespace; convenient but can increase collision risk.
- from X import *: Imports many names into your globals; usually discouraged. Names starting with _ are skipped, and a module’s __all__ (if defined) controls what’s imported. from X import Y is not constrained by __all__.
How can I reload a module during development?Use importlib.reload. Example: import mymod; import importlib; importlib.reload(mymod). This is helpful in interactive sessions while iterating on a module; it’s rarely used in production.
What does “if __name__ == '__main__':” do, and when should I use it?Code under this guard runs only when the file is executed directly, not when it’s imported. Use it to run quick tests, demos, or a command-line interface without executing that code on import.
What’s the difference between a module and a package?- Module: a single .py file.
- Package: a directory containing one or more modules. You can import with from mypackage import first or import mypackage.first. Importing a package name runs its __init__.py, where you can set up exports or import submodules.
Should I use floats for money? How do I use Decimal?Prefer integers or decimal.Decimal for monetary values to avoid floating-point errors. Construct Decimals from strings (Decimal('0.5'), not Decimal(0.5)) for accuracy. Perform calculations with Decimal and convert to float only at the very end if needed.
How should I add error checking to functions in a module?Validate inputs and raise exceptions for invalid data. It’s common to define custom exceptions (classes deriving from Exception) for clearer error reporting (for example, HourTooLowError, HourTooHighError). This prevents silent, nonsensical results and is considered Pythonic.
How do I find, install, and publish packages?- Install: Use pip install packagename from PyPI (https://pypi.org).
- Evaluate: “Awesome Python” (https://www.awesomepython.org/) curates well-maintained packages.
- Publish: Use uv to build and release. Create/configure your project (pyproject.toml), run uv build to create a distribution, and uv publish to upload to PyPI (account required). Virtual environments and Python versions can also be managed with uv.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Python Workout, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Python Workout, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Python Workout, Second Edition ebook for free