liveBook · Manning

Refactoring

As explained in The Quick Python Book, Fourth Edition

Refactoring is the systematic restructuring of existing source code to improve its internal qualities without changing its externally observable behavior.

Refactoring rewrites existing, working code to improve its structure or clarity while preserving what it does. Start with the code and a specific goal: make it shorter, move processing into functions, or reorganize modules. Adding a new feature can happen alongside a refactor, but it changes the program’s behavior and should be identified separately. section 8.13.1 section 9.9.1 section 18.6

A practical refactoring pass:

  • Identify what must keep working. For a file counter, check its line, word, and character counts before and after the rewrite. section 8.13 section 8.13.2
  • Choose a focused improvement. Shorter expressions may replace counting loops; functions can separate cleaning, counting, and reporting. Give functions clear names and return values rather than relying on globals. section 8.13.2 section 9.9 section 9.9.2
  • Check the trade-off. Reading a whole file can shorten the code, but line-by-line processing handles much larger files. section 8.13.2
  • Run the result, including AI-generated rewrites. A missing import can fail immediately; assigning a function’s name to its string result can fail on the next loop iteration. section 9.9.2
""" Reads a file and returns the number of lines, words,
    and characters - similar to the UNIX wc utility
"""
 
with open('word_count.tst') as infile: 
    lines = infile.readlines()                        #1
 
line_count = len(lines) 
word_count = sum(len(line.split()) for line in lines) #2
char_count = sum(len(line) for line in lines)         #3
 
print(f"{line_count} lines, {word_count} words, {char_count} characters")

This shorter word counter replaces explicit count increments with len(), sum(), and generator expressions. Its readlines() call holds the file’s lines in memory. section 8.13.2

Keep a feature change distinct

Changing a word counter to accept only alphabetic words is not merely a shorter way to count the same words: it changes which inputs count. A suggested filter uses word.isalpha(). Likewise, adding wc-style -l, -w, -c, and -L options extends a counter while its existing counting logic is being reworked. Compare the resulting command with the system’s wc where available. section 8.13.1 section 8.13.2 section 11.5

Refactoring can also change a program’s organization: move text cleaning and word-frequency processing into separate functions, then separate modules in a package. Other exercises add exception handling or replace os and shutil with pathlib. Specify which behavior should remain, and review any requested additions on their own terms. Avoid changing working code solely to add type hints unless there is a good reason. section 9.9 section 18.6 section 14.4 section 12.6.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through shorter expressions and function extraction, including memory and naming pitfalls, rather than prescribing a universal refactoring procedure.
Examples
Reworks a word counter, extracts text-processing functions, and reorganizes a word-frequency program into a package.
What it assumes
Assumes existing working Python code and familiarity with strings, lists, file reading, and functions.
What you can do after
Practice/perform focused Python rewrites and check generated code for resource trade-offs, missing imports, and name collisions.
How it connects
Connects refactoring to functions, generator expressions, exception handling, packages, and pathlib.

Also explained in

Compare how 22 books explain refactoring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.