Skip to content

Color

Module: terminaltexteffects.utils.graphics

Basic Usage

Color objects are used to represent colors throughout TTE. However, they can be instantiated and printed directly.

Supports Multiple Specification Formats

from terminaltexteffects.utils.graphics import Color

red = Color('ff0000')
xterm_red = Color(9)
rgb_red_again = Color('#ff0000')

Printing Colors

Colors can be printed to show the code and resulting color appearance.

from terminaltexteffects.utils.graphics import Color

red = Color("ff0000")
print(red)

t

Using Colors to build a Gradient

from terminaltexteffects.utils.graphics import Gradient, Color

rgb = Gradient(Color("ff0000"), Color("00ff00"), Color("0000ff"), steps=5)
for color in rgb:
    # color is a hex string
    ...

Passing Colors to effect configurations

text = ("EXAMPLE" * 10 + "\n") * 10
red = Color("ff0000")
green = Color("00ff00")
blue = Color("0000ff")
effect = ColorShift(text)
effect.effect_config.gradient_stops = (red, green, blue)
with effect.terminal_output() as terminal:
    for frame in effect:
        terminal.print(frame)

A Color object represents a color in the RGB color space. The color can be initialized with an XTerm-256 color code or an RGB hex color string. Can be printed to display the color code and appearance as a color block.

Attributes:

Name Type Description
color_arg int | str

The color value as an XTerm-256 color code or an RGB hex color string.

xterm_color int | None

The XTerm-256 color code. None if the color is an RGB hex color string.

rgb_color str

The RGB hex color string.

Properties

rgb_ints (tuple[int, int, int]): Returns the RGB values as a tuple of integers.

Raises:

Type Description
ValueError

If the color value is not a valid XTerm-256 color code or an RGB hex color string.

Source code in terminaltexteffects/utils/graphics.py
class Color:
    """A Color object represents a color in the RGB color space. The color can be initialized with an XTerm-256 color
    code or an RGB hex color string. Can be printed to display the color code and appearance as a color block.

    Attributes:
        color_arg (int | str): The color value as an XTerm-256 color code or an RGB hex color string.
        xterm_color (int | None): The XTerm-256 color code. None if the color is an RGB hex color string.
        rgb_color (str): The RGB hex color string.

    Properties:
        rgb_ints (tuple[int, int, int]): Returns the RGB values as a tuple of integers.

    Raises:
        ValueError: If the color value is not a valid XTerm-256 color code or an RGB hex color string.

    """

    def __init__(self, color_value: int | str) -> None:
        """Initializes a Color object.

        Args:
            color_value (int | str): The color value as an XTerm-256 color code or an RGB hex color string. Example: 255 or 'ffffff' or '#ffffff'

        Raises:
            ValueError: If the color value is not a valid XTerm-256 color code or an RGB hex color string.
        """
        self.color_arg = color_value
        self.xterm_color: int | None = None
        if hexterm.is_valid_color(color_value):
            if isinstance(color_value, int):
                self.xterm_color = color_value
                self.rgb_color = hexterm.xterm_to_hex(color_value)
            else:
                self.rgb_color = color_value.strip("#")
                self.xterm_color = None
        else:
            raise ValueError(
                "Invalid color value. Color must be an XTerm-256 color code or an RGB hex color string. Example: 255 or 'ffffff' or '#ffffff'"
            )

    @property
    def rgb_ints(self) -> tuple[int, int, int]:
        """Returns the RGB values as a tuple of integers.

        Returns:
            tuple[int, int, int]: The RGB values as a tuple of integers.
        """
        return colorterm._hex_to_int(self.rgb_color)

    def __repr__(self) -> str:
        return f"Color({self.color_arg})"

    def __str__(self) -> str:
        color_block = f"{colorterm.fg(self.rgb_color)}█████{ansitools.RESET_ALL()}"
        return f"Color Code: {self.rgb_color}{f' | XTerm Color: {self.xterm_color}' if self.xterm_color else ''}\nColor Appearance: {color_block}"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Color):
            return NotImplemented
        return self.color_arg == other.color_arg

    def __ne__(self, other: object) -> bool:
        if not isinstance(other, Color):
            return NotImplemented
        return self.color_arg != other.color_arg

    def __hash__(self) -> int:
        return hash(self.color_arg)

    def __iter__(self) -> Iterator["Color"]:
        return iter((self,))

rgb_ints: tuple[int, int, int] property

Returns the RGB values as a tuple of integers.

Returns:

Type Description
tuple[int, int, int]

tuple[int, int, int]: The RGB values as a tuple of integers.

__init__(color_value)

Initializes a Color object.

Parameters:

Name Type Description Default
color_value int | str

The color value as an XTerm-256 color code or an RGB hex color string. Example: 255 or 'ffffff' or '#ffffff'

required

Raises:

Type Description
ValueError

If the color value is not a valid XTerm-256 color code or an RGB hex color string.

Source code in terminaltexteffects/utils/graphics.py
def __init__(self, color_value: int | str) -> None:
    """Initializes a Color object.

    Args:
        color_value (int | str): The color value as an XTerm-256 color code or an RGB hex color string. Example: 255 or 'ffffff' or '#ffffff'

    Raises:
        ValueError: If the color value is not a valid XTerm-256 color code or an RGB hex color string.
    """
    self.color_arg = color_value
    self.xterm_color: int | None = None
    if hexterm.is_valid_color(color_value):
        if isinstance(color_value, int):
            self.xterm_color = color_value
            self.rgb_color = hexterm.xterm_to_hex(color_value)
        else:
            self.rgb_color = color_value.strip("#")
            self.xterm_color = None
    else:
        raise ValueError(
            "Invalid color value. Color must be an XTerm-256 color code or an RGB hex color string. Example: 255 or 'ffffff' or '#ffffff'"
        )