selfboot / AnnotatedShadowSocks

Annotated shadowsocks(python version)
Other
3 stars 1 forks source link

What does else after for and while loops mean? #29

Open selfboot opened 7 years ago

selfboot commented 7 years ago

In function daemon.py/daemon_stop, we can see:

# sleep for maximum 10s
for i in range(0, 200):
    try:
        # query for the pid
        os.kill(pid, 0)
    except OSError as e:
        if e.errno == errno.ESRCH:
            break
    time.sleep(0.05)
# Look at here
else:
    logging.error('timed out when stopping pid %d', pid)
    sys.exit(1)

The for...else and while...else syntax is one of the most under-used and misunderstood syntactic features in Python, this is a strange construct even to seasoned Python coders.

Python doc says:

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

The primary use-case of for...else is to implement searching:

for item in sequence:
    if item == target:
        print "found"
        break
else:
    print "not found"

If there is no break in the loop, the else clause is functionally redundant. That is, the following two code snippets behave identically:

for item in sequence:
    process(item)
else:
    other()

and:

for item in sequence:
    process(item)
other()

Ref
break and continue Statements, and else Clauses on Loops
[Python-ideas] Summary of for...else threads
Why does python use 'else' after for and while loops?

mrspucches commented 7 years ago

The 'else' clause executes when the loop completes normally. Which means the loop didn't encounter any breaks. Hopefully this makes more sense. So the for loop executes its code then it moves onto the else statement then repeats. If the for loop encounters any breaks the else clause will not execute.