For example, if I have the following statement:
if( foo1 or foo2) ... ...
if foo1 is true, will python check the condition of foo2?
In fact, Python is, for the most part, an eagerly evaluated programming language. It does support lazy evaluation to some extent though in the form of lambda functions, generators, and the short-circuiting that we just talked about.
Python will lazily evaluate the boolean conditions left to right in an if statement. If condition_1() is False , it will not try to evaluate condition_2() .
In Python, conditional expression is written as follows. The condition is evaluated first. If condition is True , X is evaluated and its value is returned, and if condition is False , Y is evaluated and its value is returned. If you want to switch the value by the condition, simply describe each value as it is.
If possible I would like to make the property even more lazy in that it should evaluate only when actually read. The only way to make it lazier is to make it a function that bar knows to call when necessary. Function arguments are always evaluated immediately.
Yes, Python evaluates boolean conditions lazily.
The docs say,
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.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With