Skip to content

Annotation for builtin max() function uses wrong comparison operator #6336

@rhettinger

Description

@rhettinger

The stubs for max() use SupportsLessThanT but should use SupportsGreaterThanT instead.

The CPython source uses Py_GT.

Instrumenting calls to max() shows the '>' operator being invoked:

class I(int):
    def __gt__(self, other):
        print(f'{self} > {other}')
        return int.__gt__(self, other)
    def __lt__(self, other):
        print(f'{self} < {other}')
        return int.__Lt__(self, other)

>>> largest = max(map(I, [10, 40, 20]))
40 > 10
20 > 40
>>> largest
40

A class that supplies only __gt__ suffices for a call to max():

class ReverseInt:
    def __init__(self, x):
        self.x = x
    def __gt__(self, other):
        return self.x < other.x
    def __repr__(self):
        return f'{type(self).__name__}({self.x!r})'
  
>>> max(map(ReverseInt, [10, 40, 20]))
ReverseInt(10)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions