Do you mind sharing an example usage in a realistic context? There might be a good solution that doesn't require adding magic methods.


On Tue, Jun 19, 2018, 12:24 PM James Edwards <jheiv@jheiv.com> wrote:
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 comparisons)
    class KeepsTrackOfExtrema:
        def __init__(self):
            self.min_index = None
            self.max_index = None
    
        def append(self, obj):
            new_index = len(obj)
            self.backer.append(obj)
            
            if (self.max_index is None) or (obj > self.backer[self.max_index]):
                self.max_index = new_index
            
            if (self.min_index is None) or (obj < self.backer[self.min_index]):
                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?
        
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/