[New-bugs-announce] [issue20632] Define a new __key__ protocol

Nick Coghlan report at bugs.python.org
Sat Feb 15 01:17:55 CET 2014


New submission from Nick Coghlan:

This is an idea that would require a PEP, just writing it down here as a permanent record in case someone else wants to run with it.

Currently, the *simplest* way to define a non-identity total ordering on an immutable object is to define __hash__, __eq__ and __lt__ appropriately, and then use functools.total_ordering to add the other comparison methods.

However, many such implementations follow a very similar pattern:

    def __hash__(self):
        return hash(self._calculate_key())
    def __eq__(self, other):
        if isinstance(other, __class__):
            return self._calculate_key() == other._calculate_key()
        return NotImplemented
    def __lt__(self, other):
        if isinstance(other, __class__):
            return self._calculate_key() < other._calculate_key()
        return NotImplemented

A "__key__" protocol as an inherent part of the type system could greatly simplify that:

    def __key__(self):
        return self._calculate_key()

The interpreter would then derive appropriate implementations for __hash__ and all the rich comparison methods based on that key calculation and install them when the type object was created.

If the type is mutable (and hence orderable but not hashable), then setting "__hash__ = None" would disable the implicit hashing support (just as it can already be used to explicitly disable hash inheritance).

(Inspired by Chris Withers's python-dev thread: https://mail.python.org/pipermail/python-dev/2014-February/132332.html)

----------
components: Interpreter Core
messages: 211253
nosy: ncoghlan
priority: normal
severity: normal
status: open
title: Define a new __key__ protocol
type: enhancement
versions: Python 3.5

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue20632>
_______________________________________


More information about the New-bugs-announce mailing list