Skip to content

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

Closed

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)

Activity

  1. added 3 commits that reference this issue on Nov 19, 2021
    1f432f8
    2e1d7d1
    c8ae584
  2. added a commit that references this issue on Nov 21, 2021
    a6e3699
  3. rhettinger commented on Nov 23, 2021

    @rhettinger
    Author

    Thanks for fixing this.

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions