DEV Community

Cover image for Processing Markdown in Python using available CommonMark implementations: cmarkgfm, paka.cmark, and mistletoe
Jonathan Bowman
Jonathan Bowman

Posted on

Processing Markdown in Python using available CommonMark implementations: cmarkgfm, paka.cmark, and mistletoe

Markdown is "just enough markup" to write most of the documents I write, and is very readable for humans. (Aside: it is good to have a cheatsheet handy while typing!)

I have appreciated the Markdown standardization efforts of the group working on the CommonMark spec. Thankfully, many languages have a variety of Commonmark implementations, including Python.

Here are three I have found valuable, with a brief description about the why and when you might use each.

cmarkgfm

Simple, fast, stable, and works on Windows as well as Linux, Mac, and other platforms. It also supports GitHub Flavored Markdown. Try this one first; it is likely all you need.

paka.cmark

This one is fast, configurable, and does not generally work on Windows. The maintainer is active, and keeps the project updated. Use this if you only need it to work on Linux and Mac, and especially if you want low-level access to the parser, for customization.

mistletoe

Unlike the others listed above, mistletoe is written in pure Python, so is a good candidate for pypy or if you want ease of installation/configuration and don't require the utmost in speed.

Try them all!

import cmarkgfm
import paka.cmark
import mistletoe

MARKDOWN = "**Hello**, _World_"

print(cmarkgfm.markdown_to_html(MARKDOWN))
print(paka.cmark.to_html(MARKDOWN))
print(mistletoe.markdown(MARKDOWN))
Enter fullscreen mode Exit fullscreen mode

Here is an idea for a module-agnostic implementation that will succeed if any of the above are installed:

try:
    from cmarkgfm import markdown_to_html as md_to_html
except ModuleNotFoundError:
    try:
        from paka.cmark import to_html as md_to_html
    except ModuleNotFoundError:
        from mistletoe import markdown as md_to_html

MARKDOWN = "**Hello**, _World_"

print(md_to_html(MARKDOWN))
Enter fullscreen mode Exit fullscreen mode

Enjoy!

Top comments (0)