DCubes
Python module

Lesson 15

Scripts, modules, and typing

Import your own code, use if __name__, type hints, and a clean requirements.txt.

beginner35 minRun on your machine

What you will be able to do

  • Split helpers into a module and import them
  • Guard script entry with if __name__ == "__main__"
  • Pin dependencies in requirements.txt

Why this matters for data work

Jobs grow: extract.py, transform.py, shared util.py. Imports and a single entrypoint keep CI and Compose commands short. Type hints document contracts. requirements.txt makes the venv reproducible on the next machine or image.

Concepts

Module — a .py file importable as a name (import retail_util).

if __name__ == "__main__": — code that runs only when the file is the entry script, not on import.

python -m — run a module as a script when package layout exists; for a flat lab file, python file.py is enough.

Type hints — def f(x: int) -> str: — checked by tools later; ignored at runtime unless you add a checker.

Pin versions — package==1.2.3 in requirements for jobs you care about.

Practice on your machine

cd ~/dcubes/python-lab
source .venv/bin/activate
cat > retail_util.py << 'EOF'
def line_total(quantity: int, unit_price: float) -> float:
    return quantity * unit_price


def normalize_sku(raw: str) -> str:
    return raw.strip().upper()
EOF
cat > run_retail.py << 'EOF'
from retail_util import line_total, normalize_sku


def main() -> None:
    sku = normalize_sku(" sku-100 ")
    total = line_total(3, 9.99)
    print(f"{sku} total={total}")


if __name__ == "__main__":
    main()
EOF
python run_retail.py
SKU-100 total=29.97

Write a minimal requirements pin list for packages you actually use in this module (adjust versions to what pip freeze shows):

python -m pip freeze | grep -iE '^(pandas|numpy|httpx|psycopg|rich)==' > requirements-lab.txt
cat requirements-lab.txt

On a fresh venv you would run python -m pip install -r requirements-lab.txt.

What you should see

  • Import works without running extra code when another file imports retail_util.
  • run_retail.py prints one line only when executed directly.
  • A short requirements file with pinned versions.

Common mistakes

  • Circular imports — keep shared utils free of app entry imports.
  • Unpinned pip freeze of the whole universe — freeze what the project needs, or use a compiled lock later.
  • Putting secrets in requirements — never.

Next

Notebooks as files