On Fri, Dec 27, 2019 at 9:35 AM Andrew Barnert <abarn...@yahoo.com> wrote:
>
> On Dec 26, 2019, at 14:13, Chris Angelico <ros...@gmail.com> wrote:
> >
> > On Fri, Dec 27, 2019 at 9:07 AM Andrew Barnert via Python-ideas
> > <python-ideas@python.org> wrote:
> >>
> >> You can very easily just write a key function that does this for you. In 
> >> fact, you can write different key functions for different variations.
> >>
> >> For example, if you’re specifically sorting floats and want to shift nans 
> >> to the right (even beyond inf):
> >>
> >>    class shift_nan_to_end_key(float):
> >>        def __lt__(self, other):
> >>            return math.isnan(other) or not math.isnan(self) and 
> >> float(self)<float(other)
> >>
> >> If you want to sort nans to the start, or deal with some other type with 
> >> incomparable values, or do something more general with all pairs of 
> >> incomparable values, you can just write a different key function. 
> >> Whatever’s most appropriate for readability or type safety or performance 
> >> for your particular use case, do that.
> >
> > You've created a key class, effectively equivalent to a cmp_to_key
> > form. Is there a flaw in this much simpler version?
> >
> > def nans_right(n): return math.isnan(n), n
>
> No, I just thought being explicit would be clearer here. Seeing them both 
> written out, I think you’re right, and all the extra boilerplate gets in the 
> way much more than making you think through the (trivial) lexicographical 
> compare does.
>
> And actually, where there is a difference, yours is usually better. For 
> example, if you’re not sure the inputs will be floats, yours will raise in 
> more cases than mine. (If you want to sort stringified floats out of a CSV or 
> something, you probably want to say so explicitly, and I don’t think 
> `nans_right` does say that.)
>
> But the fact that you can use whichever one you think is best for your case 
> is certainly a nice feature of Python’s sorting API. :)
>

Yeah, agreed :) Lots of languages have support for a comparison
function, but in the common cases, a key function is WAY simpler to
write (unless you forego stability, in which case it's merely "notably
simpler"), and can perform better too. But when you need the
flexibility, the comparison function is easily implemented, courtesy
of operator overloading.

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/CDTJBVFPLMYP75ECPBISIDWDRSG33FCO/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to