You'd just execute the conditions first, before testing with and
:
# explicitly execute the conditions first, compare the outcomes later
test1, test2 = x == 2, myList.pop() == 3
if test1 and test2:
For your case that can be simplified down to just the myList.pop()
call:
# explicitly pop a value from myList, regardless of what x == 2 returns
myList_value = myList.pop()
if x == 2 and myList_value == 3:
Of course, you could also just have swapped the tests:
if myList.pop() == 3 and x == 2:
to ensure that the list.pop()
method is always executed.
Otherwise, the &
bitwise operator is overloaded for Python booleans just like it is in Java:
>>> from itertools import product
>>> for a, b in product([False, True], repeat=2):
... print('{a!r:5} and {b!r:5}: {o1!r:5} {a!r:5} & {b!r:5}: {o2!r:5}'.format(a=a, b=b, o1=a and b, o2=a & b))
...
False and False: False False & False: False
False and True : False False & True : False
True and False: False True & False: False
True and True : True True & True : True
And as such you can use it to avoid short-circuiting, but only if both operands are booleans:
>>> def foo():
... print 'called!'
... return False
...
>>> def bar():
... print 'also called!'
... return False
...
>>> foo() and bar()
called!
False
>>> foo() & bar()
called!
also called!
False
However, I'd consider making use of this unpythonic, and indicative of bad coding style. Restructure your code to not have to rely on this in the first place.