Python 101Free
MODULES AND FILES

Modules and Imports

Break code into multiple files and reuse what others have written.

SECTION 01

What is a module

As a project grows, keeping every function and class in a single file becomes unworkable; modules let you split code across files. When you import one, Python runs the file once and exposes its top-level names through a namespace you can refer to by the module's name.

This is the basic mechanism for splitting code across files. Define utility functions in math_utils.py, write import math_utils from another file, and call math_utils.add(2, 3). The names from the imported file are reachable through the module name without polluting the caller's namespace.

A folder containing an __init__.py file is a package, which is a module that contains other modules. The mechanics are the same; packages just give you a tree.

2 more sections

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in