Extract functions with clear dependencies
Move a cohesive calculation into a function that accepts the data it needs rather than reading module globals. Preserve defaults and error behavior until a separate change is approved. Avoid adding classes solely to shorten a function; a small named function can be a sufficient and clearer boundary.
Illustrative scenario: a report command reads files, calculates totals, and sends email in one function. Extract total calculation first, using fixed input rows in tests. Leave file and email orchestration unchanged during that step so failures can be attributed to a narrow structural transformation.
Check laziness, mutation, and lifetime
Replacing a list with a generator changes when work occurs and whether results can be iterated repeatedly. Inspect the callers before making that change. Likewise, replacing an in-place list update with a new object can alter shared state even when printed values look identical in a small example.
Use context managers where the function owns the resource and should close it at the block boundary. A refactor should not accidentally close a stream supplied by a caller that still needs it. Test failure paths and repeated calls when mutable state or resource cleanup is involved.
Keep imports and tests representative
Moving functions between modules can expose circular imports or change import-time side effects. Keep application startup and configuration loading in explicit entry points when possible. Run the real package entry path as well as isolated function tests so an apparently safe extraction does not leave the application unable to start.
Use fixtures that isolate filesystem, environment, and shared state between tests. Assert observable outcomes rather than every helper call, unless call sequencing is itself the contract. Record any intentional exception or API change separately; a green test suite cannot explain behavior that the tests never exercised.
Working sheet
| Change | Contract to inspect | Practical test |
|---|---|---|
| List to generator | Timing and repeat iteration | Consume twice and test failure timing |
| Extract function | Defaults and exception behavior | Boundary inputs and repeated calls |
| Context manager | Resource ownership and closure | Caller-owned and failing-resource cases |
| Move module | Import order and side effects | Package startup and isolated imports |
Example to adapt
Illustrative example. Run it against your own fixtures and supported tool versions.
# Illustrative extraction: preserve eager list construction and sum order.
# Before
def total_before(rows):
amounts = [row["amount"] for row in rows]
return sum(amounts)
# After
def row_amounts(rows):
return [row["amount"] for row in rows]
def total_after(rows):
return sum(row_amounts(rows))
# Verify empty input, mixed amounts, and the existing missing-key exception.Questions about refactor Python while preserving observable behavior
Should I replace every loop with a comprehension?
Use comprehensions for clear transformations. Keep explicit loops when branching, side effects, or error handling become harder to read.
What should Python refactoring tests assert?
Prioritize returned values, state changes, exceptions, and external effects that callers rely on. Avoid coupling tests to incidental helper structure.
How should I use the working sheet?
Download the CSV and replace the sample rows with evidence from your repository. Record a clear acceptance check and an owner for each item. Keep unresolved assumptions visible rather than treating the example as a completed assessment.
Sources and further reading
Examples are illustrative. They are not customer results, security guarantees, or a substitute for checking the documentation for your installed version.
