Short-circuit Logic

Roy Smith roy at panix.com
Sun May 26 07:38:38 EDT 2013


In article <5f101d70-e51f-4531-9153-c92ee2486fd9 at googlegroups.com>,
 Ahmed Abdulshafy <abdulshafy at gmail.com> wrote:

> Hi,
> I'm having a hard time wrapping my head around short-circuit logic that's 
> used by Python, coming from a C/C++ background; so I don't understand why the 
> following condition is written this way!>
> 
>      if not allow_zero and abs(x) < sys.float_info.epsilon:
>                 print("zero is not allowed")
> 
> The purpose of this snippet is to print the given line when allow_zero is 
> False and x is 0.

I don't understand your confusion.  Short-circuit evaluation works in 
Python exactly the same way it works in C.  When you have a boolean 
operation, the operands are evaluated left-to-right, and evaluation 
stops as soon as the truth value of the expression is known.

In C, you would write:

   if (p && p->foo) {
        blah();
    }

to make sure that you don't dereference a null pointer.  A similar 
example in Python might be:

    if d and d["foo"]:
        blah()

which protects against trying to access an element of a dictionary if 
the dictionary is None (which might happen if d was an optional argument 
to a method and wasn't passed on this invocation).

But, none of that applies to your example.  The condition is

    not allow_zero and abs(x) < sys.float_info.epsilon:

it's safe to evaluate "abs(x) < sys.float_info.epsilon" no matter what 
the value of "not allow_zero".  For the purposes of understanding your 
code, you can pretend that short-circuit evaluation doesn't exist!

So, what is your code doing that you don't understand?



More information about the Python-list mailing list