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

Serhiy Storchaka storchaka at gmail.com
Wed Jun 20 13:17:37 EDT 2018


20.06.18 10:00, Steven D'Aprano пише:
> On Wed, Jun 20, 2018 at 07:05:19AM +0300, Serhiy Storchaka wrote:
>> 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)

The devil is in details. And you will see this when try to implement 
min() and __min__().

1) There is no default value for default. This makes handling it in 
Python code hard.

2) Two original examples don't work with the key function. You will need 
to add complex caches for supporting different key functions, and this 
will add new problems.

In future we may add new parameters for min() and max(). This is not 
closed protocol as for len() or `+`.

>> 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 :-)

N may be small. And I suppose that for most calls it may be <10 or even 
<5. Note that the cost will be much larger than for __len__ or __add__, 
because new dunder methods will not have slots.



More information about the Python-ideas mailing list