2

I'm optimizing the performance of some Python code and once read that "obsolete" code in boolean expressions is not executed to save computing time. So I've created the following test program:

def fun(p):
    print p
    return False

if fun(1) and fun(2):
    print "This shouldn't print"

This code only prints one line.

1

So fun(2) is not called, because it won't change the result of the "and".

I'd like to learn more about this feature, but I don't know the right name/term to search for. What's this feature called?

Alen
  • 197
  • 1
  • 2
  • 8
  • http://stackoverflow.com/questions/2580136/does-python-support-short-circuiting – stark Mar 12 '15 at 19:28
  • 3
    It's called [Short Circuit Evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation). – aruisdante Mar 12 '15 at 19:28
  • @avim not quite. [Lazy Evaluation](http://en.wikipedia.org/wiki/Lazy_evaluation) is a related but distinct term. More specifically, Short-Circuit is a specific case of the general lazy evaluation. Many languages only support lazy evaluation of operands in the case of short circuit operators (C/++, Java, Python, etc.), vs. a language like Haskell that has all operands lazy-evaluated by default. – aruisdante Mar 12 '15 at 19:31

0 Answers0