hello, I found the source code of the function and
but not for &
as I want to see why the truthfulness of only left condition is evaluated in case of and
but did not find anything for it. Could someone please help?
and
is a logical operation. It returns True
if both of the operands are true.
&
is a bitwise operator, performing a bit-by-bit operation.
Consider 42 and 24
. If 42
was False
(which it can’t be), the evaluation would stop. This is known as “lazy evaluation”. But the first statement is True
, so the second statement is evaluated; which in this case is also True
, so that is what will be returned.
Now, consider 42 & 24
:
42 - 101010
24 - 011000
& - 001000
001000 - 8
Just to add: I see, from the excellent post by @jeff5, that my answer is maybe not what you were looking for, but I’ll leave it posted; it could be of use to someone.
You may have found the source code for &
, for some type, but you can’t have found the source code for and
. In operator &
both arguments will be evaluated and dealt with as @rob42 explained.
The compiler deals with and
so that you get the short-circuit evaluation like this (varies with version of CPython):
>>> prog = """
if a and b():
print("hello")
print("world")
"""
>>> dis(compile(prog, '', 'exec'))
2 0 LOAD_NAME 0 (a)
2 POP_JUMP_IF_FALSE 18
4 LOAD_NAME 1 (b)
6 CALL_FUNCTION 0
8 POP_JUMP_IF_FALSE 18
3 10 LOAD_NAME 2 (print)
12 LOAD_CONST 0 ('hello')
14 CALL_FUNCTION 1
16 POP_TOP
4 >> 18 LOAD_NAME 2 (print)
20 LOAD_CONST 1 ('world')
22 CALL_FUNCTION 1
24 POP_TOP
26 LOAD_CONST 2 (None)
28 RETURN_VALUE
If a
is false, b()
is never called.
Have a look at the __and__
magic method: Python __and__() Magic Method – Finxter
In almost all languages, boolean operations like ‘and’ or ‘&&’ are ‘short circuit’, AKA ‘lazy’. Usually, this is done with a slightly ugly hack to get laziness for just ‘and’ and ‘or’, though there does exist at least one language that is lazy all over: Haskell. Making a language lazy throughout is a lot of work, and not necessarily a good thing because it’s hard for the developer to reason about.
Python has lazy boolean operators and generators.