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?
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?
Something missing from the other answers here is that & and | don't have any universal meaning in Python; their meaning depends on the operands' types, using the magic __and__ and __or__ methods. Since these are methods, the operands are both evaluated (i.e. without short-circuiting) before being passed as arguments.
On bool values they are logical "and" and logical "or":
>>> True & False
False
>>> True | False
True
>>> bool.__and__(True, False)
False
>>> bool.__or__(True, False)
True
On int values they are bitwise "and" and bitwise "or":
>>> bin(0b1100 & 0b1010)
'0b1000'
>>> bin(0b1100 | 0b1010)
'0b1110'
>>> bin(int.__and__(0b1100, 0b1010))
'0b1000'
>>> bin(int.__or__(0b1100, 0b1010))
'0b1110'
On sets, they are intersection and union:
>>> {1, 2} & {1, 3}
{1}
>>> {1, 2} | {1, 3}
{1, 2, 3}
>>> set.__and__({1, 2}, {1, 3})
{1}
>>> set.__or__({1, 2}, {1, 3})
{1, 2, 3}
A couple of extra notes:
__and__ and __or__ methods are always looked up on the class, not on the instance. So if you assign obj.__and__ = lambda x, y: ... then it's still obj.__class__.__and__ that's invoked.__rand__ and __ror__ methods on the class will take priority, if they are defined.See the Python language reference for more details.