Skip to Content
Learning Python, 2nd Edition
book

Learning Python, 2nd Edition

by Mark Lutz, David Ascher
December 2003
Beginner
620 pages
17h 3m
English
O'Reilly Media, Inc.
Content preview from Learning Python, 2nd Edition

Chapter 18. Advanced Module Topics

Part V concludes with a collection of more advanced module-related topics, along with the standard set of gotchas and exercises. Just like funtions, modules are more effective when their interfaces are defined well, so this chapter also takes a brief look at module design concepts. Some of the topics here, such as the __name__ trick, are very widely used, despite the word “advanced” in this chapter’s title.

Data Hiding in Modules

As we’ve seen, Python modules export all names assigned at the top level of their file. There is no notion of declaring which names should and shouldn’t be visible outside the module. In fact, there’s no way to prevent a client from changing names inside a module if they want to.

In Python, data hiding in modules is a convention, not a syntactical constraint. If you want to break a module by trashing its names, you can, but we have yet to meet a programmer who would want to. Some purists object to this liberal attitude towards data hiding and claim that it means Python can’t implement encapsulation. However, encapsulation in Python is more about packaging than about restricting.

Minimizing from* damage: _X and __all__

As a special case, prefixing names with a single underscore (e.g., _X) prevents them from being copied out when a client imports with a from* statement. This really is intended only to minimize namespace pollution; since from* copies out all names, you may get more than you bargained for (including names that ...

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

Learning Python, 5th Edition

Mark Lutz

Publisher Resources

ISBN: 0596002815Supplemental ContentErrata Page