PYTHON / CHAPTER 16

Modules and tests that challenge a contract

Intermediate

Make reusable code importable and choose tests that expose defects.

By the end of this chapter

  • Separate entry-point effects from definitions
  • Test boundaries and input preservation
  • Use precise exception assertions

The idea

A Python module executes its top-level statements when first imported in an interpreter. Put demonstration or command-line behavior behind if __name__ == "__main__" so another module can reuse the functions without launching that behavior. Importing still executes definitions and other unguarded statements; the guard does not make the whole module lazy.

A useful test distinguishes correct code from a plausible defect. Include empty input, exact threshold values, repeated values, and checks that promised input preservation actually holds. For a function expected to reject malformed data, assert the specific exception instead of accepting any failure. Tests document selected behavior; a passing suite is evidence about those cases, not proof that every possible input is correct.

Python example
def above(values, limit):
    return [n for n in values if n > limit]

if __name__ == "__main__":
    source = [2, 3, 3]
    assert above(source, 3) == []
    assert source == [2, 3, 3]
    print("checks passed")
Result
checks passed

The exact-boundary test detects an accidental >=, and the second assertion verifies input preservation.

Try it yourself

Write tests for a first-match function that returns None on absence and preserves the input.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open Python coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which test detects changing n > limit to n >= limit most directly?