Book Image

Modular Programming with Python

By : Erik Westra
Book Image

Modular Programming with Python

By: Erik Westra

Overview of this book

Python has evolved over the years and has become the primary choice of developers in various fields. The purpose of this book is to help readers develop readable, reliable, and maintainable programs in Python. Starting with an introduction to the concept of modules and packages, this book shows how you can use these building blocks to organize a complex program into logical parts and make sure those parts are working correctly together. Using clearly written, real-world examples, this book demonstrates how you can use modular techniques to build better programs. A number of common modular programming patterns are covered, including divide-and-conquer, abstraction, encapsulation, wrappers and extensibility. You will also learn how to test your modules and packages, how to prepare your code for sharing with other people, and how to publish your modules and packages on GitHub and the Python Package Index so that other people can use them. Finally, you will learn how to use modular design techniques to be a more effective programmer.
Table of Contents (16 chapters)
Modular Programming with Python
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Packages within packages


Just like you can have directories within directories, you can have packages within other packages. For example, imagine that our my_package directory contained another directory called my_sub_package, which itself had an __init__.py file:

As you might expect, you import the modules within a sub-package by prepending the names of the packages that contain it:

from my_package.my_sub_package import my_module
my_module.do_something()

There is no limit to how deeply you can nest packages, though in practice it becomes a bit unwieldy if you have too many levels of packages-within-packages. More interestingly, the various packages and sub-packages form a tree-like structure which allows you to organize even the most complex program. For example, a sophisticated business system might be arranged like this:

As you can see, this is called a tree-like structure because the packages-within-packages look like the spreading branches of a tree. A tree-like structure like this allows...