Chapter 1. Introducing Modular Programming

Modular programming is an essential tool for the modern developer. Gone are the days when you could just throw something together and hope that it works. To build robust systems that last, you need to understand how to organize your programs so that they can grow and evolve over time. Spaghetti coding is not an option. Modular programming techniques, and in particular the use of Python modules and packages, will give you the tools you need to succeed as a professional in the fast changing programming landscape.

In this chapter, we will:

  • Look at the fundamental aspects of modular programming
  • See how Python modules and packages can be used to organize your code
  • Discover what happens when modular programming techniques are not used
  • Learn how modular programming helps you stay on top of the development process
  • Take a look at the Python standard library as an example of modular programming
  • Create a simple program, built using modular techniques, to see how it works in practice

Let's get started by learning about modules and how they work.

Introducing Python modules

For most beginner programmers, their first Python program is some version of the famous Hello World program. This program would look something like this:

print("Hello World!")

This one-line program would be saved in a file on disk, typically named something like hello.py, and it would be executed by typing the following command into a terminal or command-line window:

python hello.py

The Python interpreter would then dutifully print out the message you have asked it to:

Hello World!

This hello.py file is called a Python source file. When you are first starting out, putting all your program code into a single source file is a great way of organizing your program. You can define functions and classes, and put instructions at the bottom which start your program when you run it using the Python interpreter. Storing your program code inside a Python source file saves you from having to retype it each time you want to tell the Python interpreter what to do.

As your programs get more complicated, however, you'll find that it becomes harder and harder to keep track of all the various functions and classes that you define. You'll forget where you put a particular piece of code and find it increasingly difficult to remember how all the various pieces fit together.

Modular programming is a way of organizing programs as they become more complicated. You can create a Python module, a source file that contains Python source code to do something useful, and then import this module into your program so that you can use it. For example, your program might need to keep track of various statistics about events that take place while the program is running. At the end, you might want to know how many events of each type have occurred. To achieve this, you might create a Python source file named stats.py which contains the following Python code:

def init():
    global _stats
    _stats = {}

def event_occurred(event):
    global _stats
    try:
        _stats[event] = _stats[event] + 1
    except KeyError:
        _stats[event] = 1

def get_stats():
    global _stats
    return sorted(_stats.items())

The stats.py Python source file defines a module named stats—as you can see, the name of the module is simply the name of the source file without the .py suffix. Your main program can make use of this module by importing it and then calling the various functions that you have defined as they are needed. The following frivolous example shows how you might use the stats module to collect and display statistics about events:

import stats

stats.init()
stats.event_occurred("meal_eaten")
stats.event_occurred("snack_eaten")
stats.event_occurred("meal_eaten")
stats.event_occurred("snack_eaten")
stats.event_occurred("meal_eaten")
stats.event_occurred("diet_started")
stats.event_occurred("meal_eaten")
stats.event_occurred("meal_eaten")
stats.event_occurred("meal_eaten")
stats.event_occurred("diet_abandoned")
stats.event_occurred("snack_eaten")

for event,num_times in stats.get_stats():
    print("{} occurred {} times".format(event, num_times))

We're not interested in recording meals and snacks, of course—this is just an example—but the important thing to notice here is how the stats module gets imported, and then how the various functions you defined within the stats.py file get used. For example, consider the following line of code:

stats.event_occurred("snack_eaten")

Because the event_occurred() function is defined within the stats module, you need to include the name of the module whenever you refer to this function.

Note

There are ways in which you can import modules so you don't need to include the name of the module each time. We'll take a look at this in Chapter 3, Using Modules and Packages, when we look at namespaces and how the import command works in more detail.

As you can see, the import statement is used to load a module, and any time you see the module name followed by a period, you can tell that the program is referring to something (for example, a function or class) that is defined within that module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.67.70