[Python-ideas] "Exposing" `__min__` and `__max__`
Steven D'Aprano
steve at pearwood.info
Wed Jun 20 03:00:57 EDT 2018
On Wed, Jun 20, 2018 at 07:05:19AM +0300, Serhiy Storchaka wrote:
> 19.06.18 22:18, James Edwards пише:
> >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.
>
> There are two questions.
>
> 1. What to do with additional min() and max() arguments: key and default.
Since there are no reflected versions of min/max, there is no trouble
with extra arguments. Just pass them through to the dunder:
min(obj, key=x, default=y) => type(obj).__min__(key=x, default=y)
> 2. Is the need of this feature large enough? Will the benefit for
> special cases exceed the drawback of increasing implementation
> complexity and slowing down common cases?
Reasonable questions, but I don't think that the cost of testing:
if hasattr(type(obj), '__min__')
# or equivalent
is going to be very large. Amortized over O(N) comparisons, that's
practically free :-)
More important, I think, is the increase in API complexity. That's two
more dunders to learn about.
The first part is critical: is this useful enough to justify two more
dunders? I think the answer is a definite Maybe. Or perhaps Maybe Not.
I think that without at least one use-case in the standard library,
perhaps we should hold off on this. Unless numpy arrays are important
enough to justify this on their own?
Are there any builtins or std library classes that offer their own
min()/max() methods? If so, that would be good evidence that making this
a dunder-based protocol has stdlib use-cases.
--
Steve
More information about the Python-ideas
mailing list