Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Antwoorden — Hoofdstuk 9: Modules en virtuele omgevingen

Opmerking: Code is in het Engels, met korte Nederlandse toelichtingen in comments.

Antwoord 1 — Eigen module importeren (temperature)

# temperature.py

def c_to_f(c: float) -> float:
    return (c * 9/5) + 32

def f_to_c(f: float) -> float:
    return (f - 32) * 5/9
# app.py
from temperature import c_to_f, f_to_c

print(c_to_f(20.0))  # 68.0
print(f_to_c(32.0))  # 0.0

Antwoord 2 — import vs from-import

# variant A
import math
print(math.pi)

# variant B
from math import pi
print(pi)
# Comment: with 'import math' you use the qualified name math.pi (clearer where it comes from).
# With 'from math import pi' the name 'pi' is imported directly into your module namespace.

Antwoord 3 — name == "main"

# temperature.py (extended)
import sys

def c_to_f(c: float) -> float:
    return (c * 9/5) + 32

def f_to_c(f: float) -> float:
    return (f - 32) * 5/9

if __name__ == "__main__":
    c = float(sys.argv[1]) if len(sys.argv) > 1 else 0.0
    print(c_to_f(c))

Antwoord 4 — Het importpad bekijken

# show_path.py
import sys
for p in sys.path:
    print(p)
# Comment (NL): De eerste entry is vaak de directory van het actieve script of '',
# wat de current working directory representeert. Startpositie kan verschillen per aanroeplocatie.

Antwoord 5 — Eenvoudig package calc/

# calc/__init__.py
__all__ = ["add", "sub", "mul", "div"]
from .ops import add, sub, mul, div
# calc/ops.py

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mul(a, b):
    return a * b

def div(a, b):
    if b == 0:
        raise ZeroDivisionError("division by zero")
    return a / b
# main.py
from calc.ops import add, div

print(add(2, 3))
print(div(10, 2))

Antwoord 6 — Relatieve import binnen package

# calc/cli.py
from .ops import add

def main() -> None:
    import sys
    if len(sys.argv) >= 3:
        a = float(sys.argv[1]); b = float(sys.argv[2])
    else:
        a, b = 2.0, 3.0
    print(add(a, b))

if __name__ == "__main__":
    main()
# Run as module: python -m calc.cli 4 5

Antwoord 7 — Vermijd star-import

# BAD
# from math import *

# GOOD (explicit)
from math import sqrt, pi
print(sqrt(9), pi)

# or
import math
print(math.sqrt(9), math.pi)
# Comment: '*' vervuilt je namespace en kan namen overschrijven, wat debugging lastiger maakt.

Antwoord 8 — Stdlib mini-taken

import random
from datetime import datetime
from pathlib import Path

print(random.choice(["red", "green", "blue"]))
print(datetime.now().isoformat(timespec="seconds"))
print("notes.txt exists?", (Path("notes.txt").exists()))

Antwoord 9 — pip/venv (conceptueel) en requests

# Commands (run in a shell):
python -m venv .venv
# macOS/Linux
source .venv/bin/activate
# Windows PowerShell
# .venv\Scripts\Activate.ps1
python -m pip install requests
python -m pip freeze > requirements.txt
# fetch.py (run inside an activated venv)
import requests

resp = requests.get("https://httpbin.org/get", timeout=10)
print(resp.status_code)
print(resp.headers.get("Content-Type"))

Antwoord 10 — Naamconflict met stdlib

# random.py (your file) -- DON'T DO THIS NAME

def foo():
    return "bar"
# other_script.py
import random
print(random.choice([1, 2, 3]))  # This will fail or import your local random.py instead of stdlib
# Fix: rename your file to myrandom.py and try again
import random
print(random.choice([1, 2, 3]))  # works, using stdlib random
# Comment (NL): De bestandsnaam 'random.py' overschaduwde de standaardbibliotheekmodule met dezelfde naam.
# Door te hernoemen valt de import weer naar de stdlib.

Uitdaging — greet package met CLI

# greet/__init__.py
__all__ = ["hello"]

def hello(name: str) -> str:
    return f"Hello, {name}!"
# greet/cli.py
from . import hello

def main() -> None:
    import sys
    name = sys.argv[1] if len(sys.argv) > 1 else "world"
    print(hello(name))

if __name__ == "__main__":
    main()
# Usage: python -m greet.cli Ava  (ensure PYTHONPATH includes parent dir or install in venv)