Python: execution order AND

If I have the following:

if a(my_var) and b(my_var): do something 

Can we assume that b() is evaluated only if a() is True ? Or can he do b() ?

Ask, because evaluating b() will throw an exception if a() is False .

+4
source share
4 answers

With great help help() (hah):

 >>> help('and') Boolean operations ****************** or_test ::= and_test | or_test "or" and_test and_test ::= not_test | and_test "and" not_test not_test ::= comparison | "not" not_test ... The expression ``x and y`` first evaluates *x*; if *x* is false, its value is returned; otherwise, *y* is evaluated and the resulting value is returned. ... 

So, if a(my_var) returns False, then the function b will not be called.

+1
source

b() will only be evaluated if a(my_var) True , yes. Short circuit the and operator if a(my_var) false.

From the documentation of Boolean operators :

The expression x and y first evaluates x ; if x is false, its value is returned; otherwise, y is evaluated and the return value is returned.

You can verify this yourself with a function that prints something when called:

 >>> def noisy(retval): ... print "Called, returning {!r}".format(retval) ... return retval ... >>> noisy(True) and noisy('whatever') Called, returning True Called, returning 'whatever' 'whatever' >>> noisy(False) and noisy('whatever') Called, returning False False 

Python considers empty containers and numeric values โ€‹โ€‹0 false:

 >>> noisy(0) and noisy('whatever') Called, returning 0 0 >>> noisy('') and noisy('whatever') Called, returning '' '' >>> noisy({}) and noisy('whatever') Called, returning {} {} 

User classes can implement __nonzero__ hook to return a Boolean flag for the same test or implement __len__ hook if they are a container type; return 0 means that the container is empty and should be considered false.

In a close note, the or operator does the same, but vice versa. If the first expression evaluates to true, the second expression will not evaluate:

 >>> noisy('Non-empty string is true') or noisy('whatever') Called, returning 'Non-empty string is true' 'Non-empty string is true' >>> noisy('') or noisy('But an empty string is false') Called, returning '' Called, returning 'But an empty string is false' 'But an empty string is false' 
+7
source

Yes, it is safe. Pythons, if conditions are lazily evaluated.

+1
source

The compiler always reads from top to bottom and from left to right. So, If False and True , then False is first encountered by the compiler, and it exits the if condition. This is true for all the programs that I know of.

0
source

Source: https://habr.com/ru/post/1487440/


All Articles