[Python-ideas] "Exposing" `__min__` and `__max__`
mike at selik.org
Wed Jun 27 11:05:19 EDT 2018
On Wed, Jun 27, 2018 at 7:30 AM Steven D'Aprano <steve at pearwood.info> wrote:
> On Wed, Jun 27, 2018 at 06:52:14AM -0700, Michael Selik wrote:
> > > > Have you ever written ``max(range(x))`` in production code?
> > > I have never written that.
> > > But I have written ``max(iterable)`` dozens of times, where iterable
> > > could be a range object.
> > >
> > My intent was to ask where a range was in fact passed into max, not
> > where it could be. It'd be enlightening to see a complete, realistic
> > example.
> A complete, realistic example is as I said: you call max() on some
> object which you don't control, the caller does. You could be
> passed a list, or a set, or a bitset, a binary search tree, a range
> object, whatever the caller happens to pass to you.
This is not a complete, realistic example. You're describing what an
example might be, but not providing a concrete one with context.
Quoting Guido from earlier in the thread: "I think just finding a data
structure that should implement its own min/max funtionality (or maybe one
of these, like heapq) is not enough motivation. You have to find code where
such a data structure (let's say a Tree) is passed to some function that
also accepts, say, a list."
Imagine that Python's len() always walked the entire iterable, from
start to end, to count the length. Now suppose that you proposed
> adding a __len__ protocol so that objects that know their own length
> can report it quickly, and in response I argued that
> was unrealistic and that there is no need for a __len__ method
> because we could just say
> instead. I don't think you would find that argument very persuasive,
> would you?
I would, actually. The range object is particularly unpersuasive as a
motivation for magic methods, because of its unusual usage. The
hypothetical Tree object discussed earlier was much more interesting.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas