← All lints

while_not_empty_pop

L0591Idiomswarn

Empty test, then unwrapped pop

while not q.is_empty: then let x = q.pop()!: while let x = q.pop():

Flagged
var q = [3, 1, 2]
var total = 0
while not q.is_empty:
    let x = q.pop()!
    total += x
print(total)
Write instead
var q = [3, 1, 2]
var total = 0
while let x = q.pop():
    total += x
print(total)

Why

C++ drains a queue with while (!q.empty()) { auto x = q.top(); q.pop(); ... }, because pop returns nothing. In CP Lang pop() returns the element it takes, or None when the collection is empty, so the emptiness test and the ! that unwraps the pop say the same fact twice: while not q.is_empty: then let x = q.pop()!. while let x = q.pop(): says it once. It stops on the same None the test guarded against, and an edit can no longer move the test away from the pop. It works for every collection whose pop (or pop_front, pop_min, ...) returns an optional: List, Deque and the heaps, and for a tuple pattern such as while let (d, u) = pq.pop():. The lint fires only when the let is the loop's first statement and pops the same name or field path the condition tests (not q.is_empty, q.len > 0 or q.len != 0). The fix rewrites the condition and deletes the let line.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
var q = [3, 1, 2]
var other = [5]
var total = 0
// The test and the pop name different lists: nothing is said twice.
while not other.is_empty:
    let x = q.pop()!
    total += x
    other.pop()
// The pop is not the first thing the loop does.
while not q.is_empty:
    total += 1
    let y = q.pop()!
    total += y
print(total)

Turn it off

For one block, wrap it in with lint(while_not_empty_pop: allow):. For a project, add while_not_empty_pop = "allow" under [lints] in cp.toml.

Generated from spec/lints/while_not_empty_pop, the same record the linter is built from.