check-python-snippets.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. """Check Python 3.11 syntax in lesson snippets without executing services."""
  2. import ast
  3. import json
  4. from pathlib import Path
  5. root = Path(__file__).resolve().parents[1]
  6. files = [root / "app/lessons.json", *sorted((root / "public/content").glob("*.json"))]
  7. checked = 0
  8. errors = []
  9. for path in files:
  10. lessons = json.loads(path.read_text(encoding="utf-8-sig"))
  11. for lesson in lessons:
  12. if lesson.get("kind") == "review":
  13. assert "steps" not in lesson, "Review units must not contain executable steps"
  14. continue
  15. for index, step in enumerate(lesson["steps"], 1):
  16. if step.get("lang") not in {"python", "py"} or not step.get("code"):
  17. continue
  18. label = f"{path.stem}/{lesson['id']}/step-{index}"
  19. try:
  20. ast.parse(step["code"], filename=label, feature_version=(3, 11))
  21. checked += 1
  22. except SyntaxError as exc:
  23. errors.append(f"{label}: line {exc.lineno}: {exc.msg}")
  24. if errors:
  25. raise SystemExit("\n".join(errors))
  26. print(f"Python 3.11 AST: {checked} snippets passed across {len(files)} modules.")
  27. print("Syntax only; dependencies, SQL, external services and failure drills are not executed.")