SyntaxStudy
Sign Up
Python Intermediate 4 min read

TDD in Python

Test-Driven Development

Write a failing test, write minimal code to pass it, then refactor. Each cycle is Red → Green → Refactor.

Example
# 1. Red — write failing test
def test_is_valid_email():
    assert is_valid_email("user@example.com") is True
    assert is_valid_email("notanemail") is False

# 2. Green — simplest passing implementation
import re
def is_valid_email(email: str) -> bool:
    return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))

# 3. Refactor — improve pattern, add edge cases
# Run pytest after each change
Pro Tip

TDD keeps functions small and focused — if it is hard to test, the design probably needs improvement.