[Python-ideas] "Exposing" `__min__` and `__max__`
leewangzhong+python at gmail.com
Tue Jun 26 17:49:23 EDT 2018
On Tue, Jun 26, 2018 at 11:34 AM, Franklin? Lee
<leewangzhong+python at gmail.com> wrote:
> On Wed, Jun 20, 2018, 00:05 Serhiy Storchaka <storchaka at gmail.com> 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.
> Neither should be passed to a dunder.
> It is not possible to handle `key` without figuring out if a function is
> monotonic (a Turing-complete problem in general) or anti-monotonic (if that
> is a real term), so you MUST fall back on full iteration if a key is
> `default` is only used in case of an empty collection. The only question is,
> who has responsibility for detecting an empty collection, and how?
> Caller detects: The caller checks length before calling the dunder. If there
> is no dunder, it doesn't check. Are there real-world cases where length is
> not defined on an iterable collection?
> Dunder detects: Right now, `max` detects empty by watching for
> StopIteration, which can no longer be a false positive. StopIterations from
> a deeper scope are wrapped. If the dunder throws an error to signal
> emptiness, it should not be thrown otherwise. I think that's impossible to
There's an argument that you DO want to pass to the dunder:
`last=True`. It's not currently part of `min` and `max`.
Currently, if there are multiple items that are maximum, `max` will
return the first one. In the future, a `last:bool` param could be
added, and a dunder for `max` will want to handle it.
More information about the Python-ideas