Stage 02 · Lesson 09/15

Programming & Python · Lesson 09

Modules, Packages & Environments

Est. 30–40 min

Try it · Python in your browser

Run this lesson's example (imports_demo.py), change a number, run it again.

Why

Why projects need walls between dependencies

By the end you will import stdlib modules, explain why venv exists, and sketch a simple project layout.

Concept

The big idea: import, packages, venv

  • import math / from math import radians.
  • A module is usually a .py file; a package is a folder with modules.
  • python3 -m venv .venv then activate — Stage 3 deepens this.
  • Keep robot apps as small modules: sensors.py, control.py, main.py.

How it works

How it actually works, step by step

  1. Import what you need

    stdlib first (math, json, pathlib).

  2. Split files by role

    sensors / decide / act / main.

  3. Create a venv for the project

    Avoid system-wide pip spaghetti.

  4. Pin a short requirements list later

    When you add third-party libs.

Visual

Visualise it: structured data / layout thinking

Think in compartments — modules hold related functions the way structures hold related fields.

Interactive · Data structure explorer

Ultrasonic ring buffer as a Python list

readings = [12.4,11.9,18.2,9.5,22]
latest = readings[-1]      # 22.0
mid    = readings[2]     # 18.2
min    = 9.5
max    = 22.0
avg    = 14.80
# robotics: rolling window for filters

Code lab

Code lab: imports demo

imports_demo.py · Python
#!/usr/bin/env python3
"""Show stdlib import + a tiny local helper pattern."""
import math
import json

def package_hint():
    return {
        "python": "3.x",
        "tip": "use venv so desk-arm libs do not fight camera-ML libs",
        "pi": round(math.pi, 5),
    }

info = package_hint()
print(json.dumps(info, indent=2))
print("math.radians(90) =", round(math.radians(90), 4))

Expected output

{
  "python": "3.x",
  "tip": "use venv so desk-arm libs do not fight camera-ML libs",
  "pi": 3.14159
}
math.radians(90) = 1.5708

Real world

Where environments save lab days

  • One venv per robot project on a shared lab laptop.
  • ROS workspaces also isolate — mental model transfers.
  • CI installs from requirements into a clean env.

Mistakes

Common mistakes and confusions

Hardware & safety

Hardware lab and safety notes

On a Raspberry Pi robot, a virtual environment keeps your robot libraries separate from the system. Newer Raspberry Pi OS (Bookworm) even blocks system-wide pip install by default — so venv is the normal way.

  • Create: python3 -m venv .venv; activate: source .venv/bin/activate (Windows: .venv\Scripts\activate).
  • Install inside it: pip install numpy pyserial; save with pip freeze > requirements.txt.
  • Folder layout: sensors.py, decide.py, act.py, main.py.
Raspberry Pi 4 Model B, top view
Raspberry Pi 4 — use one venv per robot project.Photo: Laserlicht · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Debugging

Debugging: when it doesn’t work

Symptom → likely cause → fix
SymptomLikely causeFix
error: externally-managed-environmentpip into system Python (PEP 668)Create and activate a venv first
ModuleNotFoundError: No module named 'numpy'Installed in a different environmentActivate the venv, then pip install
ImportError (circular import)A imports B, B imports AMove shared code to a third module
Your file json.py breaks import jsonName shadows the stdlib moduleRename your file
NoteRead the last line of a Python error first — it names the problem — then the line number above it. Change one thing at a time and re-run.

Think

Think about it

Think

Why not install every pip package globally “for convenience”?

Experiment

Try it in the lab: layout sketch

Experiment

Layout sketch

  1. Run imports_demo.py; confirm math.radians(90) ≈ 1.5708.
  2. On paper, draw main.py importing sensors.py and control.py.
  3. Write the three venv commands in your notebook (do not need network here).

Interactive · Data structure explorer

Ultrasonic ring buffer as a Python list

readings = [12.4,11.9,18.2,9.5,22]
latest = readings[-1]      # 22.0
mid    = readings[2]     # 18.2
min    = 9.5
max    = 22.0
avg    = 14.80
# robotics: rolling window for filters

Knowledge check

Check your understanding

Knowledge check

1. import math gives you…

2. venv is for…

3. math.radians(90) ≈

4. A good tiny layout includes…

5. Circular imports are…

Practice quiz

Loading practice quiz…

Coding practice

Loading coding exercises…

Mini assignment

Hands-on assignment

Mini assignment

Env checklist

Write a checklist: venv create/activate, folder layout for a mini robot app, and which stdlib modules you expect to import.

Deliverables

  • checklist.md
  • imports_custom.py using math+json

Do this, step by step

  1. Run imports_demo.py and check math.radians(90) = 1.5708.
  2. Create a venv in your Stage 2 folder and activate it; run which python (or where python).
  3. Split sense_act_story.py into sensors.py and main.py with an import.
  4. Write checklist.md and imports_custom.py that uses math and json.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. Hint 1: After activating, which python points inside .venv/bin/.
  2. Hint 2: In main.py: from sensors import read_distance_cm.
  3. Hint 3: Add if __name__ == "__main__": so importing a file does not run its demo.

Challenges (pick by level)

  • 🟢 Easy: Print sys.version and sys.prefix inside and outside the venv.
  • 🟡 Medium: Make a requirements.txt and recreate the venv from it.
  • 🟠 Hard: Turn your folder into a package with __init__.py and run it with python -m.

Next step

Next, Lesson 10: Files, Data & JSON. Related: shell and packages in Stage 3 — Linux & Dev Environment.

Sources

Self-attested for now — keep artifacts in your lab notebook.

Complete

Today's goal

0 of 1 done today

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in