Search⌘ K
AI Features

Imports and Namespaces

Explore how to organize Python code with modules and imports, understand namespaces to prevent naming conflicts, and manage script versus module execution using __name__. Learn to use Python's built-in standard library effectively for cleaner, more maintainable programs.

We now understand that separating code into multiple files improves organization and reusability. However, dividing code is only part of the solution; those pieces must also be reconnected to form a working program.

Python excels at this through its batteries-included philosophy. It ships with an extensive standard library that provides ready-made modules for tasks such as mathematics, system interaction, date and time handling, and much more. In this lesson, we will learn how to bring these tools into our programs using the import statement.

We will also explore how Python manages namespaces to prevent naming conflicts, and how a file can determine whether it is being executed directly or imported as a module—allowing our code to behave appropriately in both situations.

The import statement and namespaces

A namespace is simply a mapping that connects names to the objects they refer to. When a Python file runs, it has its own namespace where variables, functions, and imported modules are stored.

For example, when we write import math, Python does not pull all of the math functions directly into our file. Instead, it creates a single name, math, in the current namespace that refers to the math module as a whole. That module contains its own functions and values, such as sqrt, sin, and pi.

To use anything inside the module, we must explicitly access it through the name math, using dot notation. This is why we write math.sqrt() instead of just sqrt(). The functions belong to the module, not to our file. ...