Python: Avoid short circuit evaluation

short circuit evaluation python
short-circuit evaluation c++
short-circuit evaluation example
short circuit evaluation python operators
what is short-circuit evaluation in python? quizlet
short-circuit code in compiler design
python short circuit assignment
python shortcut operators

This is a problem that occured to me while working on a Django project. It's about form validation.

In Django, when you have a submitted form, you can call is_valid() on the corresponding form object to trigger the validation and return a Boolean value. So, usually you have code like that inside your view functions:

if form.is_valid():
    # code to save the form data

is_valid() not only validates the form data but also adds error messages to the form object that can afterwards be displayed to the user.

On one page I use two forms together and also want the data to be saved only if both forms contain valid data. That means I have to call is_valid() on both forms before executing the code to save the data. The most obvious way:

if form1.is_valid() and form2.is_valid():
    # ...

won't work because of the short circuit evaluation of logical operators. If form1 is not valid, form2 will not be evaluated and its error messages would be missing.

That's only an example. As far as I know, there is no greedy alternative to and/or as in other languages (i.e. Smalltalk). I can imagine that problem occurring under different circumstances (and not only in Python). The solutions I could think of are all kind of clumsy (nested ifs, assigning the return values to local variables and using them in the if statement). I would like to know the pythonic way to solve this kind of problems.

Thanks in advance!

How about something like:

if all([form1.is_valid(), form2.is_valid()]):
   ...

In a general case, a list-comprehension could be used so the results are calculated up front (as opposed to a generator expression which is commonly used in this context). e.g.:

if all([ form.is_valid() for form in (form1,form2) ])  

This will scale up nicely to an arbitrary number of conditions as well ... The only catch is that they all need to be connected by "and" as opposed to if foo and bar or baz: ....

(for a non-short circuiting or, you could use any instead of all).

Short Circuiting Techniques in Python, The evaluation of expression takes place from left to right. In python, short circuiting is supported by various boolean operators and functions. The program does not bother with the second statement. If the first value is false, only then Python checks the second value and then result is based on second half. and: For an and expression, Python uses a short circuit technique to check if the first statement is false then the whole statement must be false, so it returns that value. Only if the first value is true, it checks the second statement and returns the value.

You can simply use the binary & operator, which will do a non-short-circuit logical AND on bools.

if form1.is_valid() & form2.is_valid():
   ...

Short circuit evaluation, An and statement stops as soon as if encounters the first False case. Short circuiting to avoid errors. We can often use short circuit evaluation to� Similarly, for an and expression, python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false and it returns that object value (false) else, if the first value is true it checks the second and returns that value.

You can use Clever infix hack for defining your own Boolean operators aand=Infix(lambda x,y: bool(x) and bool(y)) 1 |aand| 2 will return True instead of 1

PEP 532 -- A circuit breaking protocol and binary operators, In the latter two cases, the syntactic form would also avoid evaluating PEP 335 proposed the ability to overload the short-circuiting and and or� Python has a useful feature called short circuit evaluation that acts on logical operators or and and. Subsequent chapters explain how to use Python for data analysis, including Chapter 5 on matplotlib which is the standard graphics package.

Short-circuit evaluation, Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is 3.1 Avoiding undesired side effects of the second argument; 3.2 Idiomatic conditional construct. 4 Possible Python, none, and , or, Last value. In an expression like this, Python uses a methodology called short-circuit evaluation, also called McCarthy evaluation in honor of computer scientist John McCarthy. The xi operands are evaluated in order from left to right. As soon as one is found to be true, the entire expression is known to be true.

Short Circuit Evaluation, Short-circuit evaluation is a strategy most programming languages (including Java) use to avoid unnecessary work. For example, say we had a conditional like � Leave a Comment / Python / By Christian Short circuit evaluation in any programming language is the act of not executing unnecessary parts of a Boolean expression. Say, you want to calculate the result of the expression “A and B” but you already know that “A=False”.

3. Conditionals � Python for person in everybody, Catching exceptions using try and except; Short-circuit evaluation of logical You might want to avoid it until you are sure you know what you are doing. +� Short Circuit Evaluation Short-circuit evaluation is a strategy most programming languages (including Java) use to avoid unnecessary work. For example, say we had a conditional like this: if (itIsFriday && itIsRaining) { System.out.println("board games at my place!");

Comments
  • Exactly what I looked for. Thank you!
  • It took me a few seconds to come up with this. It's a corner case I hadn't considered before (I often work in Fortran which doesn't guarantee short-circuiting, but permits it) and I'm always trying to figure out how to make sure my expressions are short-circuited. Figuring this out was a bit backwards for me :).
  • Yes the all is the way to go here, but where did you use list-comprehensions? I only see a simple list on your example.
  • @rantanplan -- you're right. (oops). I was thinking in the general case a list comprehension could be used. I'll fix that.
  • Also note that the above form can be combined with the solution provided by @BigYellowCactus since any and all return boolean values.
  • More specifically, it will do a bitwise and on integers. Since bools happen to be derived from integers with True == 1 and False == 0, this works. It won't (necessarily) work for other types or for functions which return things which aren't boolean. Still, it's a good tool to have around (+1)
  • Definitely simpler than the solution by mgilson. Thanks for that! The other one might be more helpful for other people reading the code. Here, I guess you could think I just confused and and &.
  • @mgilson The all function was also the first solution that came into my mind (I would use it for exactly the reason j0ker mentioned), but I discoverd the question to late for that answer (+1, btw) :-)
  • One advantage over my solution is that you aren't limited to just and if all your results are boolean (True,False,1 or 0). You can write an expression like if foo() & baz() | bar() which should behave as expected.
  • Contrary to what some of the other comments here say, this answer is completely correct. In fact, this is specifically designed and intended behavior of bools. bool even has its own bool.__and__ that returns True instead of 1 for True & True, and similarly for the other bitwise operators, so it's not just inheriting the int implementation (though it is compatible with the int behavior).