Modules and Packages

Lesson 11 of 20

Split code into files you can reuse: import math and random, then write a module of your own and import it back.

The big picture

One file, many tools

A module is just a .py file — Python lets you pull any file of tools into any other file with a single word: import.

One Job per File

A module is a plain .py file; group related functions and constants in it and import them anywhere.

Batteries Included

math, random, datetime, re — the standard library ships hundreds of ready-made modules.

Dot Access

import math gives you a namespace: math.sqrt, math.pi — no clashes with your own names.

Import Once

A module runs only the first time it is imported; after that Python reuses the cached copy.