liveBook · Manning

Refactoring

As explained in Python How-To

Refactoring is the restructuring of existing code to improve its design or maintainability without changing its externally observable behavior.

Refactoring restructures existing code to improve design and maintainability without changing its externally observable behavior. It removes repetition, clarifies responsibilities, and keeps code easier to change; it does not add features. section 2.1.4 section 9.0

Look for these practical signals and opportunities:

  • Repeated code often violates the DRY principle; extract the shared portion so changes happen in one place. section 1.1.2 section 2.1.4
  • When a class grows beyond one purpose, separate its mixed responsibilities into distinct classes. section 9.6
  • When tests repeat setup work, move the shared operation into unittest.TestCase.setUp. section 13.3.3

Extracting repeated formatting

Repeated format specifications make later changes inconvenient and error-prone. Extract the format into a parameterized function: def create_formatted_records(fmt): for i in range(3): task_id = task_ids[i] name = task_names[i] urgency = task_urgencies[i] print(f'{task_id:{fmt}}{name:{fmt}}{urgency:{fmt}}') Calling create_formatted_records('^15') or create_formatted_records('^18') changes the layout in one place while preserving the records and function’s purpose. section 2.1.4

Listing 13.7 Overriding the setUp method (test_task_func.py)
from task_func import Task, create_task, create_task_from_dict
import unittest
 
class TestTaskCreation(unittest.TestCase):
    def setUp(self):
        task_to_compare = Task("Laundry", 3)
        self.task_dict = task_to_compare.__dict__
 
    def test_create_task(self):
        task_text = "Laundry,3"
        created_task = create_task(task_text)
        self.assertEqual(created_task.__dict__, self.task_dict)
 
    def test_create_task_from_dict(self):
        task_data = {"title": "Laundry", "urgency": 3}
        created_task = create_task_from_dict(task_data)
        self.assertEqual(created_task.__dict__, self.task_dict)
 
 
if __name__ == "__main__":
    unittest.main()

Shows a unittest setup refactoring that creates one comparison object before each test instead of duplicating it inside multiple test methods. section 13.3.3

How Python How-To covers it

How deep it goes
Explains the behavior-preserving goal and demonstrates extraction in formatting, testing, and class design without discussing implementation internals.
Examples
Demonstrates repeated f-string formatting, a parameterized formatting function, a split class design, and unittest setUp.
What you can do after
Apply it by extracting repeated formatting or test setup and separating classes whose responsibilities have become mixed.
How it connects
Connects refactoring with the DRY principle, maintainability, functions, classes, unit testing, and f-strings.

Also explained in

Compare how 22 books explain refactoring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.