Skip to content

Patch module

Examples

Patch Rich's Color.parse at runtime to add CSS name and 3-digit hex support (Rich's parser runs first; the extensions are a fallback for colors Rich rejects):

from rich_color_ext.patch import install, uninstall, is_installed

install()
assert is_installed()

# ... use Rich with CSS colours here ...

uninstall()
assert not is_installed()

install() and uninstall() are idempotent and serialised with a lock, and is_installed() inspects Color.parse directly.

API reference

rich-color-ext.patch.py

Monkey-patching support for rich.color.Color.parse.

The patched parser always tries Rich's own parser first and only falls back to 3-digit hex (#abc) and CSS color names when Rich rejects the input. Colors Rich already understands (including ANSI names such as red) are therefore unchanged.

install()

Install the monkey patch. After this call, rich.color.Color.parse also accepts 3-digit hex (#abc) and CSS color names. Safe to call multiple times.

Source code in src/rich_color_ext/patch.py
def install() -> None:
    """
    Install the monkey patch. After this call, ``rich.color.Color.parse`` also
    accepts 3-digit hex (``#abc``) and CSS color names. Safe to call multiple times.
    """
    with _LOCK:
        if is_installed():
            return
        setattr(Color, "parse", _PATCHED_PARSE_ATTR)

is_installed()

Return True if the monkey patch is currently installed.

Source code in src/rich_color_ext/patch.py
def is_installed() -> bool:
    """
    Return True if the monkey patch is currently installed.
    """
    return Color.__dict__["parse"] is _PATCHED_PARSE_ATTR

uninstall()

Uninstall the monkey patch, restoring the original rich.color.Color.parse. Safe to call multiple times. If another library has replaced Color.parse since install(), that foreign patch is left untouched.

Source code in src/rich_color_ext/patch.py
def uninstall() -> None:
    """
    Uninstall the monkey patch, restoring the original ``rich.color.Color.parse``.
    Safe to call multiple times. If another library has replaced ``Color.parse``
    since ``install()``, that foreign patch is left untouched.
    """
    with _LOCK:
        if not is_installed():
            return
        setattr(Color, "parse", _ORIGINAL_PARSE_ATTR)