The canonical JWZ email message-threading algorithm with RFC 5322 identification-field parsing — pure stdlib, no runtime dependencies.
Maintained. Last release 5 months ago, commits in 6 of the last 26 weeks. Weaker on release cadence and contributor spread.
pip install threadweavethreadweave
The canonical JWZ email message-threading algorithm for Python — pure stdlib, zero runtime dependencies.
threadweave turns a flat list of email messages into conversation trees using
Jamie Zawinski's threading algorithm,
built on top of RFC 5322 §3.6.4 identification-field parsing (Message-ID,
References, In-Reply-To). It is the algorithm every serious mail client uses
to group a mailbox into threads.
It exists because the obviously-wrong approaches — grouping by subject alone, or
naively chaining In-Reply-To — mis-thread real mail: subjects collide across
unrelated conversations, references arrive out of order, roots go missing, and
malformed headers form reference loops. JWZ handles all of these; threadweave
implements it faithfully and loop-safely.
What it does
- Builds the JWZ id-table of containers and links
Referenceschains without creating loops and without overriding a message's good existing parent. - Recovers missing roots as empty placeholder containers, then prunes empty containers correctly (nuking childless empties and splice-promoting the children of empty ones, with the special root-level single-child handling).
- Optionally groups the root set by base subject (
Re:/Fwd:/Fw:stripped) — a heuristic, off by default. - Terminates on adversarial input: self-references and mutual reference cycles never loop or crash.
Install
pip install threadweave
No runtime dependencies — only the standard library (re, hashlib,
dataclasses, typing).
Quickstart
from threadweave import Message, thread_messages
threads = thread_messages([
Message(message_id="a", subject="Deploy plan"),
Message(message_id="b", in_reply_to="a", references=["a"], subject="Re: Deploy plan"),
Message(message_id="c", references=["a", "b"], subject="Re: Deploy plan"),
])
assert len(threads) == 1 # one conversation
root = threads[0] # a Container
print(root.message.message_id) # "a"
for node in root.iter_descendants():
print(node.message.message_id) # "b", then "c"
Group unrelated-but-same-subject roots when references are missing: