[Python-ideas] "Exposing" `__min__` and `__max__`

James Edwards jheiv at jheiv.com
Tue Jun 19 15:18:17 EDT 2018

I've only recently looked for these special methods, so that in and of
itself may be the reason these methods aren't exposed, but I could think of
objects that may wish to implement __min__ and __max__ themselves, for
efficiency.  For example:

    # A "self-sorted" list object
    class AlwaysSortedListObejct:
        def __min__(self): return self.lst[0]
        def __max__(self): return self.lst[-1]

    # An object that maintains indices of extrema (e.g. for complex
    class KeepsTrackOfExtrema:
        def __init__(self):
            self.min_index = None
            self.max_index = None

        def append(self, obj):
            new_index = len(obj)

            if (self.max_index is None) or (obj >
                self.max_index = new_index

            if (self.min_index is None) or (obj <
                self.min_index = new_index

        def __min__(self): return self.backer[self.min_index]
        def __max__(self): return self.backer[self.max_index]

Where these methods be called via the single-argument calls to `max(obj)`
and `min(obj)`.

If it's not clear, it'd be similar to the way __len__ is called (when
defined) via len(obj).

My solution was to implement a .min() method, but that caused some ugly
special casing when the object could also be a regular list (where I'd want
to iterate over all of the items).

I searched the list, but has this been discussed before?  Is there any
merit in it?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180619/0c3e35c6/attachment.html>

More information about the Python-ideas mailing list