Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...