Markdown Parser Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Markdown Parser runs in O(n) time and O(n) space, in Python as in every other language.
- ✓unicodedata.category is the one standard-library function a CommonMark implementation genuinely cannot do without: the flanking test needs the general category of a single character on each side of every delimiter run, and current CommonMark counts the Unicode P and S categories as punctuation.
- ✓Declare the delimiter node as a dataclass with slots=True and a reviewer stops arguing. Label normalisation must call str.casefold rather than str.lower, because the spec matches labels by Unicode case fold: casefold turns Straße into strasse so it matches STRASSE, while lower leaves the sharp s alone and the two labels never meet.
- ✓The Python trap: Python's re has no Unicode property escapes at all. re.compile(r"\p{P}") does not match punctuation, it raises re.error with the message bad escape \p.
- ✓Every str slice copies, so a scanner that writes line = line[indent:] once per open container per line turns a linear pass into a pile of allocations; carry the offset instead.
What Markdown Parser actually is
Markdown Parser in Python: what you actually reach for
Python implementation
import unicodedata
from dataclasses import dataclass
def is_md_punct(ch: str) -> bool:
# Current CommonMark counts the Unicode P and S general categories.
# re has no \p{...} escape, so this test cannot be written as a pattern.
return unicodedata.category(ch)[0] in ("P", "S")
@dataclass(slots=True)
class Run:
start: int
length: int
marker: str
can_open: bool
can_close: bool
def scan_runs(text: str) -> list[Run]:
runs: list[Run] = []
i, n = 0, len(text)
while i < n:
ch = text[i]
if ch not in "*_":
i += 1
continue
j = i
while j < n and text[j] == ch:
j += 1
before = text[i - 1] if i else "\n"
after = text[j] if j < n else "\n"
bw, aw = before.isspace(), after.isspace()
bp, ap = is_md_punct(before), is_md_punct(after)
left = not aw and (not ap or bw or bp)
right = not bw and (not bp or aw or ap)
if ch == "*":
runs.append(Run(i, j - i, ch, left, right))
else: # an underscore may not open or close inside a word
runs.append(Run(i, j - i, ch, left and (not right or bp),
right and (not left or ap)))
i = j
return runs
for r in scan_runs("«*naïve*» and snake_case_word"):
print(r)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Markdown Parser?
unicodedata.category is the one standard-library function a CommonMark implementation genuinely cannot do without: the flanking test needs the general category of a single character on each side of every delimiter run, and current CommonMark counts the Unicode P and S categories as punctuation. Around it sit str.casefold for label matching, html.escape for output, and re for the block-level line patterns. No markdown module exists anywhere in CPython. The maintained CommonMark-conformant package is markdown-it-py, a port of markdown-it; the older markdown package implements a different, pre-CommonMark dialect and will disagree on emphasis.
What is the most common Python mistake when implementing Markdown Parser?
Python's re has no Unicode property escapes at all. re.compile(r"\p{P}") does not match punctuation, it raises re.error with the message bad escape \p. The reflex fix is string.punctuation, which is thirty-two ASCII characters, and that silently rewrites the flanking rules. Take the input *foo»*bar: with real general categories the closing run is preceded by a punctuation character and followed by a letter, so it cannot close and both asterisks stay literal. With string.punctuation the guillemet is not punctuation, the run becomes a valid closer, and emphasis appears where the spec says there is none. Nothing raises; ASCII fixtures never catch it.
How does Markdown Parser actually perform in Python?
Every str slice copies, so a scanner that writes line = line[indent:] once per open container per line turns a linear pass into a pile of allocations; carry the offset instead. The node representation matters at delimiter volume: measured on this interpreter a five-field dataclass instance is 72 bytes with slots=True, against 48 bytes plus a 296-byte instance dictionary without. unicodedata.category is a C call of tens of nanoseconds, fine per delimiter and ruinous per character, so gate it behind an ASCII test. The recursion limit defaults to 1000 frames, which deeply nested block quotes will reach. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.