Skip to content

difflib.get_close_matches raises TypeError for tied matches containing non-orderable elements #158705

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: get_close_matches docstring: "word is a sequence for which close matches are desired (typically a string)." "possibilities is a list of sequences against which to match word (typically a list of strings)." "The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first."

Expected: Return both candidates, in either order, since both score 0.5 and n is 3.

Actual: Raises TypeError: '<' not supported between instances of 'complex' and 'complex'.

import difflib
from collections import Counter

data = dict(word=[0j, 3j], possibilities=[[0j, 1j], [0j, 2j]], n=3, cutoff=0.5)
w, ps, n, cutoff = data.values()

def matches(a, b):
    best, i, j = 0, 0, 0
    for x in range(len(a)):
        for y in range(len(b)):
            k = 0
            while x+k < len(a) and y+k < len(b) and a[x+k] == b[y+k]:
                k += 1
            if k > best:
                best, i, j = k, x, y
    return (best + matches(a[:i], b[:j]) + matches(a[i+best:], b[j+best:])
            if best else 0)

def score(p):
    return 2 * matches(w, p) / (len(w) + len(p))

valid = (
    isinstance(ps, list)
    and all(isinstance(s, list) and all(isinstance(x, complex) for x in s)
            for s in [w] + ps)
    and isinstance(n, int) and n > 0 and 0 <= cutoff <= 1
)
if not valid:
    print("REFUTATION REJECTED:", "input violates documented requirements")
else:
    expected = sorted((p for p in ps if score(p) >= cutoff),
                      key=score, reverse=True)[:n]
    try:
        actual = difflib.get_close_matches(**data)
        # Both reported candidates tie, so accept either ordering.
        ok = (isinstance(actual, list)
              and Counter(map(tuple, actual)) == Counter(map(tuple, expected)))
    except Exception as e:
        actual = (type(e).__name__, str(e))
        ok = False
    if ok:
        print("REFUTATION REJECTED:", "actual matches the documented expectation")
    else:
        print("REFUTATION CONFIRMED:", data, "actual:", actual, "expected:", expected)

Output on Python 3.14.6 (Windows-11-10.0.26220-SP0), standard library difflib:

REFUTATION CONFIRMED: {'word': [0j, 3j], 'possibilities': [[0j, 1j], [0j, 2j]], 'n': 3, 'cutoff': 0.5} actual: ('TypeError', "'<' not supported between instances of 'complex' and 'complex'") expected: [[0j, 1j], [0j, 2j]]

This report was found and written by an automated property-testing tool I run (bugforge). The reproducer above was executed and its output is pasted unedited; no person reviewed the report before it was filed. The search script is in https://github.com/augusto-rehfeldt/bugforge-results/tree/main/difflib-c1

CPython versions tested on:

3.14

Operating systems tested on:

Windows

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions