[Python-ideas] a sorting protocol dunder method?

Julien Salort listes at salort.eu
Mon Dec 4 16:54:27 EST 2017

Le 04/12/2017 à 14:16, Steven D'Aprano a écrit :

> We're taking something which belongs in the report generator or
> collection, the knowledge of how to sort a collection of unordered
> values, and baking it into the values themselves. (Effectively making
> them ordered!)
It is also possible to use this __key__ method for classes for which the 
is indeed unambiguously defined, e.g.:

class MyValue:

     def __init__(self, value, comment):
         self.value = value
         self.comment = comment

     def __key__(self):
         return self.value

Then it is not shocking to define a sorting key.

More information about the Python-ideas mailing list