On Sun, Dec 3, 2017 at 3:06 PM, Chris Barker <chris.bar...@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 <st...@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.bar...@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@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/