Manuals / Python / Ch 4

B · StructureBeginner45 min read

4. Functions, modules & packages

Python · 52 pages source format

def, return, default args, type hints lite, import, project layout with src/ and tests/.

What you'll learn

  • Functions and returns
  • Default arguments
  • Modules and imports
  • Type hints lite

Write functions

Pure functions first — same input, same output, no side effects. Easier to test.

def is_valid_email(s: str) -> bool:
    return "@" in s and "." in s.split("@")[-1]

Do this now

Write is_valid_email(s), normalize_phone(s), build_url(base, path).

Clear?

Modules and imports

One file = one module. from helpers import foo or import helpers. Avoid circular imports.

Do this now

Split helpers into src/helpers.py. Import from src/main.py.

Clear?

Project layout

src/ for code, tests/ for pytest, requirements.txt at root. Standard layout employers recognize.

py-journey/
  src/
    helpers.py
    main.py
  tests/
    test_helpers.py
  requirements.txt

Do this now

Restructure py-journey: src/, tests/, move helpers.

Clear?

Checklist