β¨ Clean Code & Refactoring
in Python
Write cleaner Python: naming, small functions, guard clauses, DRY, SOLID with before and after refactors, dataclasses, type hints and a worked script refactor.
What this lesson is about
Clean code is code that the next reader can understand quickly, change safely and trust. That next reader is very often you, six months from now, with no memory of why you wrote a line. Python already pushes you towards readability, but the language will happily let you write a 200-line function with names like d and tmp2. Cleanliness is a set of habits, not a feature you switch on.
Refactoring means improving the structure of code without changing what it does. It matters in every real project: requirements change, features pile up, and code that was fine on day one becomes a tangle by month three. Teams that refactor in small, tested steps keep moving; teams that do not end up afraid to touch their own code. Reviewers also notice these habits immediately in pull requests and interviews.
I have organised this lesson as a sequence of small, concrete moves. We start with names, then shrink functions and flatten them with guard clauses, remove duplication, and let dataclasses, type hints and docstrings carry meaning. Then we meet the SOLID principles through before and after refactors, and finish with a complete messy script that I refactor step by step while proving that the output stays identical. Every example runs in your browser, so you can compare the before and after yourself.
What you will learn
- βChoose names that reveal intent and follow PEP 8 conventions
- βSplit long functions into small ones that do one thing
- βFlatten nested
ifblocks with guard clauses and early returns - βRemove duplication (DRY) without creating the wrong abstraction
- βUse dataclasses, type hints and docstrings to document data and contracts
- βApply the SOLID principles with real before and after code
- βRefactor a messy script safely, proving the output did not change
- βKnow when to stop: clean enough beats perfect
Why programmers should learn this
- β Developers read code far more often than they write it, so every minute spent on clarity is repaid many times during debugging and review.
- β Small, well named functions are easy to test, which is why clean code and a good testing habit grow together.
- β Teams judge candidates and pull requests on readability; clear code signals that you can work with other people.
- β Refactoring skills let you inherit an existing codebase and improve it instead of rewriting it from scratch, which is how most professional work actually happens.
- β Clean structure limits the blast radius of a change: when each function and class has one job, fixing one thing does not break five others.
Names that explain themselves
Naming is the cheapest and most powerful refactor. A name is a tiny piece of documentation that travels with every use of the thing it names. d, lst, data2 and process() force the reader to open the function and work out the meaning; days_until_expiry, overdue_invoices and send_reminder_email() carry the meaning with them.
Python has conventions that readers expect: snake_case for variables, functions and modules, PascalCase for classes, UPPER_CASE for constants, and a leading underscore for things that are internal. Functions are usually verbs (load_config), values and classes are nouns (config, Invoice), and booleans read like questions (is_valid, has_items). Avoid single letters except for tiny scopes such as a loop index, and avoid abbreviations that only you understand.
A good test is whether you can read the code aloud as a sentence. Another is whether a comment is compensating for a bad name: if you need # total price after tax next to tp, rename it total_price_after_tax and delete the comment. Names should also be consistent: pick one word per concept, so you do not have fetch_user, get_order and retrieve_item all meaning the same action.
# Before: the reader has to decode everything
def calc(l, r):
t = 0
for i in l:
t += i[0] * i[1]
return t + t * r
print(calc([(10.0, 2), (5.0, 3)], 0.1))38.5
Line by line
- 2
calc,landrsay nothing about what is being calculated or what the parameters mean. - 3-5
taccumulates a total andi[0] * i[1]multiplies two unnamed fields; the reader must guess they are price and quantity. - 6Adds something like a tax of
r, but only careful reading reveals that. - 8The call is impossible to understand without reading the function.
# After: the same logic, but the names do the explaining
def total_with_tax(order_lines, tax_rate):
subtotal = 0
for unit_price, quantity in order_lines:
subtotal += unit_price * quantity
return subtotal + subtotal * tax_rate
print(total_with_tax([(10.0, 2), (5.0, 3)], 0.1))38.5
Line by line
- 2The function name says what it returns and the parameters say what they hold.
- 3-5Tuple unpacking in the
forline gives names to price and quantity, so no index numbers are needed. - 6
subtotal + subtotal * tax_ratenow reads as plain business logic. - 8The call prints the same value as before, 38.5, because only names changed.
Rename with your editor's rename-symbol command rather than find and replace, so that only the right variable is changed.
Small functions and guard clauses
A function should do one thing and do it at one level of abstraction. A good sign that a function is too big is that you need section comments inside it (# validate, # compute, # save). Each of those comments is a function waiting to be extracted. Small functions are easier to name, to test and to reuse, and they let the top-level function read like an outline of the steps.
The second tool is the guard clause: handle the error and edge cases first and return (or raise) immediately, so that the main logic is not buried inside layers of if and else. Deep nesting forces the reader to hold many conditions in their head at once. Flattening it makes the normal path read straight down the page.
Watch out for the opposite mistake. Splitting a function into twenty one-line helpers that are each used once can make code harder to follow, because the reader has to jump around. Extract when the piece has a clear name and a single purpose, not just to hit a line count. Also keep the number of parameters small; if a function needs six arguments that always travel together, they probably belong in a dataclass.
def shipping_cost(order):
if order is not None:
if order["items"]:
if order["country"] == "PH":
if order["total"] >= 1000:
return 0
else:
return 80
else:
return 450
else:
return None
else:
return None
print(shipping_cost({"items": [1], "country": "PH", "total": 500}))80
Line by line
- 2-4Three nested checks before any real work happens; the reader must remember all of them.
- 5-8The free-shipping rule is buried four levels deep.
- 9-14The
elsebranches are far from theifthey belong to, and two of them returnNonefor different reasons. - 16Prints 80 for a small domestic order.
FREE_SHIPPING_THRESHOLD = 1000
DOMESTIC_RATE = 80
INTERNATIONAL_RATE = 450
def shipping_cost(order):
if order is None or not order["items"]:
return None
if order["country"] != "PH":
return INTERNATIONAL_RATE
if order["total"] >= FREE_SHIPPING_THRESHOLD:
return 0
return DOMESTIC_RATE
print(shipping_cost({"items": [1], "country": "PH", "total": 500}))
print(shipping_cost({"items": [1], "country": "US", "total": 500}))
print(shipping_cost({"items": [], "country": "PH", "total": 0}))80 450 None
Line by line
- 1-3Magic numbers become named constants, so a price change happens in one place.
- 6-7First guard: no order or no items means there is nothing to ship, so return early.
- 8-9Second guard: international orders have a flat rate and we are done.
- 10-12What remains is the domestic rule, written as a flat sequence.
- 14-16Three calls cover the three outcomes: 80, 450 and
None.
DRY: removing duplication wisely
DRY stands for "don't repeat yourself": every piece of knowledge should have one authoritative home. When the same rule is copied into three functions, a change must be made in three places, and the day you forget one you have a bug. Duplicate code is the most common smell in code that grew quickly.
The usual cures are to extract a function, to replace repeated branches with a lookup table (a dictionary), or to loop over data instead of repeating statements. Data-driven code is especially nice in Python because functions are objects: you can put them in a dict and call the right one by key.
DRY has a trap, which I call the wrong abstraction. Two blocks that look alike today may change for different reasons tomorrow. If you merge them into one function full of flags and if branches, you have coupled two things that should have stayed separate. A useful rule of thumb is to tolerate duplication until you see it a third time and understand what really varies, then extract. Duplicated knowledge is what you are hunting, not merely similar-looking lines.
# Before: three copies of the same rule shape
def price_regular(base):
return round(base * 1.00, 2)
def price_member(base):
return round(base * 0.90, 2)
def price_staff(base):
return round(base * 0.75, 2)
print(price_regular(200), price_member(200), price_staff(200))
# After: the variation lives in data, the logic exists once
DISCOUNT_FACTORS = {"regular": 1.00, "member": 0.90, "staff": 0.75}
def price_for(customer_type, base):
return round(base * DISCOUNT_FACTORS[customer_type], 2)
print(*(price_for(kind, 200) for kind in ("regular", "member", "staff")))200.0 180.0 150.0 200.0 180.0 150.0
Line by line
- 2-9Three functions that differ only by a number; adding a fourth customer type means copying again.
- 11Prints
200.0 180.0 150.0. - 14Only the discount factors differ, so they become a dictionary: the data.
- 16-17The rounding and multiplication logic now exists exactly once.
- 19Same three prices, produced by one function; the unknown type raises a
KeyError, which is a clear failure.
If a shared helper grows boolean flags such as is_member=True, skip_tax=False, that is a sign the abstraction is wrong. Consider splitting it back.
Dataclasses, type hints and docstrings
Passing data around as bare tuples and dicts is a quiet source of unreadable code: order[2] means nothing, and a typo in a dict key only fails at run time. A dataclass gives that data a name, named fields and automatic __init__, __repr__ and equality, in a few lines. Frozen dataclasses (frozen=True) also make values immutable, which removes a whole class of bugs.
Type hints tell the reader and tools what goes in and what comes out. Python does not enforce them at run time, but editors and checkers such as mypy use them to catch mistakes, and they replace many comments. Write def total(lines: list[OrderLine]) -> float: and a reader no longer has to guess.
A docstring explains what a function is for and anything the signature cannot say: units, edge cases, exceptions raised. Keep it short and about behaviour, not a line by line retelling of the code. Comments inside the function should explain why something unusual is done, never what the code obviously does. If a comment restates the line below it, delete it.
from dataclasses import dataclass
@dataclass(frozen=True)
class OrderLine:
name: str
unit_price: float
quantity: int
@property
def subtotal(self) -> float:
return self.unit_price * self.quantity
def order_total(lines: list[OrderLine], tax_rate: float = 0.0) -> float:
"""Return the order total including tax.
tax_rate is a fraction (0.12 means 12 percent). An empty order costs 0.
"""
subtotal = sum(line.subtotal for line in lines)
return round(subtotal * (1 + tax_rate), 2)
lines = [OrderLine("notebook", 45.0, 4), OrderLine("pen", 12.5, 10)]
print(lines[0])
print(order_total(lines, 0.12))
print(order_total([]))OrderLine(name='notebook', unit_price=45.0, quantity=4) 341.6 0.0
Line by line
- 3-8A frozen dataclass gives the three fields names and types; frozen means values cannot be reassigned.
- 10-12A computed property keeps the subtotal rule next to the data it belongs to.
- 15Type hints state that the function takes a list of
OrderLineand returns a float. - 16-19The docstring documents units and the empty-order case, which the signature cannot show.
- 20-21Add up subtotals with a generator expression and apply the tax once.
- 24-27Print the auto-generated
repr, a taxed total and the empty-order total.
SOLID, part one: single responsibility and open/closed
SOLID is five design principles that help classes and functions stay easy to change. They are guidelines, not laws, and Python's flexibility means you will apply them more lightly than in Java, but the ideas are valuable. I will show the first two here and the others in the next section, always with a before and after.
Single Responsibility: a unit of code should have one reason to change. A function that calculates a report, formats it as text and writes it to a file has three reasons to change: the maths, the layout and the storage. Splitting them means you can test the calculation with no files and reuse the formatter elsewhere.
Open/Closed: code should be open to extension but closed to modification. If every new feature means editing the same long if/elif chain, that chain is a hot spot for bugs. Replacing it with a mapping or small classes means a new case is a new entry, and existing, tested code is not touched. In Python a dictionary of functions often achieves this with far less ceremony than a class hierarchy.
# Before: one function with three jobs and a growing if/elif chain
def report(sales, fmt):
total = sum(sales)
average = total / len(sales)
if fmt == "text":
return f"Total: {total}, Average: {average:.1f}"
elif fmt == "csv":
return f"total,average\n{total},{average:.1f}"
else:
raise ValueError(fmt)
print(report([100, 200, 300], "text"))
print(report([100, 200, 300], "csv"))Total: 600, Average: 200.0 total,average 600,200.0
Line by line
- 2-4Computes the numbers and chooses the layout in the same function.
- 5-10Every new format forces an edit to this function.
- 12-13Both formats work, but the logic is tangled together.
def summarise(sales):
"""Calculation only: no printing, no formatting."""
total = sum(sales)
return {"total": total, "average": total / len(sales)}
def as_text(stats):
return f"Total: {stats['total']}, Average: {stats['average']:.1f}"
def as_csv(stats):
return f"total,average\n{stats['total']},{stats['average']:.1f}"
FORMATTERS = {"text": as_text, "csv": as_csv}
def report(sales, fmt):
return FORMATTERS[fmt](summarise(sales))
print(report([100, 200, 300], "text"))
print(report([100, 200, 300], "csv"))Total: 600, Average: 200.0 total,average 600,200.0
Line by line
- 1-4One responsibility: turn raw sales into numbers. It is trivial to test.
- 6-10Each formatter changes for exactly one reason, its own layout.
- 12A registry of formatters: adding
as_jsonmeans one new function and one new entry (open for extension). - 14-15
reportjust wires the pieces together and never needs editing for new formats. - 17-18The output is identical to the before version.
SOLID, part two: Liskov, interface segregation and dependency inversion
Liskov Substitution says that a subclass must work anywhere its parent is expected. If code written for Bird calls fly() and a Penguin subclass raises an error, the hierarchy is lying. The fix is usually to model what things can actually do, not what they are called. Interface Segregation says to keep interfaces small: do not force a class to implement methods it does not need. In Python this often means a tiny protocol or just duck typing rather than one giant base class.
Dependency Inversion says that high-level logic should depend on abstractions, not on concrete details such as a particular database, email service or clock. In practice you pass the dependency in as a parameter instead of creating it inside the function. The payoff is testability: a function that receives a sender can be tested with a fake that records messages, without sending anything real.
The example below uses a small Protocol to describe what a notifier must do. The business function does not know whether messages go to email, SMS or a list in memory. That same pattern is how you will write testable code with pytest fixtures and mocks.
from typing import Protocol
class Notifier(Protocol):
def send(self, to: str, message: str) -> None: ...
class ConsoleNotifier:
def send(self, to: str, message: str) -> None:
print(f"to {to}: {message}")
class RecordingNotifier:
"""A fake for tests: it just remembers what it was asked to send."""
def __init__(self):
self.sent = []
def send(self, to: str, message: str) -> None:
self.sent.append((to, message))
def remind_overdue(invoices: dict[str, int], notifier: Notifier) -> int:
count = 0
for customer, days_late in sorted(invoices.items()):
if days_late > 0:
notifier.send(customer, f"Your invoice is {days_late} days late.")
count += 1
return count
invoices = {"ana": 3, "ben": 0, "cy": 12}
print(remind_overdue(invoices, ConsoleNotifier()))
fake = RecordingNotifier()
remind_overdue(invoices, fake)
print(fake.sent)to ana: Your invoice is 3 days late.
to cy: Your invoice is 12 days late.
2
[('ana', 'Your invoice is 3 days late.'), ('cy', 'Your invoice is 12 days late.')]Line by line
- 3-4A
Protocoldescribes the one method a notifier needs; any class withsendqualifies, with no inheritance required (interface segregation). - 6-8A real-world style implementation, here just printing.
- 10-15A test double that stores messages instead of sending them.
- 18-24The business rule receives its notifier as a parameter (dependency inversion) and never creates one itself.
- 28-29With the console notifier the function prints two reminders and returns 2.
- 31-33With the fake we can assert exactly what would have been sent, with no side effects.
Liskov and interface segregation are easiest to spot in code review: a subclass that raises NotImplementedError for an inherited method, or a base class with ten methods where most users call two, are both warning signs.
A worked refactor: same output, better code
Now let me put everything together on a realistic messy script. It reads a few lines of student records, validates them, computes averages and prints a report. The first version works, but it uses cryptic names, deep nesting, duplicated logic and mixes parsing, calculation and printing. I will run it, then refactor it in small steps and run it again to prove the output did not change.
My steps are always the same: first make sure I can see the current behaviour (here, by printing the output), then rename, then extract functions, then introduce a dataclass, then separate the pure logic from the printing. After each step the output must still match. In a real project those checks would be automated tests; in a script like this the printed output is the safety net.
Look at what changed and what did not. The behaviour is identical, including how bad rows are skipped. What improved is that each piece has a name, the calculations can be tested without printing, and adding a new rule (say, a pass mark that changes) means editing one clearly labelled place.
# BEFORE: works, but hard to read and to change
raw = ["ana,90,85,100", "ben,70,,60", "cy,bad,50,50", "dee,60,70,80"]
r = []
for x in raw:
p = x.split(",")
if len(p) == 4:
n = p[0]
s = []
ok = True
for y in p[1:]:
if y.isdigit():
s.append(int(y))
else:
ok = False
if ok:
a = sum(s) / len(s)
if a >= 75:
r.append((n, round(a, 1), "PASS"))
else:
r.append((n, round(a, 1), "FAIL"))
for i in r:
print(i[0] + ": " + str(i[1]) + " " + i[2])ana: 91.7 PASS dee: 70.0 FAIL
Line by line
- 2Raw comma-separated lines; two of them are invalid (empty and non-numeric scores).
- 3-6
r,xandpare meaningless;len(p) == 4is an unexplained rule. - 7-15Parsing and validation are nested inside the loop, using a flag variable
ok. - 16-21The pass mark 75 is hidden inside the nesting, and the append call is repeated twice.
- 22-23Printing is built by string concatenation.
# AFTER: same output, clear structure
from dataclasses import dataclass
PASS_MARK = 75
@dataclass(frozen=True)
class Result:
name: str
average: float
@property
def verdict(self) -> str:
return "PASS" if self.average >= PASS_MARK else "FAIL"
def parse_scores(fields: list[str]) -> list[int] | None:
"""Return the scores, or None if any field is not a whole number."""
if not all(field.isdigit() for field in fields):
return None
return [int(field) for field in fields]
def parse_line(line: str) -> Result | None:
name, *fields = line.split(",")
if len(fields) != 3:
return None
scores = parse_scores(fields)
if scores is None:
return None
return Result(name, round(sum(scores) / len(scores), 1))
def build_report(lines: list[str]) -> list[str]:
results = filter(None, (parse_line(line) for line in lines))
return [f"{r.name}: {r.average} {r.verdict}" for r in results]
raw = ["ana,90,85,100", "ben,70,,60", "cy,bad,50,50", "dee,60,70,80"]
print("\n".join(build_report(raw)))ana: 91.7 PASS dee: 70.0 FAIL
Line by line
- 4The pass mark is now a named constant at the top.
- 6-13A frozen dataclass holds a result; the PASS/FAIL rule lives in one property instead of two duplicated branches.
- 16-20Validation is its own function, with guard-clause style: bad input returns
Noneearly. - 23-30Parsing one line is a flat sequence of guards followed by the happy path; star-unpacking splits the name from the scores.
- 33-35The report builder wires the steps together and skips lines that failed to parse (
filter(None, ...)drops theNonevalues). - 38-39Prints exactly the same two lines as the before version: ana and dee.
Run the before and after blocks and compare. If you ever refactor your own script, copy the old output first and diff it against the new output after every step.
Refactoring safely, and knowing when to stop
Refactoring is only safe when you can tell whether behaviour changed. The best safety net is a set of automated tests that pass before you start and still pass after each small step; our pytest lesson shows how to write them. If there are no tests, write a few that capture the current behaviour first (people call these characterisation tests), then refactor.
Work in small steps and keep each step reversible: rename, run the tests, extract a function, run the tests. Commit often so that you can step back. Do not mix refactoring with adding features in the same commit, because if something breaks you will not know which change caused it. Tools help too: formatters such as Black remove style arguments, and linters such as Ruff flag unused variables and risky patterns automatically.
Finally, stop at "clean enough". Code does not have to be beautiful; it has to be easy for the next person to change. If you are inventing abstractions for situations that do not exist yet, you have gone too far. Prefer the simplest design that handles today's requirements, and refactor again when a real change shows you where the structure hurts.
# A characterisation test: lock in current behaviour before changing code
def slugify(title):
out = ""
for ch in title.lower():
if ch.isalnum():
out += ch
elif ch == " " and not out.endswith("-"):
out += "-"
return out.strip("-")
cases = {
"Hello World": "hello-world",
" Clean Code! ": "clean-code",
"SOLID 101": "solid-101",
}
for given, expected in cases.items():
got = slugify(given)
status = "ok" if got == expected else "CHANGED"
print(f"{status}: {given!r} -> {got!r}")ok: 'Hello World' -> 'hello-world' ok: ' Clean Code! ' -> 'clean-code' ok: 'SOLID 101' -> 'solid-101'
Line by line
- 2-9An existing function whose exact behaviour we want to preserve while we refactor it.
- 11-15A table of inputs and the outputs we have observed and accept.
- 16-19Loop over the table, compare, and print
okorCHANGED. After any refactor ofslugify, every line should still sayok.
Common mistakes
β Refactoring without any safety net
Changing structure with no tests or saved output means you cannot tell whether you broke something. Capture current behaviour first, then change one small thing at a time.
β Abstracting too early
Merging two similar-looking pieces of code into one flexible function with many flags often couples things that change for different reasons. Wait until you understand what truly varies.
β Comments that restate code
A comment like # add one to i above i += 1 adds noise and goes stale. Use names to say what, and comments to say why.
β Giant functions and deep nesting
A function with several indentation levels and section comments is doing many jobs. Extract named helpers and use guard clauses to flatten the logic.
β Over-engineering with patterns
Writing class hierarchies, factories and interfaces for a 50-line script makes it worse. In Python a function, a dict or a dataclass is often all you need.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What is a guard clause?
Q2. Which change is a refactor?
Q3. What does the Single Responsibility Principle suggest?
Q4. Why pass a notifier into a function instead of creating it inside?
Q5. When is it wise to be cautious about applying DRY?
Q6. What best replaces a long if/elif chain that maps a key to behaviour?
Frequently asked questions
How long should a function be?
+There is no magic number. A good rule is that it does one thing, fits on a screen and can be named clearly. If you need section comments inside, extract those sections into functions.
Do I need SOLID in Python?
+The ideas help, but you apply them more lightly than in languages with heavy class systems. Functions, dictionaries and protocols often replace formal hierarchies. Use the principles as a checklist for trouble spots.
Should every function have a docstring?
+Public functions, classes and modules benefit most. Tiny private helpers with a clear name may not need one. Write what the code cannot say: units, edge cases and exceptions.
What tools help keep code clean?
+A formatter such as Black, a linter such as Ruff or Flake8, and a type checker such as mypy catch many issues automatically so reviews can focus on design. Check each tool's own documentation for current setup.
How do I refactor code that has no tests?
+First write a few tests, or save the program's output, that capture what it does now. Then change one small thing at a time and re-run after every step. Our testing lesson shows how.
Key takeaways
- βGood names remove the need for most comments; follow PEP 8 and make names say intent.
- βKeep functions small and single-purpose, and use guard clauses to avoid deep nesting.
- βApply DRY to duplicated knowledge, but avoid abstractions that merge unrelated code.
- βUse dataclasses, type hints and short docstrings to make data and contracts explicit.
- βSOLID gives a checklist: one reason to change, extend rather than edit, honour substitutions, keep interfaces small, inject dependencies.
- βRefactor in small steps behind tests, and stop when the code is clean enough.