Heapq Priority Queue With Stable Tie Breaks
Push (priority, seq, task) tuples with heapq so equal priorities pop in insertion order and non-comparable task objects never enter the comparison.
Code
import heapq
from itertools import count
# (priority, seq, task):seq 是单调递增计数器
# 同优先级时元组比较落到 seq 上,平局(tie)按插入顺序决出,出队稳定(stable)
seq = count()
tasks = []
heapq.heappush(tasks, (3, next(seq), "email digest"))
heapq.heappush(tasks, (1, next(seq), "payment webhook"))
heapq.heappush(tasks, (1, next(seq), "retry upload"))
heapq.heappush(tasks, (2, next(seq), "cache warmup"))
# 数值越小越先出队;两个优先级 1 的任务保持入队顺序
while tasks:
priority, ordinal, task = heapq.heappop(tasks)
print(f"pop {priority} #{ordinal} {task}")
# 直接比较 (priority, task) 会按字母序打破平局,task 不可比较时还会 TypeErrorOutput
Captured from a sandboxed run of this snippet in the build pipeline.
pop 1 #1 payment webhook
pop 1 #2 retry upload
pop 2 #3 cache warmup
pop 3 #0 email digestHow it works
while tasks is the loop that carries the per-item work. Everything borrowed from heapq is visible in one line: count.
The demo data lives in module-level bindings: seq, tasks.
Points of care
- Requires
heapqas a package; the snippet will not run without it.
Putting it to use
Running the file prints labeled results such as pop — each operation’s effect is visible in the output.
Core lines
while tasks:
priority, ordinal, task = heapq.heappop(tasks)
print(f"pop {priority} #{ordinal} {task}")
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Every import resolves inside the standard library — `heapq`, `itertools`. Its state lives in module-level bindings: `seq`, `tasks`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.