[Python-ideas] "Exposing" `__min__` and `__max__`
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
def __min__(self): return self.lst
def __max__(self): return self.lst[-1]
# An object that maintains indices of extrema (e.g. for complex
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)`
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...
More information about the Python-ideas