Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python

Chapter 5. Modules

This chapter presents the Python module—the highest-level program organization unit, which packages program code and data for reuse. In concrete terms, modules take the form of Python program files (and C extensions); clients import modules to use the names they define. Modules are processed with two new statements and one important built-in function we explore here:

import

Lets a client fetch a module as a whole

from

Allows clients to fetch particular names from a module

reload

Provides a way to reload a module’s code without stopping Python

We introduced module basics in Chapter 1, and you may have been using module files in the exercises, so some of this chapter may be a review. But we also flesh out module details we’ve omitted so far: reloads, module compilation semantics, and so on. Because modules and classes are really just glorified namespaces, we explore namespace basics here as well, so be sure to read most of this chapter before tackling the next.

Why Use Modules?

Let’s start with the obvious first question: why should we care about modules? The short answer is that they provide an easy way to organize components into a system. But from an abstract perspective, modules have at least three roles:

Code reuse

As we saw in Chapter 1, modules let us save code in files permanently.[34] Unlike code you type at the Python interactive prompt (which goes away when you exit Python), code in module files is persistent—it can be reloaded and rerun as many times as ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata