← All lints

push_pop_pair

L0575Idiomswarn

Push then pop on a heap

h.push(x) then h.pop()!: h.push_pop(x) (std.heap)

Flagged
var h = MinHeap<Int>()
h.push(5)
for x in [3, 8, 1]:
    h.push(x)
    let y = h.pop()!
    print(y)
Write instead
var h = MinHeap<Int>()
h.push(5)
for x in [3, 8, 1]:
    let y = h.push_pop(x)
    print(y)

Why

h.push(x) and then h.pop()! sifts the new element up and then the root down, and the ! asks a question whose answer is known: the heap can't be empty just after a push. h.push_pop(x) (std.heap) does both in one sift and returns the smaller of x and the old top, so x itself comes back in O(1)O(1) when it is no greater than the top. The result is the same, so the fix is mechanical.

The practice it serves

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

Not flagged

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

Near miss
var h = MinHeap<Int>()
var xs = [5]
for x in [3, 8, 1]:
    xs.push(x)
    let z = xs.pop()!
    h.push(x)
    print(z)
    let y = h.pop()!
    print(y)

Turn it off

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

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