Does Python Evaluate If's Conditions Lazily

Does Python evaluate if's conditions lazily?

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.

Does Python Check ALL conditions in an multi-condition if statement?

Yes, python boolean operators do short-circuit

Both code samples are semantically equivalent, but the first is more readable, as it has lower level of nesting.

Python lazy multiple conditions check

Your best bet is to continue what you're doing — but put your fastest conditions to check first.

all() will short-circuit, meaning that as soon as a condition evaluates to False, it will stop processing conditions, saving you the time you would expend by running the other queries.

As for what looks best — that's up to you. But it's far better to have effective, readable code than "attractive" code! And short code isn't always better. Verbosity often makes code more readable to others.

Just be careful. For example, if subsequent conditions are dependent on the first, using all can break. For example, given x='6.5', if isinstance(x, float) and x>5.5 would work but all((isinstance(x, float), x>5.5)) would error.

Is any() evaluated lazily?

Yes, any() and all() short-circuit, aborting as soon as the outcome is clear: See the docs:

all(iterable)

Return True if all elements of the iterable are true (or if the
iterable is empty). Equivalent to:

def all(iterable):
for element in iterable:
if not element:
return False
return True

any(iterable)

Return True if any element of the iterable is true. If the iterable is
empty, return False. Equivalent to:

def any(iterable):
for element in iterable:
if element:
return True
return False

Does python stop verification on first wrong condition in if and or does it check it all before deciding?

It doesn't matter, because Python supports short-circuit evaluation:

Does Python support short-circuiting?

Does Python have a ternary conditional operator?

Yes, it was added in version 2.5. The expression syntax is:

a if condition else b

First condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored.

This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.

For example:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

Note that conditionals are an expression, not a statement. This means you can't use statements such as pass, or assignments with = (or "augmented" assignments like +=), within a conditional expression:

>>> pass if False else pass
File "<stdin>", line 1
pass if False else pass
^
SyntaxError: invalid syntax

>>> # Python parses this as `x = (1 if False else y) = 2`
>>> # The `(1 if False else x)` part is actually valid, but
>>> # it can't be on the left-hand side of `=`.
>>> x = 1 if False else y = 2
File "<stdin>", line 1
SyntaxError: cannot assign to conditional expression

>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
File "<stdin>", line 1
(x = 1) if False else (y = 2)
^
SyntaxError: invalid syntax

(In 3.8 and above, the := "walrus" operator allows simple assignment of values as an expression, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)

Similarly, because it is an expression, the else part is mandatory:

# Invalid syntax: we didn't specify what the value should be if the 
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True

You can, however, use conditional expressions to assign a variable like so:

x = a if True else b

Or for example to return a value:

# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
return a if a > b else b

Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will do the same thing with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to do something different depending on the condition, then use a normal if statement instead.


Keep in mind that it's frowned upon by some Pythonistas for several reasons:

  • The order of the arguments is different from those of the classic condition ? a : b ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order).
  • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic reasons. (Although the 'inline if' can be really useful, and make your script more concise, it really does complicate your code)

If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

Official documentation:

  • Conditional expressions
  • Is there an equivalent of C’s ”?:” ternary operator?

How does this casting assignment work?

condition1 and condition2.

condition2 is executed only if the condition1 passes. If n resolves to a True in Boolean context then n is converted to int by the statement int(n) and assigned to n

In context of Boolean operations the following are considered as false
- False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and
frozensets)

From doc

Python: how if is handled?

and is a short-circuit operator.

The second argument is evaluated if the first one is True. Similarly, for the subsequent arguments.



Related Topics



Leave a reply



Submit