Lesson 136 min read

Modules & Imports

Stand on the shoulders of giants — use code other people already wrote

What Are Modules?

A module is just a Python file that contains code you can reuse. Think of it like a toolbox. Instead of building a hammer from scratch every time, you just grab one from the toolbox. Python comes with a huge toolbox of built-in modules (the standard library), and you can install even more from the internet.

There are three kinds of modules:

  • Built-in modules — Come with Python: math, random, os, json, etc.
  • Third-party modules — Installed with pip: requests, flask, numpy, etc.
  • Your own modules — Any .py file you write can be imported by other files.

Import Styles

# Style 1: Import the whole module
import math
print(math.sqrt(144)) # Must use 'math.' prefix
print(math.pi)
# Style 2: Import specific things
from random import randint, choice
print(randint(1, 100)) # No prefix needed
print(choice(["rock", "paper", "scissors"]))
# Style 3: Import with an alias
import datetime as dt
now = dt.datetime.now()
print(f"Today: {now.strftime('%Y-%m-%d')}")
# Style 4: Import everything (usually avoid this!)
# from math import * # Pollutes your namespace
Output
12.0
3.141592653589793
42
rock
Today: 2026-03-08

Useful Standard Library Modules

Python's standard library is famously described as "batteries included." Here are some you'll use constantly:

  • math — Math functions: sqrt, ceil, floor, log, constants like pi
  • random — Random numbers: randint, choice, shuffle, sample
  • os — Operating system: file paths, environment variables, directories
  • json — Read and write JSON data
  • datetime — Dates and times
  • collections — Fancy containers: Counter, defaultdict, deque
  • pathlib — Modern file path handling

Standard Library Highlights

# collections.Counter — count things instantly
from collections import Counter
word = "mississippi"
letter_freq = Counter(word)
print(f"Letter frequencies: {letter_freq}")
print(f"Most common: {letter_freq.most_common(2)}")
# json — convert between Python dicts and JSON strings
import json
player = {"name": "Link", "health": 100, "items": ["sword", "shield"]}
json_string = json.dumps(player, indent=2)
print(f"\nJSON:\n{json_string}")
# Parse it back
parsed = json.loads(json_string)
print(f"\nParsed name: {parsed['name']}")
# pathlib — modern file paths
from pathlib import Path
home = Path.home()
print(f"\nHome directory: {home}")
print(f"Desktop exists: {(home / 'Desktop').exists()}")
Output
Letter frequencies: Counter({'s': 4, 'i': 4, 'p': 2, 'm': 1})
Most common: [('s', 4), ('i', 4)]

JSON:
{
  "name": "Link",
  "health": 100,
  "items": [
    "sword",
    "shield"
  ]
}

Parsed name: Link

Home directory: /Users/arman
Desktop exists: True

The __name__ Guard & pip

When you run a Python file directly, Python sets a special variable __name__ to "__main__". When the file is imported as a module, __name__ is set to the module's name instead. This lets you write code that only runs when the file is executed directly — not when it's imported.

To install third-party packages, use pip — Python's package installer:

  • pip install requests — Install a package
  • pip install -r requirements.txt — Install from a file
  • pip list — See what's installed
  • pip uninstall requests — Remove a package

The __name__ Guard

# Imagine this is in a file called 'calculator.py'
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# This block only runs when you execute THIS file directly
# It WON'T run when someone does: import calculator
if __name__ == "__main__":
# Test our functions
print(f"add(2, 3) = {add(2, 3)}")
print(f"multiply(4, 5) = {multiply(4, 5)}")
print("All tests passed!")
# What __name__ actually is:
print(f"\n__name__ = {__name__}")
Output
add(2, 3) = 5
multiply(4, 5) = 20
All tests passed!

__name__ = __main__
Note: Always use from module import specific_thing when you only need a few items. Importing everything with from math import * is like dumping the entire toolbox on the floor — you can't tell where anything came from, and names might clash.

Quick check

What does import math as m do?
Classes & OOPLambda, Map & Filter