[docs] [issue22052] Comparison operators called in reverse order for subclasses with no override.

Mark Dickinson report at bugs.python.org
Wed Jul 23 23:03:30 CEST 2014

New submission from Mark Dickinson:

As reported in a StackOverflow question [1]: the order in which the special comparison methods are called seems to be contradictory to the docs [2].  In the following snippet, __eq__ is called with reversed operands first:

>>> class A:
...     def __eq__(self, other):
...         print(type(self), type(other))
...         return True
>>> class B(A):
...     pass
>>> A() == B()
<class '__main__.B'> <class '__main__.A'>

However, the docs note that:

"""If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations."""

... which suggests that this reversal should only happen when the subclass B *overrides* A's definition of __eq__ (and indeed that's the usual behaviour for arithmetic operations like __add__).

Looking more closely, that statement in the docs is in the 'numeric-types' section, so it's not clear that its rules should apply to the comparison operators.  But either way, some doc clarification could be useful.

[1] http://stackoverflow.com/q/24919375/270986
[2] https://docs.python.org/3.5/reference/datamodel.html#emulating-numeric-types

assignee: docs at python
components: Documentation
messages: 223778
nosy: docs at python, mark.dickinson
priority: normal
severity: normal
status: open
title: Comparison operators called in reverse order for subclasses with no override.
versions: Python 2.7, Python 3.4, Python 3.5

Python tracker <report at bugs.python.org>

More information about the docs mailing list