[Python-ideas] a sorting protocol dunder method?

David Mertz mertz at gnosis.cx
Sun Dec 3 22:14:19 EST 2017


I'm not sure I understand the motivation to make elements *sortable* but
not comparable. If an arbitrary order is still useful, I'd think you'd want
to be able to tell how two particular elements *would* sort by asking a<b.

On Dec 3, 2017 6:55 PM, "Bruce Leban" <bruce at leban.us> wrote:

>
> On Sun, Dec 3, 2017 at 3:06 PM, Chris Barker <chris.barker at noaa.gov>
>  wrote:
>
>>
>> However, if you are writing a custom class ... <snip>
>>
>> But what if there was a sort key magic method:
>>
>>  __key__ or __sort_key__ (or whatever)
>>
>> that would be called by the sorting functions <snip>
>>
>> It seems this would provide a easy way to make custom classes sortable
>> that would be nicer for end users (not writing key functions), and possibly
>> more performant in the "usual" case.
>>
>
> On Sun, Dec 3, 2017 at 4:57 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>
>>
>> This shows the problem with putting the key function into the data type.
>> What if I want to sort AttrDicts by their list of keys instead? Or their
>> (key, value) pairs? What is so special about sorting by ID (which may
>> not even exist!) that it deserves to be part of the AttrDict itself?
>
>
> I think you're arguing against this for the wrong reason. Chris was
> talking about custom classes having the *option* of making them sortable
> by providing a key method in the class definition. This strikes me as
> useful and I can imagine having used this if it were available. What you're
> saying is that there are classes which probably shouldn't define a
> __sort_key__ function, which I quite agree with. But I don't think it's a
> good argument against this proposal.
>
>
> On Sun, Dec 3, 2017 at 3:06 PM, Chris Barker <chris.barker at noaa.gov>
>  wrote:
>
>> Am I imagining the performance benefits?
>>
>
> Maybe. Looking strictly at O(-) cost, there's no difference between a key
> function and comparison operators. Sure it might potentially only make O(n)
> calls to the key function and O(n log n) calls to compare the keys vs. O(n
> log n) calls to the comparator functions but that might not actually be
> faster. There certainly are cases where implementing a key function would
> be quite slow.
>
> --- Bruce
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171203/bbc04450/attachment.html>


More information about the Python-ideas mailing list