CHAPTER 7

Namespaces

7.1 Encapsulation in Functions

7.2 Global versus Local Namespaces

7.3 Exceptional Control Flow

7.4 Modules as Namespaces

7.5 Classes as Namespaces

Chapter Summary

Solutions to Practice Problems

Exercises

Problems

THIS CHAPTER presents namespaces as a fundamental construct for managing program complexity. As computer programs increase in complexity, it becomes necessary to adopt a modular approach and develop them using several smaller components that are developed, tested, and debugged individually. These components—whether they are functions, modules, or classes—must work together as a program but they also should not interfere, in unintended ways, with each other.

Modularity and “noninterference” (usually called encapsulation) are made possible thanks to the fact that each component has its own namespace. Namespaces organize the naming scheme in functions, modules, and classes so that names defined inside a component are not visible to other components. Namespaces play a key role in the execution of function calls and the normal control flow of a program. We contrast this with the exceptional control flow that is caused by a raised exception. We introduce exception handling as a way to control this control flow.

This chapter covers concepts and techniques that fundamentally deal with program design. We apply them in Chapter 8 to create new classes and in Chapter 10 to understand how recursive functions execute.

7.1 Encapsulation in Functions

In Chapter 3 ...

Get Introduction to Computing Using Python: An Application Development Focus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.