python/repeated-block
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| Python | warning | none, edit by hand | All versions |
Three or more structurally identical groups of at least two statements in one function that differ in one name part repeat the same logic by copy-paste. Replace them with one for loop over the varying part that builds each name from it and updates one dict with derived |= ....
def build_features(base): north_net = base["north_import"] - base["north_export"] north_total = base["north_import"] + base["north_export"] south_net = base["south_import"] - base["south_export"] south_total = base["south_import"] + base["south_export"] east_net = base["east_import"] - base["east_export"] east_total = base["east_import"] + base["east_export"] return { "north_net": north_net, "north_total": north_total, "south_net": south_net, "south_total": south_total, "east_net": east_net, "east_total": east_total, }REGIONS = ("north", "south", "east")
def region_features(base, region): return { f"{region}_net": base[f"{region}_import"] - base[f"{region}_export"], f"{region}_total": base[f"{region}_import"] + base[f"{region}_export"], }
def build_features(base): derived = {} for region in REGIONS: derived |= region_features(base, region) return derivedWhat the rule reports
Section titled “What the rule reports”The rule inspects each statement block inside a function and reports when three or more structurally identical groups of at least two statements (k >= 3 groups of s >= 2 statements) differ only in one varying name part across identifiers and string keys. Requiring at least two statements per group guarantees that replacing the k * s repeated statements with derived = {} and one for loop (2 + s statements) is strictly shorter than the code it replaces.
Common prefixes and suffixes are trimmed only at separator boundaries (_, -, ., /) so varying parts are reported as whole name parts or whole identifiers rather than mid-word fragments.
The rule leaves alone repeated single statements, blocks that call different functions or methods, statements that vary in more than one independent name, and groups without a shared separator-bounded prefix or suffix.
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so make the change by hand.
Extract the repeated block into a loop over the varying part, build each name from that part, and merge each iteration's mapping into one dict with derived |= ....
Diagnostic message
Section titled “Diagnostic message”This function repeats three or more structurally identical groups of at least two statements that differ in one name part. Replace them with one for loop over the varying part that builds each name from it and updates one dict with derived |= ....See all rules in the Python pack.