Python ยท Chapter 24 of 45

Python Modules

A module is any Python file (`.py`) that can be imported. Use `import module` or `from module import name` to reuse code.

Python ships with a huge STANDARD LIBRARY: `math`, `random`, `os`, `sys`, `datetime`, `json`, `re` and many more.

Import styles

`import math` โ€” use as `math.sqrt(9)`. `from math import sqrt` โ€” use as `sqrt(9)`. `import math as m` โ€” alias.

Your own modules

Create `helpers.py` in the same folder and `import helpers` to use its functions.

Example 1 (python)
import math
print(math.sqrt(16))
print(math.pi)
Output
4.0
3.141592653589793

Use math module for advanced numeric functions.

Example 2 (python)
from random import choice
print(choice(["red", "green", "blue"]))
Output
green

Import a single function directly.

Key points

  • A module is a `.py` file.
  • Import styles: `import x`, `from x import y`, `import x as z`.
  • Python has a rich standard library.
  • Avoid `from module import *` โ€” it pollutes the namespace.
๐Ÿ’ก Note: Circular imports (A imports B imports A) are a common bug. Restructure your modules to break the cycle.

๐Ÿ“ Quick Quiz

1. How do you import the math module?

2. `from x import *` is:

3. A Python module is: