Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Modular Programming with Python

You're reading from   Modular Programming with Python Introducing modular techniques for building sophisticated programs using Python

Arrow left icon
Product type Paperback
Published in May 2016
Publisher Packt
ISBN-13 9781785884481
Length 246 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Erik Westra Erik Westra
Author Profile Icon Erik Westra
Erik Westra
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Introducing Modular Programming 2. Writing Your First Modular Program FREE CHAPTER 3. Using Modules and Packages 4. Using Modules for Real-World Programming 5. Working with Module Patterns 6. Creating Reusable Modules 7. Advanced Module Techniques 8. Testing and Deploying Modules 9. Modular Programming as a Foundation for Good Programming Technique Index

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime