[Python-ideas] "Exposing" `__min__` and `__max__`
leewangzhong+python at gmail.com
Tue Jun 26 11:34:50 EDT 2018
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
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas