[Python-ideas] Sorted lists
Steven D'Aprano
steve at pearwood.info
Mon Apr 8 05:17:30 EDT 2019
On Mon, Apr 08, 2019 at 01:31:14PM +1000, Cameron Simpson wrote:
> __setitem__ concerns me, along with other modification methods: what
> about subclasses(*)? Every existing subclass which overrides __setitem__
> now needs to grow code to maintain __issorted__ if they do not
> themselves call list.__setitem__.
Well, yeah. That's what happens if you subclass: you are responsible for
maintaining the invariant if you don't call the superclasses.
Maybe there's a cunning way to avoid this, but that will make the
implementation more complex and probably tips this proposal from "maybe
worth thinking about" to "not a chance".
But I'd be inclined to just pass the buck to the subclass: if you want
to maintain the invariant, then you have to maintain it, or call the
appropriate super methods.
Now that you've reminded me of subclasses, I would make one other change
to the specs: all lists, including empty ones, are created with the flag
set to False. That way subclasses which *don't* maintain the invariant
will always be flagged as unsorted (unless the caller explicitly sets
the flag themselves).
> Also, should this imply an issorted() builtin to consult an instance's
> __issorted__ dunder flag? Should such a builtin return False for
> instances without an __issorted__ flag? I'm thinking yes since the flag
> is intended to mean known-to-be-sorted.
I don't think this proposal is worth adding a builtin function. Not
unless somebody thinks of some more very compelling use-cases.
Perhaps an inspect.sort_hint() function.
--
Steven
More information about the Python-ideas
mailing list