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

Python-specific checks before merging
ChangeContract to inspectPractical test
List to generatorTiming and repeat iterationConsume twice and test failure timing
Extract functionDefaults and exception behaviorBoundary inputs and repeated calls
Context managerResource ownership and closureCaller-owned and failing-resource cases
Move moduleImport order and side effectsPackage startup and isolated imports
Download this worksheet (CSV)

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.

Make the next change verifiable.

Getzilla is an open source workflow for changes to existing repositories. Inspect the project, define acceptance checks, and keep independent review in the loop.

See the repository workflow See current access and pricing