Python Master Course V2 — 109. Pythonic Design and Refactoring
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 11 · LESSON 109 OF 200
Pythonic Design and Refactoring
Study: 90–120 minutes · Prerequisites: Lessons 101–102, functions, classes, exceptions and tests.
Video lesson
Video not yet available. A verified video URL/player will be added when supplied.
Learning outcomes
Explain pythonic design and refactoring, reason about runtime behavior, apply the technique in a maintainable program, and test normal, boundary and invalid inputs.
Understand and apply: Pythonic Design and Refactoring
Readable Python uses explicit names, direct iteration, unpacking, enumerate, context managers, and small functions. Refactoring preserves behavior while improving structure.
Preserve an observable contract while changing structure
Refactoring improves organization without intentionally changing externally observable behavior. Before editing, identify the contract: accepted inputs, output text, order, return values, exceptions and side effects. Characterization tests capture what an existing script actually does, including boundary cases. They give you a baseline when the original implementation is awkward but its users depend on its behavior.
For this worked report, input is an already-validated list of dictionaries containing name, score and active. Eligible rows are active and have a score of at least seventy. Preserve source order, number only eligible rows starting at one, trim surrounding name whitespace, separate lines with newline characters and return an empty string when no row qualifies. This focused contract avoids quietly mixing a refactor with a new validation policy.
Python example: starter, refactor and characterization tests
def legacy_report(rows):
result = ""
number = 1
for index in range(len(rows)):
row = rows[index]
if row["active"]:
if row["score"] >= 70:
if result != "":
result = result + "\n"
result = result + str(number) + ". "
result = result + row["name"].strip()
result = result + ": " + str(row["score"])
number = number + 1
return result
def eligible(row):
return row["active"] and row["score"] >= 70
def render_line(number, row):
return f"{number}. {row['name'].strip()}: {row['score']}"
def report(rows):
selected = (row for row in rows if eligible(row))
return "\n".join(render_line(number, row)
for number, row in enumerate(selected, start=1))
sample = [
{"name": " Asha ", "score": 90, "active": True},
{"name": "Ravi", "score": 69, "active": True},
{"name": "Mei", "score": 70, "active": True},
]
print(report(sample))
from copy import deepcopy
cases = [
[],
[{"name": "Hidden", "score": 99, "active": False}],
[{"name": "Low", "score": 69, "active": True}],
[{"name": " Edge ", "score": 70, "active": True}],
sample,
]
expected = ["", "", "", "1. Edge: 70", "1. Asha: 90\n2. Mei: 70"]
for rows, text in zip(cases, expected):
snapshot = deepcopy(rows)
assert legacy_report(rows) == text
assert report(rows) == text
assert rows == snapshot
print("5 characterization cases passed")
Expected output
1. Asha: 90
2. Mei: 70
5 characterization cases passed
The first change replaces manual index lookup with direct row iteration. A named predicate exposes the eligibility rule. Filtering before enumerate keeps ranks consecutive among selected rows. render_line owns presentation of one line, while join owns separators and naturally handles the empty case. No sorting, new rounding or capitalization was introduced, because each would change the report contract.
Test the seams and the complete output
The five cases in the runnable example cover empty input, an inactive high scorer, a score immediately below the boundary, the exact seventy boundary and the mixed sample. Both implementations are checked against independent expected strings, and a deepcopy snapshot checks that input records remain unchanged.
Comparing both implementations against explicit expected strings is stronger than comparing them only with each other: two versions can share the same mistake. The snapshot also checks an important side effect boundary, namely that report generation leaves its inputs unchanged. Exact output comparisons catch an accidental trailing newline or a skipped rank that a loose substring assertion might miss.
Make one small structural change at a time and rerun the relevant tests. Keep input reading and output writing at the outer boundary so the report can be tested without files or a terminal. If the real script has malformed-input behavior that callers rely on, add characterization cases for those errors before modifying its validation.
Pythonic code favors direct iteration, useful names, unpacking and standard operations when they reveal intent. A dense nested comprehension or a class hierarchy for three simple functions can make this report harder to understand. Extract a helper when it names a meaningful rule or enables focused testing; splitting every expression into another function adds navigation without clarity. Any new sorting, error policy or output feature belongs in a separate, explicitly tested behavior change.
Progressive runnable examples
Requires Python 3.10+. Save as lesson109.py and run python lesson109.py or python3 lesson109.py. Expected outputs below are illustrative and not claimed to have been executed on Smartyfy.
Example 1 — Core mechanism
records = [('Asha', 90), ('Ravi', 85)]
for index, (name, score) in enumerate(records, start=1):
print(index, name, score)
Expected output:
1 Asha 90
2 Ravi 85
Guided practical project
Project: Refactor the supplied legacy_report starter in small steps, preserve its observable behavior, and run all five characterization cases.
Use the complete implementation and explicit contract in the worked explanation above. Reproduce its deterministic sample, test the stated boundary and failure cases, and explain the documented limitations before adapting it.
Common mistakes and debugging
- Adding abstraction without a demonstrated need.
- Hiding state or unexpected side effects.
- Assuming type hints replace validation.
- Ignoring resource cleanup or error propagation.
- Measuring performance on unrepresentative data.
- Failing to test boundary and error cases.
Debug by reproducing the smallest failing input, inspecting the traceback and intermediate values, then adding a regression test.
Practice with explained answers
Predict each result before opening the answer. Explain how the design handles both ordinary and boundary cases.
Why are numbers assigned after filtering?
The contract numbers only eligible rows. Enumerating the raw rows first would preserve original positions and could produce ranks one and three in the sample, changing the report even though the selected names were correct.
Why compare with explicit expected strings instead of only old == new?
Both implementations could share a defect. An independently written expected result verifies the intended example behavior as well as compatibility. Exact strings also expose whitespace and separator changes.
Is adding alphabetical sorting part of this refactor?
No. The contract preserves source order. Sorting is an observable behavior change and should be proposed and tested separately, even if the new order seems more attractive.
Why test scores sixty-nine and seventy?
They lie immediately below and exactly on the inclusive eligibility boundary. Together they reveal an accidental > instead of >= or an off-by-one threshold change.
What does the deepcopy snapshot check?
It checks that neither report function changes the input records, including nested structures if later added. This is separate from output equality: a function could return the right text while also mutating caller-owned data.
Should a refactor silently replace missing-key errors with empty defaults?
No. That changes invalid-input behavior and may hide corrupt records. First characterize the current behavior, then introduce any new validation or fallback policy as a deliberate change with its own tests.
Mastery checkpoint
Explain the concept without notes, reproduce the core example, finish the project, run three tests and justify when the technique is appropriate. No account-synced completion or certification is claimed.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.