Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of Python's built-in bool method __ror__?

In the interactive interpreter, if you type the following in order you can see some pretty interesting stuff:

1) help()

2) modules

3) __builtin__

When reading through the output for awhile I came across these lines in class bool:

__or__(...)
    x.__or__(y) <==> x|y

and then later on:

__ror__(...)
    x.__ror__(y) <==> y|x

This last method appears to describe reverse or. Why does this method exist? What could possibly cause __or__(...) to return anything different than __ror__(...)?

like image 927
user3745189 Avatar asked Aug 08 '14 20:08

user3745189


1 Answers

Suppose you write your own integer class, and you want it to work with the built-in integers. You might define __or__

class MyInt(int):

    def __or__(self, other):
        # Not a recommended implementation!
        return self | int(other)

so that you can write code like

# Because this is equivalent to MyInt.__or__(MyInt(6), 7)
MyInt(6) | 7

However, Python wouldn't know what to do with

# First interpretation is int.__or__(7, MyInt(6))
7 | MyInt(6)

because int.__or__ wouldn't know how to work with an instance of MyInt. In such a case, Python swaps the order of the operands and tries

MyInt.__ror__(MyInt(6), 7)

that is, looks for the swapped version of the magic method in the class of the right-hand argument.

like image 195
chepner Avatar answered Sep 28 '22 02:09

chepner