Skip to content

difflib ignores falsey callable junk predicates #158779

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: The Python library documentation for difflib.ndiff describes linejunk as: "A function that accepts a single string argument, and returns true if the string is junk, or false if not."

Expected: Both calls return ['- A\n', ' B\n', '+ A\n'].

Actual: The falsey predicate returns ['+ B\n', ' A\n', '- B\n']; its lambda wrapper returns the expected result.

import difflib

class Predicate:
    def __call__(self, line):
        return line == "A\n"

    def __bool__(self):
        return False

a, b, p = ["A\n", "B\n"], ["B\n", "A\n"], Predicate()
data = {"a": a, "b": b,
        "p": {"junk_membership": ["A\n"], "__bool__": False}}

if not (callable(p) and all(
    isinstance(s, str) and type(p(s)) is bool and p(s) == p(s)
    for s in a + b
)):
    print("REFUTATION REJECTED: input violates the documented predicate contract")
else:
    actual = list(difflib.ndiff(a, b, linejunk=p))
    # Independent alignment: B is the sole nonjunk anchor; A moves past it.
    expected = ["- " + a[0], "  " + a[1], "+ " + b[1]]
    wrapped = list(difflib.ndiff(a, b, linejunk=lambda s: p(s)))
    if actual != expected and wrapped == expected:
        print("REFUTATION CONFIRMED:", data,
              "actual:", actual, "expected:", expected)
    else:
        print("REFUTATION REJECTED: no independently verified wrapper discrepancy",
              data, "actual:", actual, "expected:", expected, "wrapped:", wrapped)

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

REFUTATION CONFIRMED: {'a': ['A\n', 'B\n'], 'b': ['B\n', 'A\n'], 'p': {'junk_membership': ['A\n'], '__bool__': False}} actual: ['+ B\n', '  A\n', '- B\n'] expected: ['- A\n', '  B\n', '+ A\n']

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-20261003-011733-c2

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