Where are the ampersand and vertical bar characters used in Python?

Yktula picture Yktula · Jun 27, 2011 · Viewed 55k times · Source

In the Wikipedia page describing short-circuit evaluation, & and | are listed as eager operators in Python. What does this mean and when are they used in the language?

Answer

Lauritz V. Thaulow picture Lauritz V. Thaulow · Jun 27, 2011

The wikipedia page is wrong, I've corrected it. | and & are not boolean operators, even though they are eager operators, which just means that they are not short circuit operators. As you probably know, here's how the python and and or operators work:

>>> def talk(x):
...     print "Evaluating: ", bool(x)
...     return x
... 
>>> talk(1 == 1) or talk(2 == 1)   # 2 == 1 is not evaluated
Evaluating:  True
True
>>> talk(1 == 1) and talk(2 == 1)
Evaluating:  True
Evaluating:  False
False
>>> talk(1 == 2) and talk(1 == 3)  # 1 == 3 is not evaluated
Evaluating:  False
False

As far as I know, python has no eager boolean operators, they would have to be explicitly coded, for instance like this:

>>> def eager_or(a, b):
...    return a or b
...
>>> eager_or(talk(1 == 1), talk(2 == 1))
Evaluating:  True
Evaluating:  False
True

Now a and b are automatically evaluated when the function is called, even though or still short circuits.

As for the usage of | and &, when used with numbers, they are binary operators:

>>> bin(0b11110000 & 0b10101010)
'0b10100000'
>>> bin(0b11110000 | 0b10101010)
'0b11111010'

You're most likely to use | this way with python bindings to libraries that uses flags, like wxWidgets:

>>> frame = wx.Frame(title="My Frame", style=wx.MAXIMIZE | wx.STAY_ON_TOP)
>>> bin(wx.MAXIMIZE)
'0b10000000000000'
>>> bin(wx.STAY_ON_TOP)
'0b1000000000000000'
>>> bin(wx.MAXIMIZE | wx.STAY_ON_TOP)
'0b1010000000000000'

When used with sets, they do the intersection and union operations, respectively:

>>> set("abcd") & set("cdef")
set(['c', 'd'])
>>> set("abcd") | set("cdef")
set(['a', 'c', 'b', 'e', 'd', 'f'])