Chapter 8. Module Organization

For anything more than a small program, you will want to organize your code into modules. This is also the unit of organization for reusable libraries—both libraries you create, and outside code you import into your own codebase.

Python’s module system is a delight: easy to use, well designed, and extremely flexible. Making full use requires understanding its mechanisms for imports, and how that works with namespacing. We will dive deep into all of that in this chapter.

In particular, we will focus on how modules evolve. Requirements change over time; as new requirements come in, and as you get more clarity on existing requirements, and how to best organize your codebase. So we will cover the best practices for refactoring and updating module structure during the development process.

This is an important and practical part of working with modules. But for some reason, it is never talked or written about. Until now.

Spawning a Module

To touch on everything important about modules, we will follow the lifecycle of a small Python script that gradually grows in scope and lines of code—eventually growing to a point where we want to package its components​​1 into reusable modules. We do this not just for sensible organization, but also so we can import them into other applications. This evolution from script to spin-off library happens all the time in real software development.

Imagine you create a little Python script, called findpattern.py. Its job ...

Get Powerful Python 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.