Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python equality precedence

class L(object):
    def __eq__(self, other):
        print 'invoked L.__eq__'
        return False

class R(object):
    def __eq__(self, other):
        print 'invoked R.__eq__'
        return False

left = L()
right = R()

With this code, left side gets the first shot at comparison, as documented in the data model:

>>> left == right
invoked L.__eq__
False

But if we make a slight modification on line 6 (everything else the same):

class R(L):

Now the right side gets to have the first shot at comparison.

>>> left == right
invoked R.__eq__
False

Why is that? Where is it documented, and what's the reason for the design decision?

like image 258
wim Avatar asked Dec 31 '15 09:12

wim


People also ask

What is the correct precedence order in Python?

Answer: The correct order of precedence is given by PEMDAS which means Parenthesis (), Exponential **, Multiplication *, Division /, Addition +, Subtraction -.

Which has highest precedence in Python?

Python follows the same precedence rules for its mathematical operators that mathematics does. Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8.

Do all comparison operators have the same precedence in Python?

All comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.


1 Answers

This is documented under the numeric operations, further down the page, with an explanation for why it works that way:

Note: 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.

The Python 3 documentation additionally mentions it in the section you were looking at:

If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.

like image 85
user2357112 supports Monica Avatar answered Oct 25 '22 11:10

user2357112 supports Monica