Vertical bar in Python bitwise assignment operator

29,747

Solution 1

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

object.attribute = object.attribute | variable

Read more here.

Solution 2

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.

Solution 3

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']}
...
Share:
29,747

Related videos on Youtube

Olga
Author by

Olga

Updated on February 13, 2020

Comments

  • Olga
    Olga over 3 years

    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.

  • user2357112
    user2357112 almost 10 years
    Mostly equivalent - it might be done in-place, depending on the object.