Typing Stubs for CommonMark
types-commonmark provides official typing stubs for the `commonmark` Python library, enabling static type checkers like MyPy and Pyright to analyze `commonmark` code with full type information. This package is part of the `typeshed` project. The current version is 0.9.2.20250330, with releases typically tied to `commonmark` updates or `typeshed` maintenance cycles.
Common errors
-
ModuleNotFoundError: No module named 'types_commonmark'
cause Attempting to import a runtime object directly from the `types-commonmark` stub package.fixDo not import from `types_commonmark`. Import from the `commonmark` library instead (e.g., `from commonmark import Parser`). The stub package is solely for static analysis tools. -
error: Cannot find type definition file for 'commonmark' (reportMissingTypeStubs) (from Pyright/MyPy)
cause The `commonmark` library is installed, but its corresponding type stubs (`types-commonmark`) are missing, leading to incomplete type information for type checkers.fixInstall the `types-commonmark` stub package: `pip install types-commonmark`
Warnings
- gotcha `types-commonmark` provides type stubs for static analysis only; it does not contain runtime code. Attempting to import objects directly from `types_commonmark` will result in a `ModuleNotFoundError`.
- gotcha Ensure that the version of `types-commonmark` is compatible with your installed `commonmark` library version. Mismatched versions can lead to incorrect or missing type hints, or even runtime errors if `commonmark` APIs change significantly.
- gotcha After installing `types-commonmark`, you need a static type checker (e.g., MyPy, Pyright, or Ruff's type checking rules) configured in your project to actually benefit from the type stubs. Without a type checker, the stubs have no effect.
Install
-
pip install types-commonmark -
pip install commonmark types-commonmark
Imports
- No direct runtime imports
from types_commonmark import SomeClass
N/A - `types-commonmark` provides type stubs for static analysis, not runtime code.
Quickstart
import commonmark
from commonmark.node import Node
def process_markdown(text: str) -> str:
"""Parses markdown and renders it to HTML."""
parser = commonmark.Parser()
renderer = commonmark.HtmlRenderer()
# The type checker (e.g., MyPy) will use types-commonmark
# to understand that 'root_node' is a Node object, and 'render' returns str.
root_node: Node = parser.parse(text)
html_output: str = renderer.render(root_node)
return html_output
markdown_text = "# Hello, Markdown!\n\nThis is some *formatted* text."
html = process_markdown(markdown_text)
print(html)
# Expected output (simplified example based on commonmark rendering):
# <h1>Hello, Markdown!</h1>
# <p>This is some <em>formatted</em> text.</p>