Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/_pytest/_io/terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@
from typing import final
from typing import Literal
from typing import TextIO

import pygments
from pygments.formatters.terminal import TerminalFormatter
from pygments.lexer import Lexer
from pygments.lexers.diff import DiffLexer
from pygments.lexers.python import PythonLexer
from typing import TYPE_CHECKING

from ..compat import assert_never
from .wcwidth import wcswidth


if TYPE_CHECKING:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could leave a note at the global level mentioning that the local imports for pygments are optional, and related to a speed up.

from pygments.formatters.terminal import TerminalFormatter
from pygments.lexer import Lexer


# This code was initially copied from py 1.8.1, file _io/terminalwriter.py.


Expand Down Expand Up @@ -207,13 +207,20 @@ def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> No

def _get_pygments_lexer(self, lexer: Literal["python", "diff"]) -> Lexer:
if lexer == "python":
from pygments.lexers.python import PythonLexer

return PythonLexer()
elif lexer == "diff":
from pygments.lexers.diff import DiffLexer

return DiffLexer()
else:
assert_never(lexer)

def _get_pygments_formatter(self) -> TerminalFormatter:
from pygments.formatters.terminal import TerminalFormatter
import pygments.util

from _pytest.config.exceptions import UsageError

theme = os.getenv("PYTEST_THEME")
Expand All @@ -239,6 +246,8 @@ def _highlight(
if not source or not self.hasmarkup or not self.code_highlight:
return source

import pygments

pygments_lexer = self._get_pygments_lexer(lexer)
pygments_formatter = self._get_pygments_formatter()

Expand Down
Loading