开发者

multiple and/or in an expression

foo() is NOT defined.

>>> 0 and foo()                   (1)
0                                     # trivial 

>>> 0 and foo() or 1              (2) # expecting it as 0 and (foo() or 1)
1                                     # does NOT short-circuit on 0

>>> 1 or foo()                    (3) # trivial
1

>>> 1 or foo() and 0              (4) # expecting it as 1 or (foo() and 0)
1                                     # DOES short-circuit on 1

I don't see a consistent behavior from (2) and (4).

CASE 1

if we go by (2)'s evaluation style:

0 and foo() or 1
false or true (1)
true (1)

then I expect (4) as:

1 or foo() and 0
true and false (0)
false 开发者_运维知识库(0)

CASE 2

if we go by (4)'s evaluation style:

1 or foo() and 0
true or ...
true (1)

then I expect (2) as:

0 and foo() or 1
false and ...
false (0)


and has higher precedence than or.

(2)

0 and foo() or 1 == (0 and foo()) or 1
                 == 0 or 1  # short-circuited, foo() never evaluated
                 == 1

(4)

1 or foo() and 0 == 1 or (foo() and 0)
                 == 1       # short-circuited, foo() never evaluated


Check precedence: http://docs.python.org/reference/expressions.html#summary

it'll evaluate and before or on every case.

1 or 2 and 3 == 1 or (2 and 3)


You problem comes because you believe that and and or are merely right-associative, and that there is no precedence between them.

and is evaluated before or.

1 and 2 or 3 --> 2

1 or 2 and 3 --> 1

>>> def foo():
...   print 'foo'
...   return 0
...
>>> def bar():
...   print 'bar'
...   return 1
...
>>> def baz():
...   print 'baz'
...   return 2
...
>>> foo() and bar() or baz()
foo
baz
2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜