liveBook · Manning

Don't repeat yourself principle

As explained in Python How-To

DRY is the software design principle that each piece of knowledge or behavior should have a single authoritative representation.

DRY is a maintainability rule: give each repeated piece of code or knowledge one shared representation. Duplication forces every future change to be made in several places, increasing inconvenience and the risk of inconsistent behavior. When repetition appears, consider refactoring it into a variable, function, or other shared structure. section 1.1.2 section 2.1.4

Extract a repeated f-string format

Repeated formatting makes a later alignment change require multiple edits:\n\nfor i in range(3):\n print(f'{task_ids[i]:^12}{task_names[i]:^12}{task_urgencies[i]:^12}')\n\nExtract the format specifier and make it configurable instead:\n\ndef create_formatted_records(fmt):\n for i in range(3):\n task_id = task_ids[i]\n name = task_names[i]\n urgency = task_urgencies[i]\n print(f'{task_id:{fmt}}{name:{fmt}}{urgency:{fmt}}')\n\ncreate_formatted_records('^15')\n\nNow the shared formatting rule is changed once, while the function can support different widths such as '^18'. This refactoring changes structure without adding features or changing the program's external behavior. section 2.1.4

How Python How-To covers it

How deep it goes
Demonstrates duplication, extracts a variable and function, and stops short of broader refactoring patterns.
Examples
Uses repeated f-string alignment expressions, a configurable formatting function, and alternate width arguments.
What it assumes
Assumes basic Python expressions, loops, functions, and f-strings while teaching duplication as a maintainability warning.
What you can do after
Apply it via refactoring by replacing repeated formatting rules with shared variables or parameterized functions.
How it connects
Connects DRY with refactoring, maintainability, readability, f-strings, and IDE duplication detection.

Also explained in

Compare how 10 books explain don't repeat yourself principle →

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.