X Tutup
The Wayback Machine - https://web.archive.org/web/20250604123447/https://github.com/python/cpython/issues/106222
Skip to content

Provide a way for operators on subclasses of native types to return instances of the subclass #106222

Closed as not planned
@Gouvernathor

Description

@Gouvernathor

Feature or enhancement

A simple way to make tuple_subclass(...)[:] an instance of tuple_subclass instead of tuple, same for -float_subclass(...).

Pitch

When subclassing native types such as float or dict, or stdlib types such as Counter, it’s often surprising or frustrating for new users that Subclass() + Subclass() is an instance of the native type rather than the subclass.
It is so for performance reasons I assume, so I’m not proposing we change that. Instead, I'm proposing a way to easily but specifically direct subclasses to work that way.

Mitigating that behavior is often tedious and leads to long, repetitive and error-prone code, here is my favorite one (written by yours truly) but which is still a chore :
https://github.com/renpy/renpy/blob/master/renpy/display/core.py#L193-L276
Doing this kind of operation is very unhandy for beginners and amateurs alike, as this thread shows for example.

My idea is to make a functools.total_ordering-like class decorator, which I explain in more details in the Discuss thread, in the docstring of the implem and possibly in the pull request.
Testable implementation, also proposed as a pull request to the functools module.

Previous discussion

https://discuss.python.org/t/re-type-operator-overloads-when-subclassing-a-builtin-or-stdlib-type/28378/2

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup