Skip to content

Color printer

color_printer

ColorPrinter dataclass

Bases: BasePrinter

A printer for printing colored text to a terminal window. Colors are set by calling the colored context manager.

Source code in xdsl/utils/color_printer.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@dataclass(eq=False, repr=False)
class ColorPrinter(BasePrinter):
    """
    A printer for printing colored text to a terminal window.
    Colors are set by calling the `colored` context manager.
    """

    _in_color_block: bool = field(default=False, init=False)

    @contextmanager
    def colored(self, color: Colors | None):
        """
        No-op if given color is None or the printer is already in a color block.
        Otherwise, anything printed in this context manager will be printed in
        the given color.

        When nesting this context manager, the color is determined by the outermost
        call. For example:
        ```python
        with printer.colored(Colors.BLUE):
            with printer.colored(Colors.RED):
                printer.print_string("test")
        ```
        will print "test" in blue, and not red.
        """

        if self._in_color_block or color is None:
            yield
        else:
            self._in_color_block = True
            print(color, end="", file=self.stream)
            yield
            print(RESET, end="", file=self.stream)
            self._in_color_block = False

__init__(stream: IO[str] | None = None, *, indent_num_spaces: int = 2) -> None

colored(color: Colors | None)

No-op if given color is None or the printer is already in a color block. Otherwise, anything printed in this context manager will be printed in the given color.

When nesting this context manager, the color is determined by the outermost call. For example:

with printer.colored(Colors.BLUE):
    with printer.colored(Colors.RED):
        printer.print_string("test")

will print "test" in blue, and not red.

Source code in xdsl/utils/color_printer.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@contextmanager
def colored(self, color: Colors | None):
    """
    No-op if given color is None or the printer is already in a color block.
    Otherwise, anything printed in this context manager will be printed in
    the given color.

    When nesting this context manager, the color is determined by the outermost
    call. For example:
    ```python
    with printer.colored(Colors.BLUE):
        with printer.colored(Colors.RED):
            printer.print_string("test")
    ```
    will print "test" in blue, and not red.
    """

    if self._in_color_block or color is None:
        yield
    else:
        self._in_color_block = True
        print(color, end="", file=self.stream)
        yield
        print(RESET, end="", file=self.stream)
        self._in_color_block = False