Vertical bar in Python bitwise assignment operator

Question:

There is a code and in class’ method there is a line:

object.attribute |= variable

I can’t understand what it means. I didn’t find (|=) in the list of basic Python operators.

Asked By: Olga

||

Answers:

That is a bitwise or with assignment. It is equivalent to

object.attribute = object.attribute | variable

Read more here.

Answered By: Elliott Frisch

In python, | is short hand for calling the object’s __or__ method, as seen here in the docs and this code example:

class Object(object):
    def __or__(self, other):
        print("Using __or__")

Let’s see what happens when use | operator with this generic object.

In [62]: o = Object()

In [63]: o | o
using __or__

As you can see the, the __or__ method was called. int, ‘set’, ‘bool’ all have an implementation of __or__. For numbers and bools, it is a bitwise OR. For sets, it’s a union. So depending on the type of the attribute or variable, the behavior will be different. Many of the bitwise operators have set equivalents, see more here.

Answered By: Alejandro

For an integer this would correspond to Python’s “bitwise or” method. So in the below example we take the bitwise or of 4 and 1 to get 5 (or in binary 100 | 001 = 101):

Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
    >>> a = 4
    >>> bin(a)
    '0b100'
    >>> a |= 1
    >>> bin(a)
    '0b101'
    >>> a
    5

More generalised (as Alejandro says) is to call an object’s or method, which can be defined for a class in the form:

def __or__(self, other):
    # your logic here
    pass

So in the specific case of an integer, we are calling the or method which resolves to a bitwise or, as defined by Python.

Answered By: Sami Start

I should add that “bar-equals” is now (in 2018) most popularly used as a set-union operator to append elements to a set if they’re not there yet.

>>> a = {'a', 'b'}
>>> a
set(['a', 'b'])

>>> b = {'b', 'c'}
>>> b
set(['c', 'b'])

>>> a |= b
>>> a
set(['a', 'c', 'b'])

One use-case for this, say, in natural language processing, is to extract the combined alphabet of several languages:

alphabet |= {unigram for unigram in texts['en']}
alphabet |= {unigram for unigram in texts['de']}
...
Answered By: russian_spy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.