Skip to content

pprint.saferepr raises RecursionError when sorting self-referential list-subclass dictionary keys #158738

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: The pprint.saferepr documentation states: "Return a string representation of object, protected against recursive data structures." It further specifies: "This only handles recursive instances of dict, list and tuple or subclasses whose repr is not overridden."

Expected: Return a string representing the dictionary, with recursion markers for its self-referential keys.

Actual: RecursionError: Stack overflow (used 2912 kB) in comparison

import pprint

class Key(list):
    __hash__ = object.__hash__

a, b = Key(), Key()
a.append(a)
b.append(b)
d = {a: 1, b: 2}

if not (len(d) == 2 and a is not b and all(
    isinstance(k, list) and type(k).__repr__ is list.__repr__
    and type(k).__hash__ is object.__hash__ and k[0] is k
    for k in d
)):
    print("REFUTATION REJECTED: input does not meet the documented conditions")
else:
    expected = "{" + ", ".join(
        f"[<Recursion on Key with id={id(k)}>]: {v}" for k, v in d.items()
    ) + "}"
    try:
        actual = pprint.saferepr(d)
        broken = not isinstance(actual, str)
    except Exception as e:
        actual = f"{type(e).__name__}: {e}"
        broken = True
    if broken:
        print("REFUTATION CONFIRMED:", "input:", repr(d),
              "actual:", repr(actual), "expected:", repr(expected))
    else:
        print("REFUTATION REJECTED: saferepr returned a string without raising")

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

REFUTATION CONFIRMED: input: {[[...]]: 1, [[...]]: 2} actual: 'RecursionError: Stack overflow (used 2912 kB) in comparison' expected: '{[<Recursion on Key with id=1278655537488>]: 1, [<Recursion on Key with id=1278655537136>]: 2}'

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/pprint-20261003-073352-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