IPython Pygments Lexers
The ipython-pygments-lexers library provides specialized Pygments lexers for syntax highlighting IPython code and interactive sessions. These lexers were originally part of the main IPython project but were later extracted into a dedicated package to reduce IPython's core dependencies. The package is actively maintained, with its current version being 1.1.1, and releases occur infrequently as needed for bug fixes or minor enhancements.
Warnings
- breaking The Pygments lexers for IPython were extracted from the main `IPython` package (specifically `IPython.lib.lexers`) into this separate `ipython-pygments-lexers` package. Direct imports from `IPython.lib.lexers` will fail if IPython 9.0 or newer is used without this package being installed.
- gotcha When using Pygments' `get_lexer_by_name()` or similar lookup functions, the aliases 'ipython' and 'ipython3' may be confusing. Historically, these referred to the `IPyLexer` or `IPythonConsoleLexer`, which handle full console sessions. However, the alias 'ipython' can be misleading as an IPython console session (with prompts/outputs) is distinct from pure IPython code.
Install
-
pip install ipython-pygments-lexers
Imports
- IPythonLexer
from ipython_pygments_lexers import IPythonLexer
- IPythonConsoleLexer
from ipython_pygments_lexers import IPythonConsoleLexer
- IPyLexer
from ipython_pygments_lexers import IPyLexer
Quickstart
from pygments import highlight
from pygments.formatters import HtmlFormatter
from ipython_pygments_lexers import IPyLexer
code_to_highlight = (
"""In [1]: import numpy as np
...: a = np.array([1, 2, 3])
...: print(a * 2)
Out[1]: [2 4 6]
In [2]: %timeit [i**2 for i in range(1000)]
40.7 µs ± 1.15 µs per loop (mean ± Std. dev. of 7 runs, 10000 loops each)
"""
)
lexer = IPyLexer()
formatter = HtmlFormatter()
highlighted_code = highlight(code_to_highlight, lexer, formatter)
print(highlighted_code)