[Python-ideas] a sorting protocol dunder method?
Chris Angelico
rosuav at gmail.com
Mon Dec 4 17:03:20 EST 2017
On Tue, Dec 5, 2017 at 8:54 AM, Julien Salort <listes at salort.eu> wrote:
> 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
> ordering
> 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.
MyValue = namedtuple('MyValue', ['value', 'comment'])
Job done :)
ChrisA
More information about the Python-ideas
mailing list