Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python evaluate if's conditions lazily? [duplicate]

For example, if I have the following statement:

if( foo1 or foo2)     ...     ... 

if foo1 is true, will python check the condition of foo2?

like image 379
ogama8 Avatar asked Dec 19 '12 20:12

ogama8


People also ask

Is Python eager or lazy?

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.

Does Python check all conditions?

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() .

How are conditions evaluated with Python?

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.

How do you stop lazy evaluation in Python?

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.


1 Answers

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.

like image 181
unutbu Avatar answered Oct 13 '22 06:10

unutbu