Skip to content

python/look-alike-definition

Pack Severity Fix Versions
Python warning none, edit by hand All versions

Two or more functions or classes in the same module that share most of their structure after setting aside variable names and literal values duplicate the same logic. Merge them into one definition parameterized by what differs.

async def load_wind_forecast(client, start, end):
cached = await client.cache_get("wind_forecast", start, end)
if cached is not None:
return cached
rows = await client.fetch("wind_forecast", start=start, end=end)
frame = build_frame(rows)
await client.cache_put("wind_forecast", start, end, frame)
return frame
async def load_solar_forecast(client, start, end):
cached = await client.cache_get("solar_forecast", start, end)
if cached is not None:
return cached
rows = await client.fetch("solar_forecast", start=start, end=end)
frame = build_frame(rows)
await client.cache_put("solar_forecast", start, end, frame)
return frame
async def load_forecast(client, kind, start, end):
cached = await client.cache_get(kind, start, end)
if cached is not None:
return cached
rows = await client.fetch(kind, start=start, end=end)
frame = build_frame(rows)
await client.cache_put(kind, start, end, frame)
return frame

The rule runs the xpd untangle look-alike detector across definitions in the same file at xpd check time and reports each group of look-alike functions or classes on its earliest definition.

At commit time, the rule reports a pair only when all three hold:

  • They share at least 80% of their code (the detector's plain similarity bar, without the advisory 60% name-and-parameter bar used by xpd untangle).
  • Each definition has at least 80 code tokens (twice the advisory 40-token floor, excluding comments, docstrings, type annotations, and formatting punctuation), so merging two definitions into one parameterized definition plus callers deletes code instead of adding wrapper overhead, regardless of line wrapping.
  • They are not same-named methods on different classes implementing one interface (for example, fit on separate estimator classes).

Test files, generated files, and vendored paths are skipped.

xpd has no automatic fix, so make the change by hand.

Merge the look-alike definitions into one function or class parameterized by what differs, and update each call site to pass that value.

These definitions do much the same work. Merge them into one definition parameterized by what differs.

See all rules in the Python pack.