Registry / serialization / Pygments

Pygments

JSON →
library2.21.0pypypi✓ verified 24d ago

Pygments is a generic syntax highlighting library written in Python, supporting over 500 languages and text formats with output in HTML, LaTeX, RTF, SVG, image formats, and ANSI terminal sequences. It can be used both as a library and as the `pygmentize` CLI tool. Current version is 2.19.2. Releases are made periodically with new lexers added each minor version; patch releases fix regressions quickly (2.19.1 and 2.19.2 followed 2.19.0 within weeks).

pip install Pygments
INSTALL
IMPORT
SIG · PYGMENTS
P
Pygments
serializationpythonv2.21.0
Install
2.3s avg
Import
Disk
25MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.21.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.000s · 26.6MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 2.3s · import 0.000s · 27MB
25MB installed
● package 25MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

highlight
from pygments import highlight
Top-level entry point for all highlighting; always import from `pygments` directly.
PythonLexer (and other named lexers)
from pygments.lexers import PythonLexer
from pygments import PythonLexer
All lexer classes live in `pygments.lexers`, not in the top-level `pygments` package.
get_lexer_by_name
from pygments.lexers import get_lexer_by_name
Dynamic lexer lookup by alias string, e.g. 'python'. Raises pygments.util.ClassNotFound on unknown alias.
get_lexer_for_filename
from pygments.lexers import get_lexer_for_filename
Selects lexer by filename pattern. Only uses the primary (unique) filename list; use guess_lexer_for_filename for ambiguous extensions.
guess_lexer
from pygments.lexers import guess_lexer
Analyses text content to pick a lexer. Raises ClassNotFound if no lexer scores above 0. May be slow on large inputs.
HtmlFormatter
from pygments.formatters import HtmlFormatter
from pygments import HtmlFormatter
All formatter classes live in `pygments.formatters`, not the top-level package.
ClassNotFound
from pygments.util import ClassNotFound
Exception raised by all lexer/formatter/style lookup functions when no match is found. Must be caught explicitly.
get_all_styles
from pygments.styles import get_all_styles
Returns an iterator of all built-in and plugin style names. Use instead of STYLE_MAP for complete plugin-aware enumeration.
RegexLexer
from pygments.lexer import RegexLexer
Base class for custom lexer development. Note: singular `pygments.lexer`, not `pygments.lexers`.

Highlight a Python snippet to HTML and print the required CSS alongside it.

from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter from pygments.util import ClassNotFound code = ''' def greet(name: str) -> str: return f"Hello, {name}!" print(greet("World")) ''' try: lexer = get_lexer_by_name('python', stripall=True) except ClassNotFound as e: raise SystemExit(f"Lexer not found: {e}") # cssclass must match the selector passed to get_style_defs formatter = HtmlFormatter(linenos=True, cssclass='highlight', style='default') # highlighted is an HTML snippet — NOT a full document highlighted = highlight(code, lexer, formatter) # get_style_defs() must be called to obtain the CSS; it is NOT embedded by default css = formatter.get_style_defs('.highlight') print(f'<style>\n{css}\n</style>') print(highlighted)
pygmentize --version
Debug
Known issues
gotchaHtmlFormatter output does NOT include CSS by default. The generated HTML uses CSS classes but the stylesheet must be obtained separately via `formatter.get_style_defs('.highlight')` and injected into the page. Without it the output appears unstyled.
fix
Call `HtmlFormatter().get_style_defs('.highlight')` and embed or link the result. Use `HtmlFormatter(full=True)` to get a self-contained HTML document, or `noclasses=True` for inline styles (not recommended for large code blocks).
affects: all
breakingPython 3.7 and below are no longer supported as of Pygments 2.18.0. The `importlib-metadata` backport is no longer required or used. The `pip install Pygments[plugins]` extra is a no-op.
fix
Upgrade to Python >=3.8. Remove any explicit `importlib-metadata` dependency added for Pygments plugin discovery.
affects: <2.18.0
gotchaAll lexer/formatter/style lookup functions (`get_lexer_by_name`, `get_lexer_for_filename`, `get_formatter_by_name`, etc.) raise `pygments.util.ClassNotFound` — not a built-in like `KeyError` or `ValueError` — when no match is found. Uncaught, this crashes silently in many frameworks.
fix
Always wrap lookup calls in `try/except pygments.util.ClassNotFound`. Fall back to `get_lexer_by_name('text')` (the plain-text lexer) for safe passthrough.
affects: all
gotchaPygments provides no execution-time guarantees. Certain inputs (especially adversarial or malformed code) can trigger catastrophic backtracking in lexer regexes, causing the process to hang or consume excessive memory. This is a known DoS vector for web services.
fix
Always enforce a timeout when calling Pygments on untrusted user input (e.g. run in a subprocess with `subprocess.run(..., timeout=5)`). Limit concurrent Pygments processes to avoid resource exhaustion.
affects: all
gotcha`get_lexer_for_filename()` only checks the primary (unique) filename list and can raise `ClassNotFound` for ambiguous extensions like `.html`. `guess_lexer_for_filename()` also checks secondary patterns and runs content analysis, but is slower.
fix
For ambiguous extensions use `guess_lexer_for_filename(filename, content)`. Always catch `ClassNotFound` from both functions.
affects: all
gotchaThe `cssclass` option on `HtmlFormatter` must match the selector prefix passed to `get_style_defs()`. If you set `cssclass='source'` but call `get_style_defs('.highlight')`, the CSS will not apply to the generated markup.
fix
Keep them in sync: `fmt = HtmlFormatter(cssclass='source')` then `fmt.get_style_defs('.source')`. Or rely on the default cssclass `'highlight'` and pass `'.highlight'` to `get_style_defs()`.
affects: all
deprecated`STYLE_MAP` in `pygments.styles` uses an older format and does not include plugin styles. It is kept for backwards compatibility but is incomplete.
fix
Use `from pygments.styles import get_all_styles; list(get_all_styles())` to enumerate all styles including those registered via plugins.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pygments'
The Pygments library is not installed in the current Python environment.
fix
Install Pygments using pip: `pip install pygments`.
ImportError: No module named pygments.styles
The Pygments library is not installed or not accessible in the current Python environment.
fix
Ensure Pygments is installed: `pip install pygments`.
ImportError: No module named 'pygments.lexer'
The Pygments library is not installed or not accessible in the current Python environment.
fix
Ensure Pygments is installed: `pip install pygments`.
ImportError: No module named 'pygments.lexers._asy_builtins'
The Pygments library is not installed or not accessible in the current Python environment.
fix
Ensure Pygments is installed: `pip install pygments`.
ImportError: No module named 'pygments'
The Pygments library is not installed or not accessible in the current Python environment.
fix
Ensure Pygments is installed: `pip install pygments`.
Upgrade
Version history
2.21.0latest on PyPI · released Aug 17, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
80 hits · last 30 days
node
68
OpenAI (training)
1
Resources
Pygments — pip install Pygments · libregistry