Skip to content

Dispatching mechanism in reprlib.repr may be fragile #135890

Closed as not planned
Closed as not planned
@picnixz

Description

@picnixz

Bug report

Bug description:

reprlib.repr implements a visitor pattern which dispatches according to the typename and the module. However, changing the module and the name can lead to surprises. Ideally, we need to be able to check if an instance is an exact type and only use the visitor function for that exact type (not subtypes).

The docs don't explicitly say that exceptions are ignored for custom instances. For instance:

import reprlib

class A:
    def __len__(self):
        assert 0

A.__module__ = 'builtins'
A.__name__ = 'dict'

reprlib.repr(A())  # raises AssertionError as it tries len(A()) in repr_dict

I'm opening an issue to decide whether this is worth addressing or not. Should we consider code that changes dunders in such a way that checks by names and modules fail as legitimate or as "garbage in -> garbage out"?

cc @serhiy-storchaka

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions