Skip to Content
Learning Python, 3rd Edition
book

Learning Python, 3rd Edition

by Mark Lutz
October 2007
Beginner
752 pages
19h 44m
English
O'Reilly Media, Inc.
Content preview from Learning Python, 3rd Edition

Chapter 20. Module Packages

So far, when we’ve imported modules, we’ve been loading files. This represents typical module usage, and is probably the technique you’ll use for most imports you’ll code early on in your Python career. However, the module import story is a bit richer than I have thus far implied.

In addition to a module name, an import can name a directory path. A directory of Python code is said to be a package, so such imports are known as package imports. In effect, a package import turns a directory on your computer into another Python namespace, with attributes corresponding to the subdirectories and module files that the directory contains.

This is a somewhat advanced feature, but the hierarchy it provides turns out to be handy for organizing the files in a large system, and tends to simplify module search path settings. As we’ll see, package imports are also sometimes required to resolve import ambiguities when multiple program files of the same name are installed on a single machine.

Package Import Basics

So, how do package imports work? In the place where you have been naming a simple file in your import statements, you can instead list a path of names separated by periods:


import dir1.dir2.mod

The same goes for from statements:


from dir1.dir2.mod import x

The “dotted” ...

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, 6th Edition

Learning Python, 6th Edition

Mark Lutz
Learning Python, 2nd Edition

Learning Python, 2nd Edition

Mark Lutz, David Ascher

Publisher Resources

ISBN: 9780596513986Purchase bookSupplemental ContentErrata Page