Skip to content

color

chromatic.color

ANSI_4BIT_RGB = ((0, 0, 0), (170, 0, 0), (0, 170, 0), (170, 85, 0), (0, 0, 170), (170, 0, 170), (0, 170, 170), (170, 170, 170), (85, 85, 85), (255, 85, 85), (85, 255, 85), (255, 255, 85), (85, 85, 255), (255, 85, 255), (85, 255, 255), (255, 255, 255)) module-attribute

CSI = b'\x1b[' module-attribute

DEFAULT_ANSI = ansicolor8Bit if is_vt_enabled() else ansicolor4Bit module-attribute

SGR_RESET = b'\x1b[0m' module-attribute

Back module-attribute

Fore module-attribute

Style module-attribute

named_color module-attribute

Color

Bases: int

Color([x]) -> color

Color(x, base=10) -> color

Convert a number or string into a color, or return Color(0) if no arguments are given. Accepts the same arguments as int, but the value must be in range 0,0xFFFFFF (incl).

Source code in chromatic/color/core.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
class Color(int):
    """
    Color([x]) -> color

    Color(x, base=10) -> color

    Convert a number or string into a color, or return ``Color(0)`` if no arguments are given.
    Accepts the same arguments as int, but the value must be in range 0,0xFFFFFF (incl).
    """

    def __new__(cls, *args, **kwargs):
        inst = super().__new__(cls, *args, **kwargs)
        if is_u24(inst, strict=True):
            return inst
        raise RuntimeError("unreachable")

    def __repr__(self):
        return "{0.__class__.__name__}(0x{0:06X})".format(self)

    def __invert__(self):
        return self.__class__(0xFFFFFF ^ self)

    @classmethod
    def from_rgb(cls, rgb, /):
        return super().__new__(cls, rgb2int(rgb))

    @property
    def rgb(self):
        return (self >> 16) & 0xFF, (self >> 8) & 0xFF, self & 0xFF

rgb property

__new__(*args, **kwargs)

__new__(x: ConvertibleToInt = ...) -> tp.Self
__new__(x: str | bytes | bytearray, /, base: tp.SupportsIndex = 10) -> tp.Self
Source code in chromatic/color/core.py
579
580
581
582
583
def __new__(cls, *args, **kwargs):
    inst = super().__new__(cls, *args, **kwargs)
    if is_u24(inst, strict=True):
        return inst
    raise RuntimeError("unreachable")

__repr__()

Source code in chromatic/color/core.py
585
586
def __repr__(self):
    return "{0.__class__.__name__}(0x{0:06X})".format(self)

__invert__()

Source code in chromatic/color/core.py
588
589
def __invert__(self):
    return self.__class__(0xFFFFFF ^ self)

from_rgb(rgb) classmethod

Source code in chromatic/color/core.py
591
592
593
@classmethod
def from_rgb(cls, rgb, /):
    return super().__new__(cls, rgb2int(rgb))

ColorStr

Bases: str, _IntFloatMixin

Source code in chromatic/color/core.py
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
class ColorStr(str, _IntFloatMixin):
    def _weak_var_update(self, **kwargs):
        expected = {"base_str", "sgr", "reset"}
        if not kwargs.keys() <= expected:
            unexpected = kwargs.keys() - expected
            raise ValueError(f"unexpected keys: {unexpected}")
        sgr = kwargs.get("sgr", self._sgr)
        base_str = kwargs.get("base_str", self.base_str)
        suffix = SGR_RESET_S if kwargs.get("reset", self.reset) else ""
        inst = super().__new__(self.__class__, f"{sgr}{base_str}{suffix}")
        inst.__dict__ |= vars(self) | {f"_{k}": v for k, v in kwargs.items()}
        return inst

    def ansi_partition(self):
        r"""Returns a 3-tuple of parts of the string
        (sgr, base string, '\x1B[0m' or '')

        """
        return str(self._sgr), self.base_str, self._reset

    def as_ansi_type(self, ansi_type, /):
        """Convert all ANSI colors in the `ColorStr` to a single ANSI type.

        Parameters
        ----------
        ansi_type : {'4b', '8b', '24b'} or type[ansicolor4Bit | ansicolor8Bit | ansicolor24Bit]
            ANSI format to which all SGR parameters of type `colorbytes` will be cast.

        Returns
        -------
        ColorStr
            Return `self` if all ANSI formats are already the input type.
            Otherwise, return reformatted `ColorStr`.

        """
        ansi_type = get_ansi_type(ansi_type)
        if self.rgb_dict and ansi_type is not self.ansi_type:
            sgr = self._sgr.copy()
            sgr.set_colors(sgr.rgb_dict, ansi_type)
            inst = super().__new__(self.__class__, f"{sgr}{self.base_str}{self._reset}")
            inst.__dict__ |= vars(self) | {"_sgr": sgr, "_ansi_type": ansi_type}
            return inst
        return self

    def recolor(self, *args, **kwargs):
        """Return a copy of self with a new color spec.

        ``ColorStr.recolor(self, value, /, *, absolute=False) -> ColorStr``

        ``ColorStr.recolor(self, *, fg=None, bg=None, absolute=False) -> ColorStr``

        If no arguments are given, returns self unchanged.
        If 'value' is given and a `ColorStr`, return self with the colors of 'value'.
        Else, use keyword arguments ``{'fg', 'bg'}`` for colors.

        Any other mix of arguments will fail outright,
        since 'value' along with { fg=... | bg=... } is ambiguous which to use for colors.

        The 'absolute' keyword can be used with either signature.

        Keyword Args
        ------------
        fg : SupportsInt, optional
            New foreground color.

        bg : SupportsInt, optional
            New background color.

        absolute : bool, optional
            If True, clear all colors of the copied string before substitution.
            Otherwise, replace colors only where specified (default is False).

        Returns
        -------
        recolored : ColorStr

        Raises
        ------
        ValueError
            If the input arguments do not match any of the expected signatures.

        Examples
        --------
        >>> from chromatic import ColorStr, Color, randcolor
        >>> cs1 = ColorStr('foo', randcolor())
        >>> cs2 = ColorStr('bar', fg=Color(0xFF5555), bg=Color(0xFF00FF))
        >>> new_cs = cs2.recolor(bg=cs1.fg)
        >>> int(new_cs.fg) == 0xFF5555, new_cs.bg == cs1.fg
        (True, True)

        >>> cs = ColorStr("Red text", fg=0xFF0000)
        >>> recolored = cs.recolor(fg=Color(0x00FF00))
        >>> recolored.base_str, f"0x{recolored.fg:06X}"
        ('Red text', '0x00FF00')

        """
        expected = {"absolute", "fg", "bg"}
        if not kwargs.keys() <= expected:
            unexpected = kwargs.keys() - expected
            raise ValueError(f"unexpected keywords: {unexpected}")
        if kwargs.pop("absolute", False):
            if not (args or kwargs):
                return (
                    self
                    if not self._sgr.is_color()
                    else self._weak_var_update(
                        sgr=SgrSequence(p for p in self._sgr if not p.is_color())
                    )
                )
            default_fg = default_bg = None
        else:
            if not (args or kwargs):
                return self
            default_fg = self._sgr.fg
            default_bg = self._sgr.bg
        fg: Int3Tuple | None
        bg: Int3Tuple | None
        match args, kwargs:
            case [ColorStr(fg=fg_color, bg=bg_color)], {}:
                fg = getattr(fg_color, "rgb", default_fg)
                bg = getattr(bg_color, "rgb", default_bg)
            case [], _:
                fg = kwargs.pop("fg", default_fg)
                bg = kwargs.pop("bg", default_bg)
            case _:
                raise ValueError(
                    f"expected at most 1 positional arguments, got {len(args)}"
                    if len(args) > 1
                    else f"unexpected keywords: {set(kwargs)}"
                )
        sgr = self._sgr.copy()
        sgr.set_colors({"fg": fg, "bg": bg}, self.ansi_type)
        return self._weak_var_update(sgr=sgr)

    def strip_style(self):
        only_colors = []
        diff = False
        for x in self._sgr:
            if x.is_color():
                only_colors.append(x)
            elif not diff:
                diff = True
        if not diff:
            return self
        sgr = self._sgr.copy()
        sgr[:] = only_colors
        return self._weak_var_update(sgr=sgr)

    def add_reset(self):
        if not self.reset:
            return self._weak_var_update(reset=True)
        return self

    def remove_reset(self):
        if self.reset:
            return self._weak_var_update(reset=False)
        return self

    def swap_reset(self):
        return self.remove_reset() if self.reset else self.add_reset()

    def add_sgr_param(self, x: int, /):
        bx = SgrParamBuffer(b"%d" % SgrParameter(x))
        if bx in self._sgr:
            return self
        sgr = self._sgr.copy()
        sgr.append(bx)
        inst = super().__new__(self.__class__, f"{sgr}{self.base_str}{self._reset}")
        inst.__dict__ |= vars(self) | {
            "_sgr": sgr,
            "_ansi_type": sgr.ansi_type() or self.ansi_type,
        }
        return inst

    def remove_sgr_param(self, x: int, /):
        bx = SgrParamBuffer(b"%d" % SgrParameter(x))
        if bx not in self._sgr:
            return self
        sgr = self._sgr.copy()
        sgr.remove(bx)
        inst = super().__new__(self.__class__, f"{sgr}{self.base_str}{self._reset}")
        inst.__dict__ |= vars(self) | {
            "_sgr": sgr,
            "_ansi_type": sgr.ansi_type() or self.ansi_type,
        }
        return inst

    def blink(self):
        return self.add_sgr_param(SgrParameter.SLOW_BLINK)

    def blink_stop(self):
        return self.add_sgr_param(SgrParameter.RESET_BLINKING)

    def bold(self):
        return self.add_sgr_param(SgrParameter.BOLD)

    def faint(self):
        return self.add_sgr_param(SgrParameter.FAINT)

    def crossed_out(self):
        return self.add_sgr_param(SgrParameter.CROSSED_OUT)

    def encircle(self):
        return self.add_sgr_param(SgrParameter.ENCIRCLED)

    def italicize(self):
        return self.add_sgr_param(SgrParameter.ITALICS)

    def negative(self):
        return self.add_sgr_param(SgrParameter.NEGATIVE)

    def underline(self):
        return self.add_sgr_param(SgrParameter.SINGLE_UNDERLINE)

    def double_underline(self):
        return self.add_sgr_param(SgrParameter.DOUBLE_UNDERLINE)

    def capitalize(self):
        return self._weak_var_update(base_str=self.base_str.capitalize())

    def casefold(self):
        return self._weak_var_update(base_str=self.base_str.casefold())

    def center(self, width, fillchar=" ", /):
        return self._weak_var_update(base_str=self.base_str.center(width, fillchar))

    def count(self, x, /, *args):
        return self.base_str.count(x, *args)

    def endswith(self, suffix, /, *args):
        return self.base_str.endswith(suffix, *args)

    def expandtabs(self, /, tabsize=8):
        return self._weak_var_update(base_str=self.base_str.expandtabs(tabsize))

    def find(self, sub, /, *args):
        return self.base_str.find(sub, *args)

    def format(self, *args, **kwargs):
        return self._weak_var_update(base_str=self.base_str.format(*args, **kwargs))

    def format_map(self, mapping, /):
        return self._weak_var_update(base_str=self.base_str.format_map(mapping))

    def index(self, sub, /, *args):
        return self.base_str.index(sub, *args)

    def isalnum(self):
        return self.base_str.isalnum()

    def isalpha(self):
        return self.base_str.isalpha()

    def isascii(self):
        return self.base_str.isascii()

    def isdecimal(self):
        return self.base_str.isdecimal()

    def isdigit(self):
        return self.base_str.isdigit()

    def isidentifier(self):
        return self.base_str.isidentifier()

    def islower(self):
        return self.base_str.islower()

    def isnumeric(self):
        return self.base_str.isnumeric()

    def isprintable(self):
        return self.base_str.isprintable()

    def isspace(self):
        return self.base_str.isspace()

    def istitle(self):
        return self.base_str.istitle()

    def isupper(self):
        return self.base_str.isupper()

    def join(self, iterable, /):
        return self._weak_var_update(
            base_str=self.base_str.join(
                getattr(elt, "base_str", elt) for elt in iterable
            )
        )

    def ljust(self, width, fillchar=" ", /):
        return self._weak_var_update(base_str=self.base_str.ljust(width, fillchar))

    def lower(self):
        return self._weak_var_update(base_str=self.base_str.lower())

    def lstrip(self, chars=None, /):
        return self._weak_var_update(base_str=self.base_str.lstrip(chars))

    def partition(self, sep, /):
        lhs, sep, rhs = (
            self._weak_var_update(base_str=s) for s in self.base_str.partition(sep)
        )
        return lhs, sep, rhs

    def removeprefix(self, prefix, /):
        return self._weak_var_update(base_str=self.base_str.removeprefix(prefix))

    def removesuffix(self, prefix, /):
        return self._weak_var_update(base_str=self.base_str.removesuffix(prefix))

    def replace(self, old, new, /, count=-1):
        return self._weak_var_update(base_str=self.base_str.replace(old, new, count))

    def rfind(self, sub, /, *args):
        return self.base_str.rfind(sub, *args)

    def rindex(self, sub, /, *args):
        return self.base_str.rindex(sub, *args)

    def rjust(self, width, fillchar=" ", /):
        return self._weak_var_update(base_str=self.base_str.rjust(width, fillchar))

    def rstrip(self, chars=None, /):
        return self._weak_var_update(base_str=self.base_str.rstrip(chars))

    def rpartition(self, sep, /):
        lhs, sep, rhs = (
            self._weak_var_update(base_str=s) for s in self.base_str.rpartition(sep)
        )
        return lhs, sep, rhs

    def rsplit(self, sep=None, maxsplit=-1):
        return [
            self._weak_var_update(base_str=s)
            for s in self.base_str.rsplit(sep=sep, maxsplit=maxsplit)
        ]

    def split(self, sep=None, maxsplit=-1):
        return [
            self._weak_var_update(base_str=s)
            for s in self.base_str.split(sep=sep, maxsplit=maxsplit)
        ]

    def splitlines(self, keepends=False):
        return [
            self._weak_var_update(base_str=s)
            for s in self.base_str.splitlines(keepends=keepends)
        ]

    def startswith(self, prefix, /, *args):
        return self.base_str.startswith(prefix, *args)

    def strip(self, chars=None, /):
        return self._weak_var_update(base_str=self.base_str.strip(chars))

    def swapcase(self):
        return self._weak_var_update(base_str=self.base_str.swapcase())

    def title(self):
        return self._weak_var_update(base_str=self.base_str.title())

    def translate(self, table, /):
        return self._weak_var_update(base_str=self.base_str.translate(table))

    def upper(self):
        return self._weak_var_update(base_str=self.base_str.upper())

    def zfill(self, width, /):
        return self._weak_var_update(base_str=self.base_str.zfill(width))

    def __add__(self, other, /):
        if isinstance(other, self.__class__):
            return self._weak_var_update(
                sgr=self._sgr + other._sgr, base_str=self.base_str + other.base_str
            )
        elif isinstance(other, str):
            return self._weak_var_update(base_str=self.base_str + other)
        return NotImplemented

    def __contains__(self, key: str, /):
        return self.base_str.__contains__(key)

    def __eq__(self, other, /):
        if _issubclass(other.__class__, self.__class__):
            return hash(self) == hash(other)
        return NotImplemented

    def __format__(self, format_spec="", /):
        """Return a formatted version of the ColorStr as described by format_spec.

        A `colorbytes` subclass alias (ie., '24b', '8b', '4b') can be prepended to
        a `str` format_spec to convert ansi types before applying the format_spec
        to the base string.

        Notes
        -----
        This method returns type `Self` instead of `str`, which can lead to
        surprising behavior when dealing with f-strings.

        Consider the following example:

            >>> from chromatic import ColorStr
            >>> cs = ColorStr("hello", fg=0xFF0000, ansi_type="24b")
            >>> cs._ansi_type
            <class 'chromatic.color.core.ansicolor24Bit'>
            >>> fstring = f"{cs:4b#<20}"
            >>> fstring.__class__
            <class 'chromatic.color.core.ColorStr'>
            >>> fstring._ansi_type
            <class 'chromatic.color.core.ansicolor4Bit'>
            >>> fstring.base_str
            'hello###############'

        In that case, the f-string eval returned a `ColorStr` object,
        because the whole f-string only consists of a single `{...}` span.

        In such cases, the underlying ``format(...) -> ColorStr`` has nothing
        to be concatenated with, so it is returned directly.

        In any case other than the single span f-string, the internals delegate
        to normal `str` concatentation, and we get a `str` result:

            >>> from chromatic import ColorStr
            >>> cs = ColorStr("hello", fg=0xFF0000, ansi_type="24b")
            >>> f"foo {cs} bar".__class__
            <class 'str'>
            >>> cs2 = ColorStr("world", bg=0x00FFFF, ansi_type="8b")
            >>> fstring_concat = f"{cs: >10}{cs2: <10}"
            >>> fstring_concat
            '\\x1b[38;2;255;0;0m     hello\\x1b[0m\\x1b[48;5;51mworld     \\x1b[0m'
            >>> fstring_concat.__class__
            <class 'str'>

        """
        if format_spec.startswith(("24b", "8b", "4b")):
            idx = format_spec.index("b") + 1
            alias = format_spec[:idx]
            format_spec = format_spec[idx:]
            inst = self.as_ansi_type(alias)
        else:
            inst = self
        return inst._weak_var_update(base_str=inst.base_str.__format__(format_spec))

    def __ge__(self, other, /):
        return self.base_str.__ge__(other)

    def __getitem__(self, key, /):
        return self._weak_var_update(base_str=self.base_str[key])

    def __gt__(self, other, /):
        return self.base_str.__gt__(other)

    def __hash__(self):
        return hash((self.__class__, str(self)))

    def __invert__(self):
        """Return a copy of `self` with inverted colors (color ^= 0xFFFFFF)"""
        sgr = self._sgr.copy()
        sgr.set_colors(
            {k: ~Color.from_rgb(v) for k, v in self._sgr.rgb_dict.items()},
            self.ansi_type,
        )
        return self._weak_var_update(sgr=sgr)

    def __iter__(self):
        for i in range(len(self)):
            yield self[i]

    def __le__(self, other, /):
        return self.base_str.__le__(other)

    def __len__(self):
        return len(self.base_str)

    def __lt__(self, other, /):
        return self.base_str.__lt__(other)

    def __matmul__(self, other, /):
        """Return a new `ColorStr` with the base string of `self` and colors of `other`"""
        if isinstance(other, ColorStr):
            return self._weak_var_update(sgr=other._sgr.copy(), reset=other.reset)
        return NotImplemented

    def __mod__(self, value, /):
        return self._weak_var_update(base_str=self.base_str % value)

    def __mul__(self, value, /):
        return self._weak_var_update(base_str=self.base_str * value)

    __rmul__ = __mul__

    def __new__(cls, obj=_unset, /, *args, **kwargs):
        return _colorstr(super(), obj, *args, **kwargs)  # noqa

    def __radd__(self, other, /):
        if isinstance(other, SgrSequence):
            return self._weak_var_update(sgr=(other + self._sgr))
        return NotImplemented

    def __repr__(self):
        return f"{self.__class__.__name__}({super().__repr__()})"

    def __xor__(self, other, /):
        """Return copy of self with colors ^ other colors"""

        if isinstance(other, self.__class__):
            xor_dict = {
                k: int2rgb(
                    Color.from_rgb(self.rgb_dict[k]) ^ Color.from_rgb(other.rgb_dict[k])
                )
                for k in self.rgb_dict.keys() & other.rgb_dict
            }
        elif isinstance(other, int):
            xor_dict = {
                k: int2rgb(Color.from_rgb(v) ^ other) for k, v in self.rgb_dict.items()
            }
        else:
            return NotImplemented
        if not xor_dict:
            return self
        sgr = self._sgr.copy()
        sgr.set_colors(xor_dict, self.ansi_type)
        return self._weak_var_update(sgr=sgr)

    @property
    def ansi(self):
        return bytes(self._sgr)

    @property
    def ansi_type(self):
        return getattr(self, "_ansi_type")

    @property
    def base_str(self):
        """The non-ANSI part of the string"""
        return getattr(self, "_base_str")

    @property
    def bg(self):
        """Background color"""
        if bg := self._sgr.bg:
            return Color.from_rgb(bg)

    @property
    def fg(self):
        """Foreground color"""
        if fg := self._sgr.fg:
            return Color.from_rgb(fg)

    @property
    def reset(self):
        return bool(self._reset)

    @property
    def rgb_dict(self):
        return self._sgr.rgb_dict

__rmul__ = __mul__ class-attribute instance-attribute

ansi property

ansi_type property

base_str property

The non-ANSI part of the string

bg property

Background color

fg property

Foreground color

reset property

rgb_dict property

ansi_partition()

Returns a 3-tuple of parts of the string (sgr, base string, '\x1B[0m' or '')

Source code in chromatic/color/core.py
1230
1231
1232
1233
1234
1235
def ansi_partition(self):
    r"""Returns a 3-tuple of parts of the string
    (sgr, base string, '\x1B[0m' or '')

    """
    return str(self._sgr), self.base_str, self._reset

as_ansi_type(ansi_type)

Convert all ANSI colors in the ColorStr to a single ANSI type.

Parameters:

Name Type Description Default
ansi_type ('4b', '8b', '24b')

ANSI format to which all SGR parameters of type colorbytes will be cast.

'4b'

Returns:

Type Description
ColorStr

Return self if all ANSI formats are already the input type. Otherwise, return reformatted ColorStr.

Source code in chromatic/color/core.py
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
def as_ansi_type(self, ansi_type, /):
    """Convert all ANSI colors in the `ColorStr` to a single ANSI type.

    Parameters
    ----------
    ansi_type : {'4b', '8b', '24b'} or type[ansicolor4Bit | ansicolor8Bit | ansicolor24Bit]
        ANSI format to which all SGR parameters of type `colorbytes` will be cast.

    Returns
    -------
    ColorStr
        Return `self` if all ANSI formats are already the input type.
        Otherwise, return reformatted `ColorStr`.

    """
    ansi_type = get_ansi_type(ansi_type)
    if self.rgb_dict and ansi_type is not self.ansi_type:
        sgr = self._sgr.copy()
        sgr.set_colors(sgr.rgb_dict, ansi_type)
        inst = super().__new__(self.__class__, f"{sgr}{self.base_str}{self._reset}")
        inst.__dict__ |= vars(self) | {"_sgr": sgr, "_ansi_type": ansi_type}
        return inst
    return self

recolor(*args, **kwargs)

recolor(value: ColorStr, /, *, absolute: bool = ...) -> tp.Self
recolor(**kwargs: tp.Unpack[_RecolorKwargs]) -> tp.Self

Return a copy of self with a new color spec.

ColorStr.recolor(self, value, /, *, absolute=False) -> ColorStr

ColorStr.recolor(self, *, fg=None, bg=None, absolute=False) -> ColorStr

If no arguments are given, returns self unchanged. If 'value' is given and a ColorStr, return self with the colors of 'value'. Else, use keyword arguments {'fg', 'bg'} for colors.

Any other mix of arguments will fail outright, since 'value' along with { fg=... | bg=... } is ambiguous which to use for colors.

The 'absolute' keyword can be used with either signature.

Keyword Args

fg : SupportsInt, optional New foreground color.

bg : SupportsInt, optional New background color.

absolute : bool, optional If True, clear all colors of the copied string before substitution. Otherwise, replace colors only where specified (default is False).

Returns:

Name Type Description
recolored ColorStr

Raises:

Type Description
ValueError

If the input arguments do not match any of the expected signatures.

Examples:

>>> from chromatic import ColorStr, Color, randcolor
>>> cs1 = ColorStr('foo', randcolor())
>>> cs2 = ColorStr('bar', fg=Color(0xFF5555), bg=Color(0xFF00FF))
>>> new_cs = cs2.recolor(bg=cs1.fg)
>>> int(new_cs.fg) == 0xFF5555, new_cs.bg == cs1.fg
(True, True)
>>> cs = ColorStr("Red text", fg=0xFF0000)
>>> recolored = cs.recolor(fg=Color(0x00FF00))
>>> recolored.base_str, f"0x{recolored.fg:06X}"
('Red text', '0x00FF00')
Source code in chromatic/color/core.py
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
def recolor(self, *args, **kwargs):
    """Return a copy of self with a new color spec.

    ``ColorStr.recolor(self, value, /, *, absolute=False) -> ColorStr``

    ``ColorStr.recolor(self, *, fg=None, bg=None, absolute=False) -> ColorStr``

    If no arguments are given, returns self unchanged.
    If 'value' is given and a `ColorStr`, return self with the colors of 'value'.
    Else, use keyword arguments ``{'fg', 'bg'}`` for colors.

    Any other mix of arguments will fail outright,
    since 'value' along with { fg=... | bg=... } is ambiguous which to use for colors.

    The 'absolute' keyword can be used with either signature.

    Keyword Args
    ------------
    fg : SupportsInt, optional
        New foreground color.

    bg : SupportsInt, optional
        New background color.

    absolute : bool, optional
        If True, clear all colors of the copied string before substitution.
        Otherwise, replace colors only where specified (default is False).

    Returns
    -------
    recolored : ColorStr

    Raises
    ------
    ValueError
        If the input arguments do not match any of the expected signatures.

    Examples
    --------
    >>> from chromatic import ColorStr, Color, randcolor
    >>> cs1 = ColorStr('foo', randcolor())
    >>> cs2 = ColorStr('bar', fg=Color(0xFF5555), bg=Color(0xFF00FF))
    >>> new_cs = cs2.recolor(bg=cs1.fg)
    >>> int(new_cs.fg) == 0xFF5555, new_cs.bg == cs1.fg
    (True, True)

    >>> cs = ColorStr("Red text", fg=0xFF0000)
    >>> recolored = cs.recolor(fg=Color(0x00FF00))
    >>> recolored.base_str, f"0x{recolored.fg:06X}"
    ('Red text', '0x00FF00')

    """
    expected = {"absolute", "fg", "bg"}
    if not kwargs.keys() <= expected:
        unexpected = kwargs.keys() - expected
        raise ValueError(f"unexpected keywords: {unexpected}")
    if kwargs.pop("absolute", False):
        if not (args or kwargs):
            return (
                self
                if not self._sgr.is_color()
                else self._weak_var_update(
                    sgr=SgrSequence(p for p in self._sgr if not p.is_color())
                )
            )
        default_fg = default_bg = None
    else:
        if not (args or kwargs):
            return self
        default_fg = self._sgr.fg
        default_bg = self._sgr.bg
    fg: Int3Tuple | None
    bg: Int3Tuple | None
    match args, kwargs:
        case [ColorStr(fg=fg_color, bg=bg_color)], {}:
            fg = getattr(fg_color, "rgb", default_fg)
            bg = getattr(bg_color, "rgb", default_bg)
        case [], _:
            fg = kwargs.pop("fg", default_fg)
            bg = kwargs.pop("bg", default_bg)
        case _:
            raise ValueError(
                f"expected at most 1 positional arguments, got {len(args)}"
                if len(args) > 1
                else f"unexpected keywords: {set(kwargs)}"
            )
    sgr = self._sgr.copy()
    sgr.set_colors({"fg": fg, "bg": bg}, self.ansi_type)
    return self._weak_var_update(sgr=sgr)

strip_style()

Source code in chromatic/color/core.py
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
def strip_style(self):
    only_colors = []
    diff = False
    for x in self._sgr:
        if x.is_color():
            only_colors.append(x)
        elif not diff:
            diff = True
    if not diff:
        return self
    sgr = self._sgr.copy()
    sgr[:] = only_colors
    return self._weak_var_update(sgr=sgr)

add_reset()

Source code in chromatic/color/core.py
1365
1366
1367
1368
def add_reset(self):
    if not self.reset:
        return self._weak_var_update(reset=True)
    return self

remove_reset()

Source code in chromatic/color/core.py
1370
1371
1372
1373
def remove_reset(self):
    if self.reset:
        return self._weak_var_update(reset=False)
    return self

swap_reset()

Source code in chromatic/color/core.py
1375
1376
def swap_reset(self):
    return self.remove_reset() if self.reset else self.add_reset()

add_sgr_param(x)

Source code in chromatic/color/core.py
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
def add_sgr_param(self, x: int, /):
    bx = SgrParamBuffer(b"%d" % SgrParameter(x))
    if bx in self._sgr:
        return self
    sgr = self._sgr.copy()
    sgr.append(bx)
    inst = super().__new__(self.__class__, f"{sgr}{self.base_str}{self._reset}")
    inst.__dict__ |= vars(self) | {
        "_sgr": sgr,
        "_ansi_type": sgr.ansi_type() or self.ansi_type,
    }
    return inst

remove_sgr_param(x)

Source code in chromatic/color/core.py
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
def remove_sgr_param(self, x: int, /):
    bx = SgrParamBuffer(b"%d" % SgrParameter(x))
    if bx not in self._sgr:
        return self
    sgr = self._sgr.copy()
    sgr.remove(bx)
    inst = super().__new__(self.__class__, f"{sgr}{self.base_str}{self._reset}")
    inst.__dict__ |= vars(self) | {
        "_sgr": sgr,
        "_ansi_type": sgr.ansi_type() or self.ansi_type,
    }
    return inst
Source code in chromatic/color/core.py
1404
1405
def blink(self):
    return self.add_sgr_param(SgrParameter.SLOW_BLINK)
Source code in chromatic/color/core.py
1407
1408
def blink_stop(self):
    return self.add_sgr_param(SgrParameter.RESET_BLINKING)

bold()

Source code in chromatic/color/core.py
1410
1411
def bold(self):
    return self.add_sgr_param(SgrParameter.BOLD)

faint()

Source code in chromatic/color/core.py
1413
1414
def faint(self):
    return self.add_sgr_param(SgrParameter.FAINT)

crossed_out()

Source code in chromatic/color/core.py
1416
1417
def crossed_out(self):
    return self.add_sgr_param(SgrParameter.CROSSED_OUT)

encircle()

Source code in chromatic/color/core.py
1419
1420
def encircle(self):
    return self.add_sgr_param(SgrParameter.ENCIRCLED)

italicize()

Source code in chromatic/color/core.py
1422
1423
def italicize(self):
    return self.add_sgr_param(SgrParameter.ITALICS)

negative()

Source code in chromatic/color/core.py
1425
1426
def negative(self):
    return self.add_sgr_param(SgrParameter.NEGATIVE)

underline()

Source code in chromatic/color/core.py
1428
1429
def underline(self):
    return self.add_sgr_param(SgrParameter.SINGLE_UNDERLINE)

double_underline()

Source code in chromatic/color/core.py
1431
1432
def double_underline(self):
    return self.add_sgr_param(SgrParameter.DOUBLE_UNDERLINE)

capitalize()

Source code in chromatic/color/core.py
1434
1435
def capitalize(self):
    return self._weak_var_update(base_str=self.base_str.capitalize())

casefold()

Source code in chromatic/color/core.py
1437
1438
def casefold(self):
    return self._weak_var_update(base_str=self.base_str.casefold())

center(width, fillchar=' ')

Source code in chromatic/color/core.py
1440
1441
def center(self, width, fillchar=" ", /):
    return self._weak_var_update(base_str=self.base_str.center(width, fillchar))

count(x, /, *args)

Source code in chromatic/color/core.py
1443
1444
def count(self, x, /, *args):
    return self.base_str.count(x, *args)

endswith(suffix, /, *args)

Source code in chromatic/color/core.py
1446
1447
def endswith(self, suffix, /, *args):
    return self.base_str.endswith(suffix, *args)

expandtabs(tabsize=8)

Source code in chromatic/color/core.py
1449
1450
def expandtabs(self, /, tabsize=8):
    return self._weak_var_update(base_str=self.base_str.expandtabs(tabsize))

find(sub, /, *args)

Source code in chromatic/color/core.py
1452
1453
def find(self, sub, /, *args):
    return self.base_str.find(sub, *args)

format(*args, **kwargs)

Source code in chromatic/color/core.py
1455
1456
def format(self, *args, **kwargs):
    return self._weak_var_update(base_str=self.base_str.format(*args, **kwargs))

format_map(mapping)

Source code in chromatic/color/core.py
1458
1459
def format_map(self, mapping, /):
    return self._weak_var_update(base_str=self.base_str.format_map(mapping))

index(sub, /, *args)

Source code in chromatic/color/core.py
1461
1462
def index(self, sub, /, *args):
    return self.base_str.index(sub, *args)

isalnum()

Source code in chromatic/color/core.py
1464
1465
def isalnum(self):
    return self.base_str.isalnum()

isalpha()

Source code in chromatic/color/core.py
1467
1468
def isalpha(self):
    return self.base_str.isalpha()

isascii()

Source code in chromatic/color/core.py
1470
1471
def isascii(self):
    return self.base_str.isascii()

isdecimal()

Source code in chromatic/color/core.py
1473
1474
def isdecimal(self):
    return self.base_str.isdecimal()

isdigit()

Source code in chromatic/color/core.py
1476
1477
def isdigit(self):
    return self.base_str.isdigit()

isidentifier()

Source code in chromatic/color/core.py
1479
1480
def isidentifier(self):
    return self.base_str.isidentifier()

islower()

Source code in chromatic/color/core.py
1482
1483
def islower(self):
    return self.base_str.islower()

isnumeric()

Source code in chromatic/color/core.py
1485
1486
def isnumeric(self):
    return self.base_str.isnumeric()

isprintable()

Source code in chromatic/color/core.py
1488
1489
def isprintable(self):
    return self.base_str.isprintable()

isspace()

Source code in chromatic/color/core.py
1491
1492
def isspace(self):
    return self.base_str.isspace()

istitle()

Source code in chromatic/color/core.py
1494
1495
def istitle(self):
    return self.base_str.istitle()

isupper()

Source code in chromatic/color/core.py
1497
1498
def isupper(self):
    return self.base_str.isupper()

join(iterable)

Source code in chromatic/color/core.py
1500
1501
1502
1503
1504
1505
def join(self, iterable, /):
    return self._weak_var_update(
        base_str=self.base_str.join(
            getattr(elt, "base_str", elt) for elt in iterable
        )
    )

ljust(width, fillchar=' ')

Source code in chromatic/color/core.py
1507
1508
def ljust(self, width, fillchar=" ", /):
    return self._weak_var_update(base_str=self.base_str.ljust(width, fillchar))

lower()

Source code in chromatic/color/core.py
1510
1511
def lower(self):
    return self._weak_var_update(base_str=self.base_str.lower())

lstrip(chars=None)

Source code in chromatic/color/core.py
1513
1514
def lstrip(self, chars=None, /):
    return self._weak_var_update(base_str=self.base_str.lstrip(chars))

partition(sep)

Source code in chromatic/color/core.py
1516
1517
1518
1519
1520
def partition(self, sep, /):
    lhs, sep, rhs = (
        self._weak_var_update(base_str=s) for s in self.base_str.partition(sep)
    )
    return lhs, sep, rhs

removeprefix(prefix)

Source code in chromatic/color/core.py
1522
1523
def removeprefix(self, prefix, /):
    return self._weak_var_update(base_str=self.base_str.removeprefix(prefix))

removesuffix(prefix)

Source code in chromatic/color/core.py
1525
1526
def removesuffix(self, prefix, /):
    return self._weak_var_update(base_str=self.base_str.removesuffix(prefix))

replace(old, new, /, count=-1)

Source code in chromatic/color/core.py
1528
1529
def replace(self, old, new, /, count=-1):
    return self._weak_var_update(base_str=self.base_str.replace(old, new, count))

rfind(sub, /, *args)

Source code in chromatic/color/core.py
1531
1532
def rfind(self, sub, /, *args):
    return self.base_str.rfind(sub, *args)

rindex(sub, /, *args)

Source code in chromatic/color/core.py
1534
1535
def rindex(self, sub, /, *args):
    return self.base_str.rindex(sub, *args)

rjust(width, fillchar=' ')

Source code in chromatic/color/core.py
1537
1538
def rjust(self, width, fillchar=" ", /):
    return self._weak_var_update(base_str=self.base_str.rjust(width, fillchar))

rstrip(chars=None)

Source code in chromatic/color/core.py
1540
1541
def rstrip(self, chars=None, /):
    return self._weak_var_update(base_str=self.base_str.rstrip(chars))

rpartition(sep)

Source code in chromatic/color/core.py
1543
1544
1545
1546
1547
def rpartition(self, sep, /):
    lhs, sep, rhs = (
        self._weak_var_update(base_str=s) for s in self.base_str.rpartition(sep)
    )
    return lhs, sep, rhs

rsplit(sep=None, maxsplit=-1)

Source code in chromatic/color/core.py
1549
1550
1551
1552
1553
def rsplit(self, sep=None, maxsplit=-1):
    return [
        self._weak_var_update(base_str=s)
        for s in self.base_str.rsplit(sep=sep, maxsplit=maxsplit)
    ]

split(sep=None, maxsplit=-1)

Source code in chromatic/color/core.py
1555
1556
1557
1558
1559
def split(self, sep=None, maxsplit=-1):
    return [
        self._weak_var_update(base_str=s)
        for s in self.base_str.split(sep=sep, maxsplit=maxsplit)
    ]

splitlines(keepends=False)

Source code in chromatic/color/core.py
1561
1562
1563
1564
1565
def splitlines(self, keepends=False):
    return [
        self._weak_var_update(base_str=s)
        for s in self.base_str.splitlines(keepends=keepends)
    ]

startswith(prefix, /, *args)

Source code in chromatic/color/core.py
1567
1568
def startswith(self, prefix, /, *args):
    return self.base_str.startswith(prefix, *args)

strip(chars=None)

Source code in chromatic/color/core.py
1570
1571
def strip(self, chars=None, /):
    return self._weak_var_update(base_str=self.base_str.strip(chars))

swapcase()

Source code in chromatic/color/core.py
1573
1574
def swapcase(self):
    return self._weak_var_update(base_str=self.base_str.swapcase())

title()

Source code in chromatic/color/core.py
1576
1577
def title(self):
    return self._weak_var_update(base_str=self.base_str.title())

translate(table)

Source code in chromatic/color/core.py
1579
1580
def translate(self, table, /):
    return self._weak_var_update(base_str=self.base_str.translate(table))

upper()

Source code in chromatic/color/core.py
1582
1583
def upper(self):
    return self._weak_var_update(base_str=self.base_str.upper())

zfill(width)

Source code in chromatic/color/core.py
1585
1586
def zfill(self, width, /):
    return self._weak_var_update(base_str=self.base_str.zfill(width))

__add__(other)

Source code in chromatic/color/core.py
1588
1589
1590
1591
1592
1593
1594
1595
def __add__(self, other, /):
    if isinstance(other, self.__class__):
        return self._weak_var_update(
            sgr=self._sgr + other._sgr, base_str=self.base_str + other.base_str
        )
    elif isinstance(other, str):
        return self._weak_var_update(base_str=self.base_str + other)
    return NotImplemented

__contains__(key)

Source code in chromatic/color/core.py
1597
1598
def __contains__(self, key: str, /):
    return self.base_str.__contains__(key)

__eq__(other)

Source code in chromatic/color/core.py
1600
1601
1602
1603
def __eq__(self, other, /):
    if _issubclass(other.__class__, self.__class__):
        return hash(self) == hash(other)
    return NotImplemented

__format__(format_spec='')

Return a formatted version of the ColorStr as described by format_spec.

A colorbytes subclass alias (ie., '24b', '8b', '4b') can be prepended to a str format_spec to convert ansi types before applying the format_spec to the base string.

Notes

This method returns type Self instead of str, which can lead to surprising behavior when dealing with f-strings.

Consider the following example:

>>> from chromatic import ColorStr
>>> cs = ColorStr("hello", fg=0xFF0000, ansi_type="24b")
>>> cs._ansi_type
<class 'chromatic.color.core.ansicolor24Bit'>
>>> fstring = f"{cs:4b#<20}"
>>> fstring.__class__
<class 'chromatic.color.core.ColorStr'>
>>> fstring._ansi_type
<class 'chromatic.color.core.ansicolor4Bit'>
>>> fstring.base_str
'hello###############'

In that case, the f-string eval returned a ColorStr object, because the whole f-string only consists of a single {...} span.

In such cases, the underlying format(...) -> ColorStr has nothing to be concatenated with, so it is returned directly.

In any case other than the single span f-string, the internals delegate to normal str concatentation, and we get a str result:

>>> from chromatic import ColorStr
>>> cs = ColorStr("hello", fg=0xFF0000, ansi_type="24b")
>>> f"foo {cs} bar".__class__
<class 'str'>
>>> cs2 = ColorStr("world", bg=0x00FFFF, ansi_type="8b")
>>> fstring_concat = f"{cs: >10}{cs2: <10}"
>>> fstring_concat
'\x1b[38;2;255;0;0m     hello\x1b[0m\x1b[48;5;51mworld     \x1b[0m'
>>> fstring_concat.__class__
<class 'str'>
Source code in chromatic/color/core.py
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
def __format__(self, format_spec="", /):
    """Return a formatted version of the ColorStr as described by format_spec.

    A `colorbytes` subclass alias (ie., '24b', '8b', '4b') can be prepended to
    a `str` format_spec to convert ansi types before applying the format_spec
    to the base string.

    Notes
    -----
    This method returns type `Self` instead of `str`, which can lead to
    surprising behavior when dealing with f-strings.

    Consider the following example:

        >>> from chromatic import ColorStr
        >>> cs = ColorStr("hello", fg=0xFF0000, ansi_type="24b")
        >>> cs._ansi_type
        <class 'chromatic.color.core.ansicolor24Bit'>
        >>> fstring = f"{cs:4b#<20}"
        >>> fstring.__class__
        <class 'chromatic.color.core.ColorStr'>
        >>> fstring._ansi_type
        <class 'chromatic.color.core.ansicolor4Bit'>
        >>> fstring.base_str
        'hello###############'

    In that case, the f-string eval returned a `ColorStr` object,
    because the whole f-string only consists of a single `{...}` span.

    In such cases, the underlying ``format(...) -> ColorStr`` has nothing
    to be concatenated with, so it is returned directly.

    In any case other than the single span f-string, the internals delegate
    to normal `str` concatentation, and we get a `str` result:

        >>> from chromatic import ColorStr
        >>> cs = ColorStr("hello", fg=0xFF0000, ansi_type="24b")
        >>> f"foo {cs} bar".__class__
        <class 'str'>
        >>> cs2 = ColorStr("world", bg=0x00FFFF, ansi_type="8b")
        >>> fstring_concat = f"{cs: >10}{cs2: <10}"
        >>> fstring_concat
        '\\x1b[38;2;255;0;0m     hello\\x1b[0m\\x1b[48;5;51mworld     \\x1b[0m'
        >>> fstring_concat.__class__
        <class 'str'>

    """
    if format_spec.startswith(("24b", "8b", "4b")):
        idx = format_spec.index("b") + 1
        alias = format_spec[:idx]
        format_spec = format_spec[idx:]
        inst = self.as_ansi_type(alias)
    else:
        inst = self
    return inst._weak_var_update(base_str=inst.base_str.__format__(format_spec))

__ge__(other)

Source code in chromatic/color/core.py
1661
1662
def __ge__(self, other, /):
    return self.base_str.__ge__(other)

__getitem__(key)

__getitem__(key: tp.SupportsIndex) -> tp.Self
__getitem__(key: slice) -> tp.Self
Source code in chromatic/color/core.py
1664
1665
def __getitem__(self, key, /):
    return self._weak_var_update(base_str=self.base_str[key])

__gt__(other)

Source code in chromatic/color/core.py
1667
1668
def __gt__(self, other, /):
    return self.base_str.__gt__(other)

__hash__()

Source code in chromatic/color/core.py
1670
1671
def __hash__(self):
    return hash((self.__class__, str(self)))

__invert__()

Return a copy of self with inverted colors (color ^= 0xFFFFFF)

Source code in chromatic/color/core.py
1673
1674
1675
1676
1677
1678
1679
1680
def __invert__(self):
    """Return a copy of `self` with inverted colors (color ^= 0xFFFFFF)"""
    sgr = self._sgr.copy()
    sgr.set_colors(
        {k: ~Color.from_rgb(v) for k, v in self._sgr.rgb_dict.items()},
        self.ansi_type,
    )
    return self._weak_var_update(sgr=sgr)

__iter__()

Source code in chromatic/color/core.py
1682
1683
1684
def __iter__(self):
    for i in range(len(self)):
        yield self[i]

__le__(other)

Source code in chromatic/color/core.py
1686
1687
def __le__(self, other, /):
    return self.base_str.__le__(other)

__len__()

Source code in chromatic/color/core.py
1689
1690
def __len__(self):
    return len(self.base_str)

__lt__(other)

Source code in chromatic/color/core.py
1692
1693
def __lt__(self, other, /):
    return self.base_str.__lt__(other)

__matmul__(other)

Return a new ColorStr with the base string of self and colors of other

Source code in chromatic/color/core.py
1695
1696
1697
1698
1699
def __matmul__(self, other, /):
    """Return a new `ColorStr` with the base string of `self` and colors of `other`"""
    if isinstance(other, ColorStr):
        return self._weak_var_update(sgr=other._sgr.copy(), reset=other.reset)
    return NotImplemented

__mod__(value)

Source code in chromatic/color/core.py
1701
1702
def __mod__(self, value, /):
    return self._weak_var_update(base_str=self.base_str % value)

__mul__(value)

Source code in chromatic/color/core.py
1704
1705
def __mul__(self, value, /):
    return self._weak_var_update(base_str=self.base_str * value)

__new__(obj=_unset, /, *args, **kwargs)

__new__(obj: object = ..., /, fg: tp.SupportsInt | _RGBVectorLike | None = None, bg: tp.SupportsInt | _RGBVectorLike | None = None, *, ansi_type: AnsiColorParam = ..., reset: bool = ...) -> tp.Self
__new__(obj: abc.Buffer, /, fg: tp.SupportsInt | _RGBVectorLike | None = None, bg: tp.SupportsInt | _RGBVectorLike | None = None, *, encoding: str = ..., errors: str = ..., ansi_type: AnsiColorParam = ..., reset: bool = ...) -> tp.Self
Source code in chromatic/color/core.py
1709
1710
def __new__(cls, obj=_unset, /, *args, **kwargs):
    return _colorstr(super(), obj, *args, **kwargs)  # noqa

__radd__(other)

Source code in chromatic/color/core.py
1712
1713
1714
1715
def __radd__(self, other, /):
    if isinstance(other, SgrSequence):
        return self._weak_var_update(sgr=(other + self._sgr))
    return NotImplemented

__repr__()

Source code in chromatic/color/core.py
1717
1718
def __repr__(self):
    return f"{self.__class__.__name__}({super().__repr__()})"

__xor__(other)

Return copy of self with colors ^ other colors

Source code in chromatic/color/core.py
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
def __xor__(self, other, /):
    """Return copy of self with colors ^ other colors"""

    if isinstance(other, self.__class__):
        xor_dict = {
            k: int2rgb(
                Color.from_rgb(self.rgb_dict[k]) ^ Color.from_rgb(other.rgb_dict[k])
            )
            for k in self.rgb_dict.keys() & other.rgb_dict
        }
    elif isinstance(other, int):
        xor_dict = {
            k: int2rgb(Color.from_rgb(v) ^ other) for k, v in self.rgb_dict.items()
        }
    else:
        return NotImplemented
    if not xor_dict:
        return self
    sgr = self._sgr.copy()
    sgr.set_colors(xor_dict, self.ansi_type)
    return self._weak_var_update(sgr=sgr)

SgrFlag

Bases: IntFlag

Source code in chromatic/color/core.py
141
142
143
class SgrFlag(enum.IntFlag):
    @property
    def parameters(self) -> list[SgrParameter]: ...

parameters property

RESET = 1 class-attribute instance-attribute

BOLD = 2 class-attribute instance-attribute

FAINT = 4 class-attribute instance-attribute

ITALICS = 8 class-attribute instance-attribute

SINGLE_UNDERLINE = 16 class-attribute instance-attribute

NEGATIVE = 128 class-attribute instance-attribute

CONCEALED_CHARS = 256 class-attribute instance-attribute

CROSSED_OUT = 512 class-attribute instance-attribute

PRIMARY = 1024 class-attribute instance-attribute

FIRST_ALT = 2048 class-attribute instance-attribute

SECOND_ALT = 4096 class-attribute instance-attribute

THIRD_ALT = 8192 class-attribute instance-attribute

FOURTH_ALT = 16384 class-attribute instance-attribute

FIFTH_ALT = 32768 class-attribute instance-attribute

SIXTH_ALT = 65536 class-attribute instance-attribute

SEVENTH_ALT = 131072 class-attribute instance-attribute

EIGHTH_ALT = 262144 class-attribute instance-attribute

NINTH_ALT = 524288 class-attribute instance-attribute

GOTHIC = 1048576 class-attribute instance-attribute

DOUBLE_UNDERLINE = 2097152 class-attribute instance-attribute

RESET_BOLD_AND_FAINT = 4194304 class-attribute instance-attribute

RESET_ITALIC_AND_GOTHIC = 8388608 class-attribute instance-attribute

RESET_UNDERLINES = 16777216 class-attribute instance-attribute

RESET_BLINKING = 33554432 class-attribute instance-attribute

POSITIVE = 67108864 class-attribute instance-attribute

REVEALED_CHARS = 134217728 class-attribute instance-attribute

RESET_CROSSED_OUT = 268435456 class-attribute instance-attribute

DEFAULT_FG_COLOR = 536870912 class-attribute instance-attribute

DEFAULT_BG_COLOR = 1073741824 class-attribute instance-attribute

FRAMED = 2147483648 class-attribute instance-attribute

ENCIRCLED = 4294967296 class-attribute instance-attribute

OVERLINED = 8589934592 class-attribute instance-attribute

NOT_FRAMED_OR_CIRCLED = 17179869184 class-attribute instance-attribute

IDEOGRAM_UNDER_OR_RIGHT = 34359738368 class-attribute instance-attribute

IDEOGRAM_2UNDER_OR_2RIGHT = 68719476736 class-attribute instance-attribute

IDEOGRAM_OVER_OR_LEFT = 137438953472 class-attribute instance-attribute

IDEOGRAM_2OVER_OR_2LEFT = 274877906944 class-attribute instance-attribute

CANCEL = 549755813888 class-attribute instance-attribute

SgrParameter

Bases: IntEnum

Source code in chromatic/color/core.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class SgrParameter(enum.IntEnum):
    RESET = 0
    BOLD = 1
    FAINT = 2
    ITALICS = 3
    SINGLE_UNDERLINE = 4
    SLOW_BLINK = 5
    RAPID_BLINK = 6
    NEGATIVE = 7
    CONCEALED_CHARS = 8
    CROSSED_OUT = 9
    PRIMARY = 10
    FIRST_ALT = 11
    SECOND_ALT = 12
    THIRD_ALT = 13
    FOURTH_ALT = 14
    FIFTH_ALT = 15
    SIXTH_ALT = 16
    SEVENTH_ALT = 17
    EIGHTH_ALT = 18
    NINTH_ALT = 19
    GOTHIC = 20
    DOUBLE_UNDERLINE = 21
    RESET_BOLD_AND_FAINT = 22
    RESET_ITALIC_AND_GOTHIC = 23
    RESET_UNDERLINES = 24
    RESET_BLINKING = 25
    POSITIVE = 26
    REVEALED_CHARS = 28
    RESET_CROSSED_OUT = 29
    BLACK_FG = 30
    RED_FG = 31
    GREEN_FG = 32
    YELLOW_FG = 33
    BLUE_FG = 34
    MAGENTA_FG = 35
    CYAN_FG = 36
    WHITE_FG = 37
    ANSI_256_SET_FG = 38
    DEFAULT_FG_COLOR = 39
    BLACK_BG = 40
    RED_BG = 41
    GREEN_BG = 42
    YELLOW_BG = 43
    BLUE_BG = 44
    MAGENTA_BG = 45
    CYAN_BG = 46
    WHITE_BG = 47
    ANSI_256_SET_BG = 48
    DEFAULT_BG_COLOR = 49
    FRAMED = 50
    ENCIRCLED = 52
    OVERLINED = 53
    NOT_FRAMED_OR_CIRCLED = 54
    IDEOGRAM_UNDER_OR_RIGHT = 55
    IDEOGRAM_2UNDER_OR_2RIGHT = 60
    IDEOGRAM_OVER_OR_LEFT = 61
    IDEOGRAM_2OVER_OR_2LEFT = 62
    CANCEL = 63
    BLACK_BRIGHT_FG = 90
    RED_BRIGHT_FG = 91
    GREEN_BRIGHT_FG = 92
    YELLOW_BRIGHT_FG = 93
    BLUE_BRIGHT_FG = 94
    MAGENTA_BRIGHT_FG = 95
    CYAN_BRIGHT_FG = 96
    WHITE_BRIGHT_FG = 97
    BLACK_BRIGHT_BG = 100
    RED_BRIGHT_BG = 101
    GREEN_BRIGHT_BG = 102
    YELLOW_BRIGHT_BG = 103
    BLUE_BRIGHT_BG = 104
    MAGENTA_BRIGHT_BG = 105
    CYAN_BRIGHT_BG = 106
    WHITE_BRIGHT_BG = 107

    @ft.cached_property
    def flag(self) -> "SgrFlag":
        try:
            return SgrFlag[self.name]
        except KeyError:
            return SgrFlag(0)

RESET = 0 class-attribute instance-attribute

BOLD = 1 class-attribute instance-attribute

FAINT = 2 class-attribute instance-attribute

ITALICS = 3 class-attribute instance-attribute

SINGLE_UNDERLINE = 4 class-attribute instance-attribute

NEGATIVE = 7 class-attribute instance-attribute

CONCEALED_CHARS = 8 class-attribute instance-attribute

CROSSED_OUT = 9 class-attribute instance-attribute

PRIMARY = 10 class-attribute instance-attribute

FIRST_ALT = 11 class-attribute instance-attribute

SECOND_ALT = 12 class-attribute instance-attribute

THIRD_ALT = 13 class-attribute instance-attribute

FOURTH_ALT = 14 class-attribute instance-attribute

FIFTH_ALT = 15 class-attribute instance-attribute

SIXTH_ALT = 16 class-attribute instance-attribute

SEVENTH_ALT = 17 class-attribute instance-attribute

EIGHTH_ALT = 18 class-attribute instance-attribute

NINTH_ALT = 19 class-attribute instance-attribute

GOTHIC = 20 class-attribute instance-attribute

DOUBLE_UNDERLINE = 21 class-attribute instance-attribute

RESET_BOLD_AND_FAINT = 22 class-attribute instance-attribute

RESET_ITALIC_AND_GOTHIC = 23 class-attribute instance-attribute

RESET_UNDERLINES = 24 class-attribute instance-attribute

RESET_BLINKING = 25 class-attribute instance-attribute

POSITIVE = 26 class-attribute instance-attribute

REVEALED_CHARS = 28 class-attribute instance-attribute

RESET_CROSSED_OUT = 29 class-attribute instance-attribute

BLACK_FG = 30 class-attribute instance-attribute

RED_FG = 31 class-attribute instance-attribute

GREEN_FG = 32 class-attribute instance-attribute

YELLOW_FG = 33 class-attribute instance-attribute

BLUE_FG = 34 class-attribute instance-attribute

MAGENTA_FG = 35 class-attribute instance-attribute

CYAN_FG = 36 class-attribute instance-attribute

WHITE_FG = 37 class-attribute instance-attribute

ANSI_256_SET_FG = 38 class-attribute instance-attribute

DEFAULT_FG_COLOR = 39 class-attribute instance-attribute

BLACK_BG = 40 class-attribute instance-attribute

RED_BG = 41 class-attribute instance-attribute

GREEN_BG = 42 class-attribute instance-attribute

YELLOW_BG = 43 class-attribute instance-attribute

BLUE_BG = 44 class-attribute instance-attribute

MAGENTA_BG = 45 class-attribute instance-attribute

CYAN_BG = 46 class-attribute instance-attribute

WHITE_BG = 47 class-attribute instance-attribute

ANSI_256_SET_BG = 48 class-attribute instance-attribute

DEFAULT_BG_COLOR = 49 class-attribute instance-attribute

FRAMED = 50 class-attribute instance-attribute

ENCIRCLED = 52 class-attribute instance-attribute

OVERLINED = 53 class-attribute instance-attribute

NOT_FRAMED_OR_CIRCLED = 54 class-attribute instance-attribute

IDEOGRAM_UNDER_OR_RIGHT = 55 class-attribute instance-attribute

IDEOGRAM_2UNDER_OR_2RIGHT = 60 class-attribute instance-attribute

IDEOGRAM_OVER_OR_LEFT = 61 class-attribute instance-attribute

IDEOGRAM_2OVER_OR_2LEFT = 62 class-attribute instance-attribute

CANCEL = 63 class-attribute instance-attribute

BLACK_BRIGHT_FG = 90 class-attribute instance-attribute

RED_BRIGHT_FG = 91 class-attribute instance-attribute

GREEN_BRIGHT_FG = 92 class-attribute instance-attribute

YELLOW_BRIGHT_FG = 93 class-attribute instance-attribute

BLUE_BRIGHT_FG = 94 class-attribute instance-attribute

MAGENTA_BRIGHT_FG = 95 class-attribute instance-attribute

CYAN_BRIGHT_FG = 96 class-attribute instance-attribute

WHITE_BRIGHT_FG = 97 class-attribute instance-attribute

BLACK_BRIGHT_BG = 100 class-attribute instance-attribute

RED_BRIGHT_BG = 101 class-attribute instance-attribute

GREEN_BRIGHT_BG = 102 class-attribute instance-attribute

YELLOW_BRIGHT_BG = 103 class-attribute instance-attribute

BLUE_BRIGHT_BG = 104 class-attribute instance-attribute

MAGENTA_BRIGHT_BG = 105 class-attribute instance-attribute

CYAN_BRIGHT_BG = 106 class-attribute instance-attribute

WHITE_BRIGHT_BG = 107 class-attribute instance-attribute

flag cached property

SgrSequence

Bases: MutableSequence[SgrParamBuffer]

Construct a mutable sequence of SGR code bytes.

Source code in chromatic/color/core.py
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
class SgrSequence(abc.MutableSequence[SgrParamBuffer]):
    """Construct a mutable sequence of SGR code bytes."""

    _idx_attrs = ("_fg_idx", "_bg_idx")
    _key2idx = mappingproxy(dict(zip(("fg", "bg"), _idx_attrs)))
    _reset2idx = mappingproxy(dict(zip((b"39", b"49"), _idx_attrs)))
    __match_args__ = ("_sgr_params",)
    __slots__ = __match_args__ + _idx_attrs

    class _color_descriptor:
        def __set_name__(self, objtype, name, /):
            self.__objclass__ = objtype
            self.key = name
            self.idx = f"_{name}_idx"
            assert self.idx in objtype._idx_attrs

        def __get__(self, inst, objtype=None):
            if inst is None:
                return self
            try:
                idx = getattr(inst, self.idx)
            except AttributeError:
                params = inst._sgr_params
                for i in reversed(range(len(params))):
                    x = params[i]
                    if x == b"0" or inst._reset2idx.get(x) == self.idx:
                        break
                    if not x.is_color():
                        continue
                    rgb = x._value.rgb_dict
                    if self.key in rgb:
                        setattr(inst, self.idx, i)
                        return rgb[self.key]
                setattr(inst, self.idx, None)
                return
            else:
                if idx is None:
                    return
                rgb = inst._sgr_params[idx]._value.rgb_dict
                return rgb[self.key]

        def __set__(self, inst, value, /):
            if inst is None:
                raise TypeError
            if value is None:
                return delattr(inst, self.key)
            params = inst._sgr_params
            idx = hi = None
            for i in reversed(range(len(params))):
                x = params[i]
                if x == b"0" or inst._reset2idx.get(x) == self.idx:
                    return setattr(inst, self.idx, None)
                if not x.is_color():
                    continue
                rgb = x._value.rgb_dict
                if self.key in rgb:
                    if rgb[self.key] != value:
                        if hi is None:
                            hi = i
                        continue
                    elif hi is None:
                        return setattr(inst, self.idx, i)
                    idx = i
                    break
            else:
                raise ValueError
            x = params[idx]
            params[idx] = params[hi]
            params[hi] = x
            setattr(inst, self.idx, hi)

        def __delete__(self, inst, /):
            if inst is None:
                raise TypeError
            idx = getattr(inst, self.idx, None)
            if idx is None:
                return
            params = inst._sgr_params
            new_idx = None
            for i in reversed(range(len(params))):
                if i == idx:
                    continue
                x = params[i]
                if not x.is_color():
                    continue
                if self.key in x._value.rgb_dict:
                    new_idx = i
                    break
            setattr(inst, self.idx, new_idx)

    fg = _color_descriptor()
    bg = _color_descriptor()

    def _invalidate_indices(self):
        for idx_attr in self._idx_attrs:
            try:
                delattr(self, idx_attr)
            except AttributeError:
                pass

    def insert(self, index, value, /):
        value = SgrParamBuffer(value)
        params = self._sgr_params
        n = len(params)
        if index < 0:
            index = max(0, n + index)
        elif index > n:
            index = n
        params.insert(index, value)
        if value == b"0":
            self._invalidate_indices()
        elif idx_attr := self._reset2idx.get(value):
            try:
                delattr(self, idx_attr)
            except AttributeError:
                pass
        else:
            keys = value._value.rgb_dict if value.is_color() else ()
            for k, idx_attr in self._key2idx.items():
                try:
                    cur = getattr(self, idx_attr)
                except AttributeError:
                    continue
                if cur is not None and cur >= index:
                    cur += 1
                if k in keys and (cur is None or cur < index):
                    cur = index
                setattr(self, idx_attr, cur)

    def extend(self, iterable, /):
        return super().extend(map(SgrParamBuffer, _iter_sgr(iterable)))

    def is_color(self):
        return bool(self.fg or self.bg)

    def is_reset(self):
        return any(p.is_reset() for p in self)

    def values(self):
        for p in self._sgr_params:
            yield p._value

    def ansi_type(self):
        if self.is_color():
            typ, _ = max(
                Counter(x._value.__class__ for x in self if x.is_color()).items(),
                key=lambda x: x[1],
            )
            return typ

    def shrink(self):
        """Mutate self in-place by removing redundant codes from the sequence.

        Specifically what is removed:

        - codes that occur before a ``b"0"``
        - fg / bg colors occurring before a respective reset code
            and vice-versa, or a subsequent color of the same kind
        - duplicate codes (the highest-index occurrence is kept)

        """

        K2I = {
            k: i for i, ks in enumerate(zip((b"39", b"49"), ("fg", "bg"))) for k in ks
        }
        buf = []
        seen = set()
        seen_colors = [False] * 2
        for x in reversed(self):
            if x in seen:
                continue
            seen.add(x)
            v = x._value
            if v == b"0":
                buf.append(x)
                break
            elif v in K2I or x.is_color():
                idx = K2I[getattr(v, "kind", lambda: v)()]
                if seen_colors[idx]:
                    continue
                seen_colors[idx] = True
            buf.append(x)
        self[:] = buf[::-1]

    def __add__(self, other, /):
        if isinstance(other, self.__class__):
            return self.__class__(x for xs in (self, other) for x in xs)
        return NotImplemented

    def __bool__(self):
        return bool(self._sgr_params)

    def __bytes__(self):
        return _concat_ansi_escape(self.values()) if self else b""

    def __copy__(self):
        inst = object.__new__(self.__class__)
        inst._sgr_params = self._sgr_params.copy()
        for attr in self._idx_attrs:
            try:
                idx = getattr(self, attr)
            except AttributeError:
                continue
            setattr(inst, attr, idx)
        return inst

    copy = __copy__

    def __deepcopy__(self, memo, /):
        inst = memo[id(self)] = object.__new__(self.__class__)
        inst._sgr_params = deepcopy(self._sgr_params, memo)
        for attr in self._idx_attrs:
            try:
                idx = getattr(self, attr)
            except AttributeError:
                continue
            setattr(inst, attr, idx)
        return inst

    def __delitem__(self, index, /):
        del self._sgr_params[index]
        self._invalidate_indices()

    def __eq__(self, other, /):
        if isinstance(other, SgrSequence):
            return bytes(self) == bytes(other)
        return NotImplemented

    def __getitem__(self, index, /):
        return self._sgr_params[index]

    def __init__(self, iterable=None, /) -> None:
        if iterable is None:
            self._sgr_params = []
        elif isinstance(iterable, SgrSequence):
            self._sgr_params = iterable._sgr_params.copy()
            for attr in self._idx_attrs:
                try:
                    idx = getattr(iterable, attr)
                except AttributeError:
                    continue
                setattr(self, attr, idx)
        else:
            self._sgr_params = [SgrParamBuffer(x) for x in _iter_sgr(iterable)]

    def __iter__(self) -> abc.Iterator[SgrParamBuffer]:
        return iter(self._sgr_params)

    def __len__(self):
        return len(self._sgr_params)

    def __repr__(self):
        return f"{self.__class__.__name__}({list(self.values())})"

    def __setitem__(self, index, value, /):
        iterable = map(SgrParamBuffer, _iter_sgr(value))
        if isinstance(index, slice):
            self._sgr_params[index] = iterable
        else:
            [item] = iterable
            self._sgr_params[index] = item
        self._invalidate_indices()

    def __str__(self):
        return bytes(self).decode()

    __hash__ = None

    def clear_colors(self):
        """Remove all `colorbytes` values from self"""
        self._sgr_params[:] = [p for p in self._sgr_params if not p.is_color()]
        self._bg_idx = self._fg_idx = None

    def set_colors(self, iterable, /, ansi_type=None):
        """Set the active colors to the given dict or dict items, and remove
        the previous active colors from the sequence if they existed.

        Values of None mean 'clear color', so
        ``sgr.set_colors({"fg": None, "bg": None})`` is the same as
        ``sgr.clear_colors()``.
        """
        new_colors = dict(iterable)
        if not new_colors:
            return
        new_keys = new_colors.keys()
        keys = self._key2idx.keys()
        if not new_keys <= keys:
            raise ValueError
        if len(new_keys) == 2 and all(v is None for v in new_colors.values()):
            return self.clear_colors()
        if ansi_type is None:
            ansi_type = DEFAULT_ANSI
        self._sgr_params[:] = [
            p
            for p in self._sgr_params
            if not p.is_color() or p._value.rgb_dict.keys().isdisjoint(new_colors)
        ]
        for k in keys - new_keys:
            try:
                delattr(self, self._key2idx[k])
            except AttributeError:
                pass
        for k, v in new_colors.items():
            idx_attr = self._key2idx[k]
            if v is None:
                setattr(self, idx_attr, None)
            else:
                new_idx = len(self._sgr_params)
                x = ansi_type.from_rgb((k, v)).to_param_buffer()
                self._sgr_params.append(x)
                setattr(self, idx_attr, new_idx)

    def _rgb_dict_get(self):
        d = {}
        if (bg := self.bg) is not None:
            d["bg"] = bg
        if (fg := self.fg) is not None:
            d["fg"] = fg
        return d

    rgb_dict = property(_rgb_dict_get, set_colors, clear_colors)

__match_args__ = ('_sgr_params',) class-attribute instance-attribute

__slots__ = ('_sgr_params', '_fg_idx', '_bg_idx') class-attribute instance-attribute

fg = _color_descriptor() class-attribute instance-attribute

bg = _color_descriptor() class-attribute instance-attribute

copy = __copy__ class-attribute instance-attribute

__hash__ = None class-attribute instance-attribute

rgb_dict = property(_rgb_dict_get, set_colors, clear_colors) class-attribute instance-attribute

insert(index, value)

Source code in chromatic/color/core.py
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
def insert(self, index, value, /):
    value = SgrParamBuffer(value)
    params = self._sgr_params
    n = len(params)
    if index < 0:
        index = max(0, n + index)
    elif index > n:
        index = n
    params.insert(index, value)
    if value == b"0":
        self._invalidate_indices()
    elif idx_attr := self._reset2idx.get(value):
        try:
            delattr(self, idx_attr)
        except AttributeError:
            pass
    else:
        keys = value._value.rgb_dict if value.is_color() else ()
        for k, idx_attr in self._key2idx.items():
            try:
                cur = getattr(self, idx_attr)
            except AttributeError:
                continue
            if cur is not None and cur >= index:
                cur += 1
            if k in keys and (cur is None or cur < index):
                cur = index
            setattr(self, idx_attr, cur)

extend(iterable)

Source code in chromatic/color/core.py
910
911
def extend(self, iterable, /):
    return super().extend(map(SgrParamBuffer, _iter_sgr(iterable)))

is_color()

Source code in chromatic/color/core.py
913
914
def is_color(self):
    return bool(self.fg or self.bg)

is_reset()

Source code in chromatic/color/core.py
916
917
def is_reset(self):
    return any(p.is_reset() for p in self)

values()

Source code in chromatic/color/core.py
919
920
921
def values(self):
    for p in self._sgr_params:
        yield p._value

ansi_type()

Source code in chromatic/color/core.py
923
924
925
926
927
928
929
def ansi_type(self):
    if self.is_color():
        typ, _ = max(
            Counter(x._value.__class__ for x in self if x.is_color()).items(),
            key=lambda x: x[1],
        )
        return typ

shrink()

Mutate self in-place by removing redundant codes from the sequence.

Specifically what is removed:

  • codes that occur before a b"0"
  • fg / bg colors occurring before a respective reset code and vice-versa, or a subsequent color of the same kind
  • duplicate codes (the highest-index occurrence is kept)
Source code in chromatic/color/core.py
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
def shrink(self):
    """Mutate self in-place by removing redundant codes from the sequence.

    Specifically what is removed:

    - codes that occur before a ``b"0"``
    - fg / bg colors occurring before a respective reset code
        and vice-versa, or a subsequent color of the same kind
    - duplicate codes (the highest-index occurrence is kept)

    """

    K2I = {
        k: i for i, ks in enumerate(zip((b"39", b"49"), ("fg", "bg"))) for k in ks
    }
    buf = []
    seen = set()
    seen_colors = [False] * 2
    for x in reversed(self):
        if x in seen:
            continue
        seen.add(x)
        v = x._value
        if v == b"0":
            buf.append(x)
            break
        elif v in K2I or x.is_color():
            idx = K2I[getattr(v, "kind", lambda: v)()]
            if seen_colors[idx]:
                continue
            seen_colors[idx] = True
        buf.append(x)
    self[:] = buf[::-1]

__add__(other)

Source code in chromatic/color/core.py
965
966
967
968
def __add__(self, other, /):
    if isinstance(other, self.__class__):
        return self.__class__(x for xs in (self, other) for x in xs)
    return NotImplemented

__bool__()

Source code in chromatic/color/core.py
970
971
def __bool__(self):
    return bool(self._sgr_params)

__bytes__()

Source code in chromatic/color/core.py
973
974
def __bytes__(self):
    return _concat_ansi_escape(self.values()) if self else b""

__copy__()

Source code in chromatic/color/core.py
976
977
978
979
980
981
982
983
984
985
def __copy__(self):
    inst = object.__new__(self.__class__)
    inst._sgr_params = self._sgr_params.copy()
    for attr in self._idx_attrs:
        try:
            idx = getattr(self, attr)
        except AttributeError:
            continue
        setattr(inst, attr, idx)
    return inst

__deepcopy__(memo)

Source code in chromatic/color/core.py
989
990
991
992
993
994
995
996
997
998
def __deepcopy__(self, memo, /):
    inst = memo[id(self)] = object.__new__(self.__class__)
    inst._sgr_params = deepcopy(self._sgr_params, memo)
    for attr in self._idx_attrs:
        try:
            idx = getattr(self, attr)
        except AttributeError:
            continue
        setattr(inst, attr, idx)
    return inst

__delitem__(index)

__delitem__(index: tp.SupportsIndex) -> None
__delitem__(index: slice) -> None
Source code in chromatic/color/core.py
1000
1001
1002
def __delitem__(self, index, /):
    del self._sgr_params[index]
    self._invalidate_indices()

__eq__(other)

Source code in chromatic/color/core.py
1004
1005
1006
1007
def __eq__(self, other, /):
    if isinstance(other, SgrSequence):
        return bytes(self) == bytes(other)
    return NotImplemented

__getitem__(index)

__getitem__(index: tp.SupportsIndex) -> SgrParamBuffer
__getitem__(index: slice) -> list[SgrParamBuffer]
Source code in chromatic/color/core.py
1009
1010
def __getitem__(self, index, /):
    return self._sgr_params[index]

__init__(iterable=None)

Source code in chromatic/color/core.py
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
def __init__(self, iterable=None, /) -> None:
    if iterable is None:
        self._sgr_params = []
    elif isinstance(iterable, SgrSequence):
        self._sgr_params = iterable._sgr_params.copy()
        for attr in self._idx_attrs:
            try:
                idx = getattr(iterable, attr)
            except AttributeError:
                continue
            setattr(self, attr, idx)
    else:
        self._sgr_params = [SgrParamBuffer(x) for x in _iter_sgr(iterable)]

__iter__()

Source code in chromatic/color/core.py
1026
1027
def __iter__(self) -> abc.Iterator[SgrParamBuffer]:
    return iter(self._sgr_params)

__len__()

Source code in chromatic/color/core.py
1029
1030
def __len__(self):
    return len(self._sgr_params)

__repr__()

Source code in chromatic/color/core.py
1032
1033
def __repr__(self):
    return f"{self.__class__.__name__}({list(self.values())})"

__setitem__(index, value)

__setitem__(index: tp.SupportsIndex, value: bytes | SgrParamBuffer) -> None
__setitem__(index: slice, value: abc.Iterable[bytes | SgrParamBuffer]) -> None
Source code in chromatic/color/core.py
1035
1036
1037
1038
1039
1040
1041
1042
def __setitem__(self, index, value, /):
    iterable = map(SgrParamBuffer, _iter_sgr(value))
    if isinstance(index, slice):
        self._sgr_params[index] = iterable
    else:
        [item] = iterable
        self._sgr_params[index] = item
    self._invalidate_indices()

__str__()

Source code in chromatic/color/core.py
1044
1045
def __str__(self):
    return bytes(self).decode()

clear_colors()

Remove all colorbytes values from self

Source code in chromatic/color/core.py
1049
1050
1051
1052
def clear_colors(self):
    """Remove all `colorbytes` values from self"""
    self._sgr_params[:] = [p for p in self._sgr_params if not p.is_color()]
    self._bg_idx = self._fg_idx = None

set_colors(iterable, /, ansi_type=None)

set_colors(mapping: SupportsKeysAndGetItem[ColorDictKeys, Int3Tuple | None], /, ansi_type: AnsiColorParam | None = None) -> None
set_colors(iterable: abc.Iterable[tuple[ColorDictKeys, Int3Tuple | None]], /, ansi_type: AnsiColorParam | None = None) -> None

Set the active colors to the given dict or dict items, and remove the previous active colors from the sequence if they existed.

Values of None mean 'clear color', so sgr.set_colors({"fg": None, "bg": None}) is the same as sgr.clear_colors().

Source code in chromatic/color/core.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
def set_colors(self, iterable, /, ansi_type=None):
    """Set the active colors to the given dict or dict items, and remove
    the previous active colors from the sequence if they existed.

    Values of None mean 'clear color', so
    ``sgr.set_colors({"fg": None, "bg": None})`` is the same as
    ``sgr.clear_colors()``.
    """
    new_colors = dict(iterable)
    if not new_colors:
        return
    new_keys = new_colors.keys()
    keys = self._key2idx.keys()
    if not new_keys <= keys:
        raise ValueError
    if len(new_keys) == 2 and all(v is None for v in new_colors.values()):
        return self.clear_colors()
    if ansi_type is None:
        ansi_type = DEFAULT_ANSI
    self._sgr_params[:] = [
        p
        for p in self._sgr_params
        if not p.is_color() or p._value.rgb_dict.keys().isdisjoint(new_colors)
    ]
    for k in keys - new_keys:
        try:
            delattr(self, self._key2idx[k])
        except AttributeError:
            pass
    for k, v in new_colors.items():
        idx_attr = self._key2idx[k]
        if v is None:
            setattr(self, idx_attr, None)
        else:
            new_idx = len(self._sgr_params)
            x = ansi_type.from_rgb((k, v)).to_param_buffer()
            self._sgr_params.append(x)
            setattr(self, idx_attr, new_idx)

ansicolor4Bit

Bases: colorbytes

ANSI 4-bit color format.

Notes

Supports 16 colors.

+-------+---------+
| index |  color  |
+-------+---------+
|     0 | black   |
|     1 | red     |
|     2 | green   |
|     3 | yellow  |
|     4 | blue    |
|     5 | magenta |
|     6 | cyan    |
|     7 | white   |
+-------+---------+

Each color has a bright variant at index + 60.

Color codes use escape sequences of the form:

  • CSI 30–37 m for foreground colors.
  • CSI 40–47 m for background colors.
  • CSI 90–97 m for foreground colors (bright).
  • CSI 100–107 m for background colors (bright).

Where CSI (Control Sequence Introducer) is ESC[.

Examples:

  • bright red fg: ESC[91m
  • standard green bg: ESC[42m
  • bright white bg, black fg: ESC[107;30m
Source code in chromatic/color/core.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
class ansicolor4Bit(colorbytes):
    """ANSI 4-bit color format.

    Notes
    -----
    Supports 16 colors.

        +-------+---------+
        | index |  color  |
        +-------+---------+
        |     0 | black   |
        |     1 | red     |
        |     2 | green   |
        |     3 | yellow  |
        |     4 | blue    |
        |     5 | magenta |
        |     6 | cyan    |
        |     7 | white   |
        +-------+---------+

    Each color has a bright variant at ``index + 60``.

    Color codes use escape sequences of the form:

    - `CSI 30–37 m` for foreground colors.
    - `CSI 40–47 m` for background colors.
    - `CSI 90–97 m` for foreground colors (bright).
    - `CSI 100–107 m` for background colors (bright).

    Where `CSI` (Control Sequence Introducer) is `ESC[`.

    Examples
    --------

    - bright red fg: `ESC[91m`
    - standard green bg: `ESC[42m`
    - bright white bg, black fg: `ESC[107;30m`

    """

    alias = "4b"
    typecode = 1

alias = '4b' class-attribute instance-attribute

typecode = 1 class-attribute instance-attribute

ansicolor8Bit

Bases: colorbytes

ANSI 8-Bit color format.

Notes

Supports 256 colors, mapped to the following value ranges:

  • (0, 15): Corresponds to ANSI 4-bit colors.
  • (16, 231): Represents a 6x6x6 RGB color cube.
  • (232, 255): Greyscale colors, from black to white.

Color codes use escape sequences of the form:

  • CSI 38;5;(n) m for foreground colors.
  • CSI 48;5;(n) m for background colors.

Where CSI (Control Sequence Introducer) is ESC[ and n is an unsigned 8-bit integer.

Examples:

  • white bg: ESC[48;5;255m
  • bright red fg (ANSI 4-bit): ESC[38;5;9m
  • bright red fg (color cube): ESC[38;5;196m
Source code in chromatic/color/core.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
class ansicolor8Bit(colorbytes):
    """ANSI 8-Bit color format.

    Notes
    -----
    Supports 256 colors, mapped to the following value ranges:

    - ``(0, 15)``: Corresponds to ANSI 4-bit colors.
    - ``(16, 231)``: Represents a 6x6x6 RGB color cube.
    - ``(232, 255)``: Greyscale colors, from black to white.

    Color codes use escape sequences of the form:

    - `CSI 38;5;(n) m` for foreground colors.
    - `CSI 48;5;(n) m` for background colors.

    Where `CSI` (Control Sequence Introducer) is `ESC[` and `n` is an unsigned 8-bit integer.

    Examples
    --------

    - white bg: `ESC[48;5;255m`
    - bright red fg (ANSI 4-bit): `ESC[38;5;9m`
    - bright red fg (color cube): `ESC[38;5;196m`

    """

    alias = "8b"
    typecode = 2

alias = '8b' class-attribute instance-attribute

typecode = 2 class-attribute instance-attribute

ansicolor24Bit

Bases: colorbytes

ANSI 24-Bit color format.

Notes

Supports all colors in the RGB color space (16,777,216 total).

Color codes use escape sequences of the form:

  • CSI 38;2;(r);(g);(b) m for foreground colors.
  • CSI 48;2;(r);(g);(b) m for background colors.

Where CSI (Control Sequence Introducer) is ESC[ and r,g,b are unsigned 8-bit integers.

Examples:

  • red fg: ESC[38;2;255;85;85m
  • black bg: ESC[48;2;0;0;0m
  • white fg, green bg: ESC[38;2;255;255;255;48;2;0;170;0m
Source code in chromatic/color/core.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
class ansicolor24Bit(colorbytes):
    """ANSI 24-Bit color format.

    Notes
    -----
    Supports all colors in the RGB color space (16,777,216 total).

    Color codes use escape sequences of the form:

    - `CSI 38;2;(r);(g);(b) m` for foreground colors.
    - `CSI 48;2;(r);(g);(b) m` for background colors.

    Where `CSI` (Control Sequence Introducer) is `ESC[` and `r,g,b` are unsigned 8-bit integers.

    Examples
    --------

    - red fg: `ESC[38;2;255;85;85m`
    - black bg: `ESC[48;2;0;0;0m`
    - white fg, green bg: `ESC[38;2;255;255;255;48;2;0;170;0m`

    """

    alias = "24b"
    typecode = 3

alias = '24b' class-attribute instance-attribute

typecode = 3 class-attribute instance-attribute

color_chain

Bases: MutableSequence[tuple[SgrSequence, str]]

Source code in chromatic/color/core.py
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
class color_chain(abc.MutableSequence[tuple[SgrSequence, str]]):
    __slots__ = ("_ansi_type", "_items")
    __match_args__ = ("_items",)

    dtype = ColorChainDType

    def __array__(self, dtype=None, copy=None):
        if dtype is None:
            dtype = self.dtype
        elif not np.issubdtype(dtype, self.dtype):
            raise TypeError(
                "only subdtypes of {.dtype} are allowed, got {}".format(self, dtype)
            )
        if copy is False:
            raise ValueError("`copy=False` isn't supported. a copy is always created")
        flags = 0
        rgb = np.zeros((2, 4), dtype="u1")
        buf: list[tuple[str, int, np.ndarray]] = []
        RESET = SgrParameter(0).flag
        K2I = tuple(
            (k, idx_attr, i, SgrParameter(x).flag)
            for i, ((k, idx_attr), x) in enumerate(
                zip(SgrSequence._key2idx.items(), (39, 49))
            )
        )
        for sgr, s in self:
            for p in sgr:
                if p.is_color():
                    continue
                v = int(p._value)
                if v == 0:
                    flags = rgb[:] = 0
                elif v in {39, 49}:
                    rgb[0 if v == 39 else 1] = 0
                flags |= SgrParameter(v).flag
            for k, idx_attr, i, r in K2I:
                cur_rgb = getattr(sgr, k, None)
                if not cur_rgb:
                    continue
                idx = getattr(sgr, idx_attr)
                p = sgr[idx]._value
                rgb[i] = [p.typecode, *cur_rgb]
                flags &= ~r
            if not s:
                continue
            buf.append((s, flags, rgb.copy()))
            flags &= ~RESET
        if not buf:
            return np.empty(0, dtype=dtype)
        strs, mask_flags, mask_rgb = zip(*buf)
        lengths = np.fromiter(map(len, strs), dtype=np.intp, count=len(strs))
        arr = np.empty(lengths.sum(), dtype=dtype)
        if not arr.size:
            return arr
        arr["char"] = np.frombuffer("".join(strs).encode("utf-32-le"), dtype="<U1")
        arr["sgr"] = np.repeat(np.asarray(mask_flags, dtype="<u8"), lengths)
        arr["rgb"] = np.repeat(np.stack(mask_rgb), lengths, axis=0)
        return arr if dtype is None else arr.astype(dtype, copy=False)

    @classmethod
    def fromarray(cls, arr, /, *, ansi_type=None) -> tp.Self:
        arr = np.asarray(arr, dtype=cls.dtype)
        if arr.ndim > 2:
            raise ValueError
        elif arr.ndim == 2:
            newlines = np.zeros((arr.shape[0], 1), dtype=cls.dtype)
            newlines["char"][:-1] = "\n"
            if arr.shape[1]:
                newlines["rgb"] = arr["rgb"][:, -1:]
            arr = np.concatenate((arr, newlines), axis=1)
        arr = arr.reshape(-1)
        n = arr.size
        if not n:
            return cls(ansi_type=ansi_type)
        changed = np.zeros(n, dtype=bool)
        changed[0] = True
        changed[1:] = (
            (arr["sgr"][1:] != arr["sgr"][:-1]) |
            (arr["rgb"][1:] != arr["rgb"][:-1]).any(axis=(1, 2))
        )   # fmt: skip
        prev_flags = 0
        prev_rgb = np.zeros((2, 4), dtype="u1")
        RESET = SgrParameter(0).flag
        CLEAR_COLOR = RESET | SgrParameter(39).flag | SgrParameter(49).flag
        buf: list[tuple[SgrSequence, str]] = []
        for start, stop in pairwise(np.flatnonzero(changed).tolist() + [n]):
            diff_flags = cur_flags = int(arr["sgr"][start])
            cur_rgb = arr["rgb"][start]
            diff_rgb = ((i, k) for i, k in enumerate(("fg", "bg")) if cur_rgb[i, 0])
            # if flags have not changed and current flags do not have reset-bit set,
            # subtract previous flags and filter rgb by delta.
            if not ((prev_flags & ~cur_flags) or cur_flags & RESET):
                diff_flags &= ~prev_flags
                diff_rgb = (
                    (i, k) for i, k in diff_rgb if (cur_rgb[i] != prev_rgb[i]).any()
                )
            sgr = SgrSequence(SgrFlag(diff_flags).parameters)
            for i, k in diff_rgb:
                typecode, r, g, b = cur_rgb[i].tolist()
                sgr.set_colors({k: (r, g, b)}, _ANSI_FORMAT_MAP[typecode])
            buf.append((sgr, "".join(arr["char"][start:stop])))
            prev_flags, prev_rgb = cur_flags & ~CLEAR_COLOR, cur_rgb
        return cls(buf, ansi_type=ansi_type)

    @staticmethod
    def _coerce(item, /) -> abc.Iterator[tuple[SgrSequence, str]]:
        match item:
            case (SgrSequence() as sgr, _ as s) | ColorStr(
                _sgr=sgr, base_str=_ as s
            ) if s.__class__ is str:
                yield (sgr.copy(), s)
            case str() as s:
                if spans := [m.span(0) for m in sgr_pattern().finditer(s)]:
                    [ix0, *bounds] = [
                        slice(*x)
                        for i, span in enumerate(spans)
                        for x in [
                            (None if i == 0 else spans[i - 1][1], span[0]),
                            (span[0] + 2, span[1] - 1),
                        ]
                    ]
                    if s0 := s[ix0]:
                        yield (SgrSequence(), s0)
                    if not bounds:
                        return
                    bounds.append(slice(spans[-1][1], None))
                    sgr_prev: SgrSequence | None = None
                    for ix_sgr, ix_s in zip(bounds[::2], bounds[1::2], strict=True):
                        params = (
                            int(n or 0) for n in s[ix_sgr].removesuffix(";").split(";")
                        )
                        if sn := s[ix_s]:
                            if sgr_prev is None:
                                yield (SgrSequence(params), sn)
                            else:
                                sgr_prev.extend(params)
                                yield (sgr_prev, sn)
                                sgr_prev = None
                        elif sgr_prev is None:
                            sgr_prev = SgrSequence(params)
                        else:
                            sgr_prev.extend(params)
                    if sgr_prev is not None:
                        yield (sgr_prev, "")
                else:
                    yield (SgrSequence(), s)
            case SgrSequence() as sgr:
                yield (sgr, "")
            case _:
                raise TypeError

    def _handle_sgr[_T: SgrSequence](self, sgr: _T, /) -> _T:
        if (
            (ansi_type := self._ansi_type) is not None
            and sgr.is_color()
            and any(
                sgr[getattr(sgr, sgr._key2idx[k])].__class__ is not ansi_type
                for k in sgr.rgb_dict
            )
        ):
            sgr.set_colors(sgr.rgb_dict, ansi_type)
        return sgr

    def insert(self, index, value, /):
        [(sgr, s)] = self._coerce(value)
        self._items.insert(index, (self._handle_sgr(sgr), s))

    def shrink(self):
        """Mutate self in-place by joining SGR sequences for spans of empty string parts
        and vice-versa.

        This operation removes items from the sequence, so prior length assumptions
        should be considered invalidated by calling this method.
        """
        maxlen = len(self)
        if maxlen <= 1:
            return
        buf = []
        it = enumerate(self)
        for idx, (sgr, s) in it:
            while idx + 1 < maxlen and not s:
                idx, (_sgr, s) = next(it)
                sgr += _sgr
            sgr.shrink()
            buf.append((sgr, s))
        idx = len(buf) - 1
        while idx > 0:
            sgr, s = buf[idx]
            while idx - 1 >= 0 and not sgr:
                buf[idx] = None
                idx -= 1
                sgr, _s = buf[idx]
                s = _s + s
            buf[idx] = sgr, s
            idx -= 1
        self[:] = filter(None, buf)

    def splitlines(self):
        if not self:
            return []
        pend_cr = opened = False
        buf, out = [], []
        carry = SgrSequence()
        for sgr, s in self:
            if s:
                if pend_cr:
                    s = s.removeprefix("\n")
                pend_cr = s.endswith("\r")
            if s:
                # cpython/main/Objects/stringlib/split.h#L336
                # splitlines just for '\n'
                lines = []
                str_len = len(s)
                i = j = 0
                while i < str_len:
                    while i < str_len and s[i] != "\n":
                        i += 1
                    eol = i
                    if i < str_len:
                        i += 1
                    lines.append(s[j:eol])
                    j = i

                last = len(lines) - 1
                tail_open = s[-1] not in "\r\n\v\f"
                for i, line in enumerate(lines):
                    if not opened:
                        if carry:
                            buf.append((carry.copy(), ""))
                        opened = True
                    buf.append((sgr, line))
                    if i < last or not tail_open:
                        out.append(buf)
                        buf, opened = [], False
            elif opened:
                buf.append((sgr, ""))
            carry += sgr
            carry.shrink()
        if opened:
            out.append(buf)
        cls = self.__class__
        for i, line in enumerate(out):
            x = object.__new__(cls)
            x._ansi_type, x._items = self._ansi_type, line
            x.shrink()
            out[i] = x
        return out

    def term_array(self, shape=None, fillchar=""):
        if shape and not (
            isinstance(shape, abc.Sequence)
            and len(shape) == 2
            and all(isinstance(x, int) for x in shape)
        ):
            raise ValueError(f"expected 2d shape: {shape}")
        rows = [*map(np.array, self.splitlines())]
        h, w = (None, None) if shape is None else shape
        if w is not None:
            rows = [r[i : i + w] for r in rows for i in range(0, len(r) or 1, w)]
        if h is not None:
            del rows[h:]
            rows += [np.empty(0, self.dtype)] * (h - len(rows))
        if not rows:
            return np.zeros((0, 0), self.dtype)
        lengths = np.fromiter(map(len, rows), np.intp, len(rows))
        width = int(lengths.max(initial=0)) if w is None else w
        out = np.zeros((len(rows), width), self.dtype)
        mask = np.arange(width) < lengths[:, None]
        out[mask] = np.concatenate(rows)
        if fillchar:
            out["char"][~mask] = fillchar
        return out

    def __add__(self, other, /):
        if isinstance(other, str):
            return color_chain(f"{self}{other}")
        elif isinstance(other, color_chain):
            res = object.__new__(color_chain)
            res._ansi_type = self._ansi_type
            copied_self, copied_other = (
                ((sgr.copy(), s) for sgr, s in xs) for xs in (self, other)
            )
            if self._ansi_type is not other._ansi_type:
                copied_other = ((self._handle_sgr(sgr), s) for sgr, s in copied_other)
            res._items = [*copied_self, *copied_other]
            return res
        elif isinstance(other, abc.Iterable):
            return color_chain(
                (x for xs in (self, other) for x in xs), ansi_type=self._ansi_type
            )
        return NotImplemented

    def __bool__(self):
        return bool(self._items)

    def __call__(self, obj="", /):
        return f"{self}{obj}\x1b[0m"

    def __delitem__(self, index, /):
        del self._items[index]

    def __eq__(self, other, /):
        if isinstance(other, color_chain):
            return self._items == other._items
        return NotImplemented

    def __getitem__(self, index, /):
        return self._items[index]

    def __init__(self, iterable=None, /, *, ansi_type=None):
        if ansi_type is not None:
            self._ansi_type = ansi_type = get_ansi_type(ansi_type)
        else:
            self._ansi_type = None
        if iterable is None:
            self._items = []
        elif isinstance(iterable, color_chain):
            copied = ((sgr.copy(), s) for sgr, s in iterable)
            self._items = (
                list(copied)
                if self._ansi_type is iterable._ansi_type
                else [(self._handle_sgr(sgr), s) for sgr, s in copied]
            )
        else:
            if isinstance(iterable, str):
                iterable = [iterable]
            self._items = [
                (self._handle_sgr(sgr), s)
                for item in iterable
                for sgr, s in self._coerce(item)
            ]

    def __len__(self):
        return len(self._items)

    def __radd__(self, other, /):
        if isinstance(other, str):
            return color_chain(f"{other}{self}")
        elif isinstance(other, abc.Iterable):
            return color_chain(
                (x for xs in (other, self) for x in xs), ansi_type=self._ansi_type
            )
        return NotImplemented

    def __repr__(self):
        constructor_args = repr([f"{sgr}{s}" for sgr, s in self])
        if self._ansi_type is not None:
            constructor_args += f", ansi_type={self._ansi_type.alias!r}"
        return "{.__class__.__name__}({})".format(self, constructor_args)

    def __setitem__(self, index, value, /):
        def _validate(obj, /):
            if (
                isinstance(obj, tuple)
                and len(obj) == 2
                and isinstance(obj[0], SgrSequence)
                and obj[1].__class__ is str
            ):
                sgr, s = obj
                return self._handle_sgr(sgr), s
            raise TypeError

        if isinstance(index, slice):
            self._items[index] = list(map(_validate, value))
        else:
            self._items[index] = _validate(value)

    def __str__(self):
        return "".join(f"{sgr}{s}" for sgr, s in self)

__slots__ = ('_ansi_type', '_items') class-attribute instance-attribute

__match_args__ = ('_items',) class-attribute instance-attribute

dtype = ColorChainDType class-attribute instance-attribute

__array__(dtype=None, copy=None)

Source code in chromatic/color/core.py
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
def __array__(self, dtype=None, copy=None):
    if dtype is None:
        dtype = self.dtype
    elif not np.issubdtype(dtype, self.dtype):
        raise TypeError(
            "only subdtypes of {.dtype} are allowed, got {}".format(self, dtype)
        )
    if copy is False:
        raise ValueError("`copy=False` isn't supported. a copy is always created")
    flags = 0
    rgb = np.zeros((2, 4), dtype="u1")
    buf: list[tuple[str, int, np.ndarray]] = []
    RESET = SgrParameter(0).flag
    K2I = tuple(
        (k, idx_attr, i, SgrParameter(x).flag)
        for i, ((k, idx_attr), x) in enumerate(
            zip(SgrSequence._key2idx.items(), (39, 49))
        )
    )
    for sgr, s in self:
        for p in sgr:
            if p.is_color():
                continue
            v = int(p._value)
            if v == 0:
                flags = rgb[:] = 0
            elif v in {39, 49}:
                rgb[0 if v == 39 else 1] = 0
            flags |= SgrParameter(v).flag
        for k, idx_attr, i, r in K2I:
            cur_rgb = getattr(sgr, k, None)
            if not cur_rgb:
                continue
            idx = getattr(sgr, idx_attr)
            p = sgr[idx]._value
            rgb[i] = [p.typecode, *cur_rgb]
            flags &= ~r
        if not s:
            continue
        buf.append((s, flags, rgb.copy()))
        flags &= ~RESET
    if not buf:
        return np.empty(0, dtype=dtype)
    strs, mask_flags, mask_rgb = zip(*buf)
    lengths = np.fromiter(map(len, strs), dtype=np.intp, count=len(strs))
    arr = np.empty(lengths.sum(), dtype=dtype)
    if not arr.size:
        return arr
    arr["char"] = np.frombuffer("".join(strs).encode("utf-32-le"), dtype="<U1")
    arr["sgr"] = np.repeat(np.asarray(mask_flags, dtype="<u8"), lengths)
    arr["rgb"] = np.repeat(np.stack(mask_rgb), lengths, axis=0)
    return arr if dtype is None else arr.astype(dtype, copy=False)

fromarray(arr, /, *, ansi_type=None) classmethod

Source code in chromatic/color/core.py
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
@classmethod
def fromarray(cls, arr, /, *, ansi_type=None) -> tp.Self:
    arr = np.asarray(arr, dtype=cls.dtype)
    if arr.ndim > 2:
        raise ValueError
    elif arr.ndim == 2:
        newlines = np.zeros((arr.shape[0], 1), dtype=cls.dtype)
        newlines["char"][:-1] = "\n"
        if arr.shape[1]:
            newlines["rgb"] = arr["rgb"][:, -1:]
        arr = np.concatenate((arr, newlines), axis=1)
    arr = arr.reshape(-1)
    n = arr.size
    if not n:
        return cls(ansi_type=ansi_type)
    changed = np.zeros(n, dtype=bool)
    changed[0] = True
    changed[1:] = (
        (arr["sgr"][1:] != arr["sgr"][:-1]) |
        (arr["rgb"][1:] != arr["rgb"][:-1]).any(axis=(1, 2))
    )   # fmt: skip
    prev_flags = 0
    prev_rgb = np.zeros((2, 4), dtype="u1")
    RESET = SgrParameter(0).flag
    CLEAR_COLOR = RESET | SgrParameter(39).flag | SgrParameter(49).flag
    buf: list[tuple[SgrSequence, str]] = []
    for start, stop in pairwise(np.flatnonzero(changed).tolist() + [n]):
        diff_flags = cur_flags = int(arr["sgr"][start])
        cur_rgb = arr["rgb"][start]
        diff_rgb = ((i, k) for i, k in enumerate(("fg", "bg")) if cur_rgb[i, 0])
        # if flags have not changed and current flags do not have reset-bit set,
        # subtract previous flags and filter rgb by delta.
        if not ((prev_flags & ~cur_flags) or cur_flags & RESET):
            diff_flags &= ~prev_flags
            diff_rgb = (
                (i, k) for i, k in diff_rgb if (cur_rgb[i] != prev_rgb[i]).any()
            )
        sgr = SgrSequence(SgrFlag(diff_flags).parameters)
        for i, k in diff_rgb:
            typecode, r, g, b = cur_rgb[i].tolist()
            sgr.set_colors({k: (r, g, b)}, _ANSI_FORMAT_MAP[typecode])
        buf.append((sgr, "".join(arr["char"][start:stop])))
        prev_flags, prev_rgb = cur_flags & ~CLEAR_COLOR, cur_rgb
    return cls(buf, ansi_type=ansi_type)

insert(index, value)

Source code in chromatic/color/core.py
1951
1952
1953
def insert(self, index, value, /):
    [(sgr, s)] = self._coerce(value)
    self._items.insert(index, (self._handle_sgr(sgr), s))

shrink()

Mutate self in-place by joining SGR sequences for spans of empty string parts and vice-versa.

This operation removes items from the sequence, so prior length assumptions should be considered invalidated by calling this method.

Source code in chromatic/color/core.py
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
def shrink(self):
    """Mutate self in-place by joining SGR sequences for spans of empty string parts
    and vice-versa.

    This operation removes items from the sequence, so prior length assumptions
    should be considered invalidated by calling this method.
    """
    maxlen = len(self)
    if maxlen <= 1:
        return
    buf = []
    it = enumerate(self)
    for idx, (sgr, s) in it:
        while idx + 1 < maxlen and not s:
            idx, (_sgr, s) = next(it)
            sgr += _sgr
        sgr.shrink()
        buf.append((sgr, s))
    idx = len(buf) - 1
    while idx > 0:
        sgr, s = buf[idx]
        while idx - 1 >= 0 and not sgr:
            buf[idx] = None
            idx -= 1
            sgr, _s = buf[idx]
            s = _s + s
        buf[idx] = sgr, s
        idx -= 1
    self[:] = filter(None, buf)

splitlines()

Source code in chromatic/color/core.py
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
def splitlines(self):
    if not self:
        return []
    pend_cr = opened = False
    buf, out = [], []
    carry = SgrSequence()
    for sgr, s in self:
        if s:
            if pend_cr:
                s = s.removeprefix("\n")
            pend_cr = s.endswith("\r")
        if s:
            # cpython/main/Objects/stringlib/split.h#L336
            # splitlines just for '\n'
            lines = []
            str_len = len(s)
            i = j = 0
            while i < str_len:
                while i < str_len and s[i] != "\n":
                    i += 1
                eol = i
                if i < str_len:
                    i += 1
                lines.append(s[j:eol])
                j = i

            last = len(lines) - 1
            tail_open = s[-1] not in "\r\n\v\f"
            for i, line in enumerate(lines):
                if not opened:
                    if carry:
                        buf.append((carry.copy(), ""))
                    opened = True
                buf.append((sgr, line))
                if i < last or not tail_open:
                    out.append(buf)
                    buf, opened = [], False
        elif opened:
            buf.append((sgr, ""))
        carry += sgr
        carry.shrink()
    if opened:
        out.append(buf)
    cls = self.__class__
    for i, line in enumerate(out):
        x = object.__new__(cls)
        x._ansi_type, x._items = self._ansi_type, line
        x.shrink()
        out[i] = x
    return out

term_array(shape=None, fillchar='')

term_array(shape: _Shape, fillchar='') -> ShapedNDArray[_Shape, np.void]
term_array(shape: tp.Any | None = None, fillchar='') -> ShapedNDArray[tuple[int, int], np.void]
Source code in chromatic/color/core.py
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
def term_array(self, shape=None, fillchar=""):
    if shape and not (
        isinstance(shape, abc.Sequence)
        and len(shape) == 2
        and all(isinstance(x, int) for x in shape)
    ):
        raise ValueError(f"expected 2d shape: {shape}")
    rows = [*map(np.array, self.splitlines())]
    h, w = (None, None) if shape is None else shape
    if w is not None:
        rows = [r[i : i + w] for r in rows for i in range(0, len(r) or 1, w)]
    if h is not None:
        del rows[h:]
        rows += [np.empty(0, self.dtype)] * (h - len(rows))
    if not rows:
        return np.zeros((0, 0), self.dtype)
    lengths = np.fromiter(map(len, rows), np.intp, len(rows))
    width = int(lengths.max(initial=0)) if w is None else w
    out = np.zeros((len(rows), width), self.dtype)
    mask = np.arange(width) < lengths[:, None]
    out[mask] = np.concatenate(rows)
    if fillchar:
        out["char"][~mask] = fillchar
    return out

__add__(other)

Source code in chromatic/color/core.py
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
def __add__(self, other, /):
    if isinstance(other, str):
        return color_chain(f"{self}{other}")
    elif isinstance(other, color_chain):
        res = object.__new__(color_chain)
        res._ansi_type = self._ansi_type
        copied_self, copied_other = (
            ((sgr.copy(), s) for sgr, s in xs) for xs in (self, other)
        )
        if self._ansi_type is not other._ansi_type:
            copied_other = ((self._handle_sgr(sgr), s) for sgr, s in copied_other)
        res._items = [*copied_self, *copied_other]
        return res
    elif isinstance(other, abc.Iterable):
        return color_chain(
            (x for xs in (self, other) for x in xs), ansi_type=self._ansi_type
        )
    return NotImplemented

__bool__()

Source code in chromatic/color/core.py
2080
2081
def __bool__(self):
    return bool(self._items)

__call__(obj='')

Source code in chromatic/color/core.py
2083
2084
def __call__(self, obj="", /):
    return f"{self}{obj}\x1b[0m"

__delitem__(index)

__delitem__(index: tp.SupportsIndex) -> None
__delitem__(index: slice) -> None
Source code in chromatic/color/core.py
2086
2087
def __delitem__(self, index, /):
    del self._items[index]

__eq__(other)

Source code in chromatic/color/core.py
2089
2090
2091
2092
def __eq__(self, other, /):
    if isinstance(other, color_chain):
        return self._items == other._items
    return NotImplemented

__getitem__(index)

__getitem__(index: tp.SupportsIndex) -> tuple[SgrSequence, str]
__getitem__(index: slice) -> list[tuple[SgrSequence, str]]
Source code in chromatic/color/core.py
2094
2095
def __getitem__(self, index, /):
    return self._items[index]

__init__(iterable=None, /, *, ansi_type=None)

__init__(iterable: None = None, /, *, ansi_type: AnsiColorParam | None = None) -> None
__init__(iterable: str, /, *, ansi_type: AnsiColorParam | None = None) -> None
__init__(iterable: abc.Iterable[tuple[SgrSequence, str] | SgrSequence | str], /, *, ansi_type: AnsiColorParam | None = None) -> None
Source code in chromatic/color/core.py
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
def __init__(self, iterable=None, /, *, ansi_type=None):
    if ansi_type is not None:
        self._ansi_type = ansi_type = get_ansi_type(ansi_type)
    else:
        self._ansi_type = None
    if iterable is None:
        self._items = []
    elif isinstance(iterable, color_chain):
        copied = ((sgr.copy(), s) for sgr, s in iterable)
        self._items = (
            list(copied)
            if self._ansi_type is iterable._ansi_type
            else [(self._handle_sgr(sgr), s) for sgr, s in copied]
        )
    else:
        if isinstance(iterable, str):
            iterable = [iterable]
        self._items = [
            (self._handle_sgr(sgr), s)
            for item in iterable
            for sgr, s in self._coerce(item)
        ]

__len__()

Source code in chromatic/color/core.py
2120
2121
def __len__(self):
    return len(self._items)

__radd__(other)

Source code in chromatic/color/core.py
2123
2124
2125
2126
2127
2128
2129
2130
def __radd__(self, other, /):
    if isinstance(other, str):
        return color_chain(f"{other}{self}")
    elif isinstance(other, abc.Iterable):
        return color_chain(
            (x for xs in (other, self) for x in xs), ansi_type=self._ansi_type
        )
    return NotImplemented

__repr__()

Source code in chromatic/color/core.py
2132
2133
2134
2135
2136
def __repr__(self):
    constructor_args = repr([f"{sgr}{s}" for sgr, s in self])
    if self._ansi_type is not None:
        constructor_args += f", ansi_type={self._ansi_type.alias!r}"
    return "{.__class__.__name__}({})".format(self, constructor_args)

__setitem__(index, value)

__setitem__(index: tp.SupportsIndex, value: tuple[SgrSequence, str]) -> None
__setitem__(index: slice, value: abc.Iterable[tuple[SgrSequence, str]]) -> None
Source code in chromatic/color/core.py
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
def __setitem__(self, index, value, /):
    def _validate(obj, /):
        if (
            isinstance(obj, tuple)
            and len(obj) == 2
            and isinstance(obj[0], SgrSequence)
            and obj[1].__class__ is str
        ):
            sgr, s = obj
            return self._handle_sgr(sgr), s
        raise TypeError

    if isinstance(index, slice):
        self._items[index] = list(map(_validate, value))
    else:
        self._items[index] = _validate(value)

__str__()

Source code in chromatic/color/core.py
2155
2156
def __str__(self):
    return "".join(f"{sgr}{s}" for sgr, s in self)

colorbytes

Bases: bytes

colorbytes(bytes_or_buffer) -> ansicolor4Bit | ansicolor8Bit | ansicolor24Bit

Construct an immutable array of bytes representing a valid ANSI SGR color code span.

When called from the base colorbytes class form, if the input is already an instance of a colorbytes subclass, the constructor returns it as-is. Otherwise, the bytes will be parsed and the constructor returns an instance of the appropriate subclass. The constructor will never return an instance of colorbytes, only a covariant type.

When called from a subclass, if the input is not a colorbytes subclass instance, it will be parsed. If the input colorbytes is the same type as this subclass, the constructor returns it as-is. Otherwise, the input rgb colors are mapped to the nearest color code in this subclass' color-space.

Note

colorbytes is only to be subclassed by the internal implementation. The programmer must override all constructors for it to behave properly as a standalone subclass.

Source code in chromatic/color/core.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
class colorbytes(bytes):
    """
    ``colorbytes(bytes_or_buffer) -> ansicolor4Bit | ansicolor8Bit | ansicolor24Bit``

    Construct an immutable array of bytes representing a valid ANSI SGR color
    code span.

    When called from the base `colorbytes` class form, if the input is already
    an instance of a `colorbytes` subclass, the constructor returns it as-is.
    Otherwise, the bytes will be parsed and the constructor returns an instance
    of the appropriate subclass. The constructor will never return an instance
    of `colorbytes`, only a covariant type.

    When called from a subclass, if the input is not a `colorbytes` subclass
    instance, it will be parsed. If the input `colorbytes` is the same type as
    this subclass, the constructor returns it as-is. Otherwise, the input rgb
    colors are mapped to the nearest color code in this subclass' color-space.

    Note
    ----
    ``colorbytes`` is only to be subclassed by the internal implementation.
    The programmer must override all constructors for it to behave properly as
    a standalone subclass.
    """

    @classmethod
    def from_rgb(cls, rgb, /):
        """Construct a `colorbytes` object from an RGB key-value pair.

        Returns
        -------
        cb
            colorbytes object

        Raises
        ------
        ValueError
            If key-value pair does not match expected structure.

        Examples
        --------
        >>> from chromatic.color.core import ansicolor4Bit, ansicolor8Bit

        >>> rgb_dict = {'fg': (255, 85, 85)}
        >>> old_ansi = ansicolor4Bit.from_rgb(rgb_dict)
        >>> repr(old_ansi)
        "ansicolor4Bit(b'91')"

        >>> new_ansi = ansicolor24Bit.from_rgb(rgb_dict)
        >>> repr(new_ansi)
        "ansicolor24Bit(b'38;2;255;85;85')"

        """

        k: ColorDictKeys
        match rgb:
            case ("fg" | "bg") as k, v:
                pass
            case {"fg": _} | {"bg": _}:
                [(k, v)] = rgb.items()
            case _:
                raise ValueError
        r, g, b = (
            (int(x) & 0xFF for x in v)
            if _issubclass(v.__class__, abc.Iterable)
            else int2rgb(v)
        )
        typ = DEFAULT_ANSI if cls is colorbytes else cls
        inst = super().__new__(typ, rgb2ansi_escape(typ, mode=k, rgb=(r, g, b)))
        inst.rgb_dict = mappingproxy({k: (r, g, b)})
        return inst

    def __new__(cls, ansi, /):
        if (objtype := ansi.__class__) is cls:
            return ansi
        elif not _issubclass(objtype, (bytes, bytearray)):
            if _issubclass(objtype, abc.Buffer):
                ansi = (objtype := bytes)(ansi)
            else:
                raise TypeError(
                    f"expected bytes-like object, got {objtype.__name__!r} object instead"
                )
        k: ColorDictKeys
        match _unwrap_ansi_escape(ansi):
            case [color]:
                try:
                    k, rgb = _ANSI16C_I2KV[int(color)]
                except KeyError:
                    raise ValueError(f"invalid 4bit color code: {color}")
                typ = ansicolor4Bit
            case [(b"38" | b"48") as sgr1, (b"2" | b"5") as sgr2, *rest]:
                k = _ANSI256_B2KEY[sgr1]
                if sgr2 == b"2":
                    [r, g, b] = map(int, rest)
                    rgb = r, g, b
                    typ = ansicolor24Bit
                else:
                    [color] = rest
                    rgb = ansi_8bit_to_rgb(int(color))
                    typ = ansicolor8Bit
            case _:
                raise ValueError
        if typ is not cls:
            if cls is not colorbytes:
                typ = cls
            ansi = rgb2ansi_escape(typ, mode=k, rgb=rgb)
        inst = super().__new__(typ, ansi)
        inst.rgb_dict = mappingproxy({k: rgb})
        return inst

    def __repr__(self):
        return "{0.__class__.__name__}({0!s})".format(self)

    def kind(self):
        [k] = self.rgb_dict
        return k

    def to_param_buffer(self) -> "SgrParamBuffer[tp.Self]":
        obj = object.__new__(SgrParamBuffer)
        obj._value = self
        obj._is_color = True
        return obj

    rgb_dict: mappingproxy[L["fg"], Int3Tuple] | mappingproxy[L["bg"], Int3Tuple]

rgb_dict instance-attribute

from_rgb(rgb) classmethod

from_rgb(rgb: tuple[ColorDictKeys, _VT] | abc.Mapping[_KT, _VT]) -> _T
from_rgb(rgb: tuple[str, _VT] | abc.Mapping[str, _VT]) -> _T

Construct a colorbytes object from an RGB key-value pair.

Returns:

Type Description
cb

colorbytes object

Raises:

Type Description
ValueError

If key-value pair does not match expected structure.

Examples:

>>> from chromatic.color.core import ansicolor4Bit, ansicolor8Bit
>>> rgb_dict = {'fg': (255, 85, 85)}
>>> old_ansi = ansicolor4Bit.from_rgb(rgb_dict)
>>> repr(old_ansi)
"ansicolor4Bit(b'91')"
>>> new_ansi = ansicolor24Bit.from_rgb(rgb_dict)
>>> repr(new_ansi)
"ansicolor24Bit(b'38;2;255;85;85')"
Source code in chromatic/color/core.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
@classmethod
def from_rgb(cls, rgb, /):
    """Construct a `colorbytes` object from an RGB key-value pair.

    Returns
    -------
    cb
        colorbytes object

    Raises
    ------
    ValueError
        If key-value pair does not match expected structure.

    Examples
    --------
    >>> from chromatic.color.core import ansicolor4Bit, ansicolor8Bit

    >>> rgb_dict = {'fg': (255, 85, 85)}
    >>> old_ansi = ansicolor4Bit.from_rgb(rgb_dict)
    >>> repr(old_ansi)
    "ansicolor4Bit(b'91')"

    >>> new_ansi = ansicolor24Bit.from_rgb(rgb_dict)
    >>> repr(new_ansi)
    "ansicolor24Bit(b'38;2;255;85;85')"

    """

    k: ColorDictKeys
    match rgb:
        case ("fg" | "bg") as k, v:
            pass
        case {"fg": _} | {"bg": _}:
            [(k, v)] = rgb.items()
        case _:
            raise ValueError
    r, g, b = (
        (int(x) & 0xFF for x in v)
        if _issubclass(v.__class__, abc.Iterable)
        else int2rgb(v)
    )
    typ = DEFAULT_ANSI if cls is colorbytes else cls
    inst = super().__new__(typ, rgb2ansi_escape(typ, mode=k, rgb=(r, g, b)))
    inst.rgb_dict = mappingproxy({k: (r, g, b)})
    return inst

__new__(ansi)

__new__(ansi: bytes | AnsiColorFormat) -> _T
__new__(ansi: bytes) -> AnsiColorFormat
Source code in chromatic/color/core.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def __new__(cls, ansi, /):
    if (objtype := ansi.__class__) is cls:
        return ansi
    elif not _issubclass(objtype, (bytes, bytearray)):
        if _issubclass(objtype, abc.Buffer):
            ansi = (objtype := bytes)(ansi)
        else:
            raise TypeError(
                f"expected bytes-like object, got {objtype.__name__!r} object instead"
            )
    k: ColorDictKeys
    match _unwrap_ansi_escape(ansi):
        case [color]:
            try:
                k, rgb = _ANSI16C_I2KV[int(color)]
            except KeyError:
                raise ValueError(f"invalid 4bit color code: {color}")
            typ = ansicolor4Bit
        case [(b"38" | b"48") as sgr1, (b"2" | b"5") as sgr2, *rest]:
            k = _ANSI256_B2KEY[sgr1]
            if sgr2 == b"2":
                [r, g, b] = map(int, rest)
                rgb = r, g, b
                typ = ansicolor24Bit
            else:
                [color] = rest
                rgb = ansi_8bit_to_rgb(int(color))
                typ = ansicolor8Bit
        case _:
            raise ValueError
    if typ is not cls:
        if cls is not colorbytes:
            typ = cls
        ansi = rgb2ansi_escape(typ, mode=k, rgb=rgb)
    inst = super().__new__(typ, ansi)
    inst.rgb_dict = mappingproxy({k: rgb})
    return inst

__repr__()

Source code in chromatic/color/core.py
303
304
def __repr__(self):
    return "{0.__class__.__name__}({0!s})".format(self)

kind()

Source code in chromatic/color/core.py
306
307
308
def kind(self):
    [k] = self.rgb_dict
    return k

to_param_buffer()

Source code in chromatic/color/core.py
310
311
312
313
314
def to_param_buffer(self) -> "SgrParamBuffer[tp.Self]":
    obj = object.__new__(SgrParamBuffer)
    obj._value = self
    obj._is_color = True
    return obj

ColorNamespace

Bases: DynamicNamespace

Source code in chromatic/color/palette.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
class ColorNamespace(DynamicNamespace, wrapper=Color):
    BLACK = 0x000000
    DIM_GREY = 0x696969
    GREY = 0x808080
    DARK_GREY = 0xA9A9A9
    SILVER = 0xC0C0C0
    LIGHT_GREY = 0xD3D3D3
    WHITE_SMOKE = 0xF5F5F5
    WHITE = 0xFFFFFF
    MAROON = 0x800000
    DARK_RED = 0x8B0000
    RED = 0xFF0000
    FIREBRICK = 0xB22222
    BROWN = 0xA52A2A
    INDIAN_RED = 0xCD5C5C
    LIGHT_CORAL = 0xF08080
    ROSY_BROWN = 0xBC8F8F
    MISTY_ROSE = 0xFFE4E1
    SNOW = 0xFFFAFA
    SIENNA = 0xA0522D
    ORANGE_RED = 0xFF4500
    TOMATO = 0xFF6347
    BURNT_SIENNA = 0xEA7E5D
    CORAL = 0xFF7F50
    SALMON = 0xFA8072
    DARK_SALMON = 0xE9967A
    LIGHT_SALMON = 0xFFA07A
    SEASHELL = 0xFFF5EE
    SADDLE_BROWN = 0x8B4513
    CHOCOLATE = 0xD2691E
    PERU = 0xCD853F
    SANDY_BROWN = 0xF4A460
    PEACH_PUFF = 0xFFDAB9
    LINEN = 0xFAF0E6
    DARK_ORANGE = 0xFF8C00
    BURLY_WOOD = 0xDEB887
    BISQUE = 0xFFE4C4
    ANTIQUE_WHITE = 0xFAEBD7
    ORANGE = 0xFFA500
    TAN = 0xD2B48C
    WHEAT = 0xF5DEB3
    NAVAJO_WHITE = 0xFFDEAD
    MOCCASIN = 0xFFE4B5
    BLANCHED_ALMOND = 0xFFEBCD
    PAPAYA_WHIP = 0xFFEFD5
    OLD_LACE = 0xFDF5E6
    FLORAL_WHITE = 0xFFFAF0
    DARK_GOLDENROD = 0xB8860B
    GOLDENROD = 0xDAA520
    CORNSILK = 0xFFF8DC
    DARK_KHAKI = 0xBDB76B
    GOLD = 0xFFD700
    KHAKI = 0xF0E68C
    PALE_GOLDENROD = 0xEEE8AA
    BEIGE = 0xF5F5DC
    LIGHT_GOLDENROD_YELLOW = 0xFAFAD2
    LEMON_CHIFFON = 0xFFFACD
    OLIVE = 0x808000
    YELLOW = 0xFFFF00
    LIGHT_YELLOW = 0xFFFFE0
    IVORY = 0xFFFFF0
    DARK_GREEN = 0x006400
    GREEN = 0x008000
    DARK_OLIVE_GREEN = 0x556B2F
    FOREST_GREEN = 0x228B22
    OLIVE_DRAB = 0x6B8E23
    LIME_GREEN = 0x32CD32
    DARK_SEA_GREEN = 0x8FBC8F
    LIME = 0x00FF00
    YELLOW_GREEN = 0x9ACD32
    LAWN_GREEN = 0x7CFC00
    CHARTREUSE = 0x7FFF00
    LIGHT_GREEN = 0x90EE90
    GREEN_YELLOW = 0xADFF2F
    PALE_GREEN = 0x98FB98
    HONEYDEW = 0xF0FFF0
    SEA_GREEN = 0x2E8B57
    MEDIUM_SEA_GREEN = 0x3CB371
    SPRING_GREEN = 0x00FF7F
    MINT_CREAM = 0xF5FFFA
    DARK_SLATE_GREY = 0x2F4F4F
    TEAL = 0x008080
    DARK_CYAN = 0x008B8B
    LIGHT_SEA_GREEN = 0x20B2AA
    MEDIUM_TURQUOISE = 0x48D1CC
    MEDIUM_AQUAMARINE = 0x66CDAA
    TURQUOISE = 0x40E0D0
    MEDIUM_SPRING_GREEN = 0x00FA9A
    CYAN = 0x00FFFF
    PALE_TURQUOISE = 0xAFEEEE
    AQUAMARINE = 0x7FFFD4
    LIGHT_CYAN = 0xE0FFFF
    AZURE = 0xF0FFFF
    STEEL_BLUE = 0x4682B4
    CADET_BLUE = 0x5F9EA0
    DEEP_SKY_BLUE = 0x00BFFF
    DARK_TURQUOISE = 0x00CED1
    SKY_BLUE = 0x87CEEB
    LIGHT_SKY_BLUE = 0x87CEFA
    LIGHT_BLUE = 0xADD8E6
    POWDER_BLUE = 0xB0E0E6
    ALICE_BLUE = 0xF0F8FF
    MIDNIGHT_BLUE = 0x191970
    ROYAL_BLUE = 0x4169E1
    SLATE_GREY = 0x708090
    DODGER_BLUE = 0x1E90FF
    LIGHT_SLATE_GREY = 0x778899
    CORNFLOWER_BLUE = 0x6495ED
    LIGHT_STEEL_BLUE = 0xB0C4DE
    LAVENDER = 0xE6E6FA
    NAVY = 0x000080
    DARK_BLUE = 0x00008B
    MEDIUM_BLUE = 0x0000CD
    BLUE = 0x0000FF
    GHOST_WHITE = 0xF8F8FF
    INDIGO = 0x4B0082
    DARK_VIOLET = 0x9400D3
    DARK_SLATE_BLUE = 0x483D8B
    REBECCA_PURPLE = 0x663399
    BLUE_VIOLET = 0x8A2BE2
    DARK_ORCHID = 0x9932CC
    SLATE_BLUE = 0x6A5ACD
    MEDIUM_ORCHID = 0xBA55D3
    MEDIUM_SLATE_BLUE = 0x7B68EE
    MEDIUM_PURPLE = 0x9370DB
    THISTLE = 0xD8BFD8
    PURPLE = 0x800080
    DARK_MAGENTA = 0x8B008B
    MEDIUM_VIOLET_RED = 0xC71585
    FUCHSIA = 0xFF00FF
    DEEP_PINK = 0xFF1493
    ORCHID = 0xDA70D6
    HOT_PINK = 0xFF69B4
    VIOLET = 0xEE82EE
    PLUM = 0xDDA0DD
    LAVENDER_BLUSH = 0xFFF0F5
    CRIMSON = 0xDC143C
    PALE_VIOLET_RED = 0xDB7093
    LIGHT_PINK = 0xFFB6C1
    PINK = 0xFFC0CB

BLACK = 0 class-attribute instance-attribute

DIM_GREY = 6908265 class-attribute instance-attribute

GREY = 8421504 class-attribute instance-attribute

DARK_GREY = 11119017 class-attribute instance-attribute

SILVER = 12632256 class-attribute instance-attribute

LIGHT_GREY = 13882323 class-attribute instance-attribute

WHITE_SMOKE = 16119285 class-attribute instance-attribute

WHITE = 16777215 class-attribute instance-attribute

MAROON = 8388608 class-attribute instance-attribute

DARK_RED = 9109504 class-attribute instance-attribute

RED = 16711680 class-attribute instance-attribute

FIREBRICK = 11674146 class-attribute instance-attribute

BROWN = 10824234 class-attribute instance-attribute

INDIAN_RED = 13458524 class-attribute instance-attribute

LIGHT_CORAL = 15761536 class-attribute instance-attribute

ROSY_BROWN = 12357519 class-attribute instance-attribute

MISTY_ROSE = 16770273 class-attribute instance-attribute

SNOW = 16775930 class-attribute instance-attribute

SIENNA = 10506797 class-attribute instance-attribute

ORANGE_RED = 16729344 class-attribute instance-attribute

TOMATO = 16737095 class-attribute instance-attribute

BURNT_SIENNA = 15367773 class-attribute instance-attribute

CORAL = 16744272 class-attribute instance-attribute

SALMON = 16416882 class-attribute instance-attribute

DARK_SALMON = 15308410 class-attribute instance-attribute

LIGHT_SALMON = 16752762 class-attribute instance-attribute

SEASHELL = 16774638 class-attribute instance-attribute

SADDLE_BROWN = 9127187 class-attribute instance-attribute

CHOCOLATE = 13789470 class-attribute instance-attribute

PERU = 13468991 class-attribute instance-attribute

SANDY_BROWN = 16032864 class-attribute instance-attribute

PEACH_PUFF = 16767673 class-attribute instance-attribute

LINEN = 16445670 class-attribute instance-attribute

DARK_ORANGE = 16747520 class-attribute instance-attribute

BURLY_WOOD = 14596231 class-attribute instance-attribute

BISQUE = 16770244 class-attribute instance-attribute

ANTIQUE_WHITE = 16444375 class-attribute instance-attribute

ORANGE = 16753920 class-attribute instance-attribute

TAN = 13808780 class-attribute instance-attribute

WHEAT = 16113331 class-attribute instance-attribute

NAVAJO_WHITE = 16768685 class-attribute instance-attribute

MOCCASIN = 16770229 class-attribute instance-attribute

BLANCHED_ALMOND = 16772045 class-attribute instance-attribute

PAPAYA_WHIP = 16773077 class-attribute instance-attribute

OLD_LACE = 16643558 class-attribute instance-attribute

FLORAL_WHITE = 16775920 class-attribute instance-attribute

DARK_GOLDENROD = 12092939 class-attribute instance-attribute

GOLDENROD = 14329120 class-attribute instance-attribute

CORNSILK = 16775388 class-attribute instance-attribute

DARK_KHAKI = 12433259 class-attribute instance-attribute

GOLD = 16766720 class-attribute instance-attribute

KHAKI = 15787660 class-attribute instance-attribute

PALE_GOLDENROD = 15657130 class-attribute instance-attribute

BEIGE = 16119260 class-attribute instance-attribute

LIGHT_GOLDENROD_YELLOW = 16448210 class-attribute instance-attribute

LEMON_CHIFFON = 16775885 class-attribute instance-attribute

OLIVE = 8421376 class-attribute instance-attribute

YELLOW = 16776960 class-attribute instance-attribute

LIGHT_YELLOW = 16777184 class-attribute instance-attribute

IVORY = 16777200 class-attribute instance-attribute

DARK_GREEN = 25600 class-attribute instance-attribute

GREEN = 32768 class-attribute instance-attribute

DARK_OLIVE_GREEN = 5597999 class-attribute instance-attribute

FOREST_GREEN = 2263842 class-attribute instance-attribute

OLIVE_DRAB = 7048739 class-attribute instance-attribute

LIME_GREEN = 3329330 class-attribute instance-attribute

DARK_SEA_GREEN = 9419919 class-attribute instance-attribute

LIME = 65280 class-attribute instance-attribute

YELLOW_GREEN = 10145074 class-attribute instance-attribute

LAWN_GREEN = 8190976 class-attribute instance-attribute

CHARTREUSE = 8388352 class-attribute instance-attribute

LIGHT_GREEN = 9498256 class-attribute instance-attribute

GREEN_YELLOW = 11403055 class-attribute instance-attribute

PALE_GREEN = 10025880 class-attribute instance-attribute

HONEYDEW = 15794160 class-attribute instance-attribute

SEA_GREEN = 3050327 class-attribute instance-attribute

MEDIUM_SEA_GREEN = 3978097 class-attribute instance-attribute

SPRING_GREEN = 65407 class-attribute instance-attribute

MINT_CREAM = 16121850 class-attribute instance-attribute

DARK_SLATE_GREY = 3100495 class-attribute instance-attribute

TEAL = 32896 class-attribute instance-attribute

DARK_CYAN = 35723 class-attribute instance-attribute

LIGHT_SEA_GREEN = 2142890 class-attribute instance-attribute

MEDIUM_TURQUOISE = 4772300 class-attribute instance-attribute

MEDIUM_AQUAMARINE = 6737322 class-attribute instance-attribute

TURQUOISE = 4251856 class-attribute instance-attribute

MEDIUM_SPRING_GREEN = 64154 class-attribute instance-attribute

CYAN = 65535 class-attribute instance-attribute

PALE_TURQUOISE = 11529966 class-attribute instance-attribute

AQUAMARINE = 8388564 class-attribute instance-attribute

LIGHT_CYAN = 14745599 class-attribute instance-attribute

AZURE = 15794175 class-attribute instance-attribute

STEEL_BLUE = 4620980 class-attribute instance-attribute

CADET_BLUE = 6266528 class-attribute instance-attribute

DEEP_SKY_BLUE = 49151 class-attribute instance-attribute

DARK_TURQUOISE = 52945 class-attribute instance-attribute

SKY_BLUE = 8900331 class-attribute instance-attribute

LIGHT_SKY_BLUE = 8900346 class-attribute instance-attribute

LIGHT_BLUE = 11393254 class-attribute instance-attribute

POWDER_BLUE = 11591910 class-attribute instance-attribute

ALICE_BLUE = 15792383 class-attribute instance-attribute

MIDNIGHT_BLUE = 1644912 class-attribute instance-attribute

ROYAL_BLUE = 4286945 class-attribute instance-attribute

SLATE_GREY = 7372944 class-attribute instance-attribute

DODGER_BLUE = 2003199 class-attribute instance-attribute

LIGHT_SLATE_GREY = 7833753 class-attribute instance-attribute

CORNFLOWER_BLUE = 6591981 class-attribute instance-attribute

LIGHT_STEEL_BLUE = 11584734 class-attribute instance-attribute

LAVENDER = 15132410 class-attribute instance-attribute

NAVY = 128 class-attribute instance-attribute

DARK_BLUE = 139 class-attribute instance-attribute

MEDIUM_BLUE = 205 class-attribute instance-attribute

BLUE = 255 class-attribute instance-attribute

GHOST_WHITE = 16316671 class-attribute instance-attribute

INDIGO = 4915330 class-attribute instance-attribute

DARK_VIOLET = 9699539 class-attribute instance-attribute

DARK_SLATE_BLUE = 4734347 class-attribute instance-attribute

REBECCA_PURPLE = 6697881 class-attribute instance-attribute

BLUE_VIOLET = 9055202 class-attribute instance-attribute

DARK_ORCHID = 10040012 class-attribute instance-attribute

SLATE_BLUE = 6970061 class-attribute instance-attribute

MEDIUM_ORCHID = 12211667 class-attribute instance-attribute

MEDIUM_SLATE_BLUE = 8087790 class-attribute instance-attribute

MEDIUM_PURPLE = 9662683 class-attribute instance-attribute

THISTLE = 14204888 class-attribute instance-attribute

PURPLE = 8388736 class-attribute instance-attribute

DARK_MAGENTA = 9109643 class-attribute instance-attribute

MEDIUM_VIOLET_RED = 13047173 class-attribute instance-attribute

FUCHSIA = 16711935 class-attribute instance-attribute

DEEP_PINK = 16716947 class-attribute instance-attribute

ORCHID = 14315734 class-attribute instance-attribute

HOT_PINK = 16738740 class-attribute instance-attribute

VIOLET = 15631086 class-attribute instance-attribute

PLUM = 14524637 class-attribute instance-attribute

LAVENDER_BLUSH = 16773365 class-attribute instance-attribute

CRIMSON = 14423100 class-attribute instance-attribute

PALE_VIOLET_RED = 14381203 class-attribute instance-attribute

LIGHT_PINK = 16758465 class-attribute instance-attribute

PINK = 16761035 class-attribute instance-attribute

ansi_4bit_to_rgb(value)

Source code in chromatic/color/colorconv.py
314
315
316
317
318
319
320
321
322
323
324
325
def ansi_4bit_to_rgb(value: int, /):
    offset = 0
    if value > 37:
        if value <= 47:
            offset -= 10
        elif value <= 97:
            offset += 8
        else:
            offset -= 2
    value %= 30
    value += offset
    return ANSI_4BIT_RGB[value]

ansi_8bit_to_rgb(value)

ansi_8bit_to_rgb(value: int) -> Int3Tuple
ansi_8bit_to_rgb(value: ShapedNDArray[_Shape, np.number]) -> ShapedNDArray[tuple[*_Shape, L[3]], np.uint8]
Source code in chromatic/color/colorconv.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def ansi_8bit_to_rgb(value, /):
    arr = np.asarray(value, dtype=np.uint8)
    if arr.ndim == 0:
        return _ansi_8bit_to_rgb_fast(arr.item())
    out = np.empty(arr.shape + (3,), dtype=np.uint8)
    mask = np.ones(arr.shape, dtype=np.bool_)
    ansi_16c = arr < 16
    out[ansi_16c] = np.take(ANSI_4BIT_RGB, arr[ansi_16c], axis=0)
    mask &= ~ansi_16c
    colorcube = (arr >= 16) & (arr < 232)
    c = arr[colorcube] - 16
    out[colorcube, 0] = c // 36
    out[colorcube, 1] = c % 36 // 6
    out[colorcube, 2] = c % 6
    out[colorcube, :] *= 51
    mask &= ~colorcube
    out[mask] = (8 + (arr[mask] - 232) * 10)[:, None]
    return out

hexstr2rgb(s)

Source code in chromatic/color/colorconv.py
67
68
69
70
71
72
73
74
75
76
77
78
def hexstr2rgb(s: str, /) -> Int3Tuple:
    n = len(s)
    if n % 4 == 0:  # trunc alpha
        n *= 3
        n //= 4
        s = s[:n]
    if n == 3:  # rgb -> rrggbb
        s = "".join(c * 2 for c in s)
    x = int(s, 16)
    if not 0 <= x < (1 << 24):
        raise ValueError(f"{x:#x} is not u24")
    return int2rgb(x)

hsl2rgb(hsl)

hsl2rgb(hsl: Float3Tuple) -> ShapedNDArray[tuple[L[3]], np.uint8]
hsl2rgb(hsl: ShapedNDArray[_Shape, np.floating]) -> ShapedNDArray[_Shape, np.uint8]
Source code in chromatic/color/colorconv.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def hsl2rgb(hsl, /):
    arr = np.asarray(hsl, dtype=np.float32)
    shape = arr.shape
    h, s, L = np.unstack(np.atleast_2d(arr), axis=-1)
    C = (1.0 - np.abs(2.0 * L - 1.0)) * s
    h6 = h * 6.0
    i = np.floor(h6).astype(int)
    X = C * (1.0 - np.abs(h6 % 2.0 - 1.0))
    m = L - C / 2.0
    xs = np.stack([C + m, X + m, m], axis=-1)
    P = np.array(
        [[0, 1, 2],
         [1, 0, 2],
         [2, 0, 1],
         [2, 1, 0],
         [1, 2, 0],
         [0, 2, 1]]
    )   # fmt: skip
    out = np.take_along_axis(xs, P[i % 6], axis=-1)
    return np.rint(out * 255).astype(np.uint8).reshape(shape)

hsv2rgb(hsv)

hsv2rgb(hsv: Float3Tuple) -> ShapedNDArray[tuple[L[3]], np.uint8]
hsv2rgb(hsv: ShapedNDArray[_Shape, np.floating]) -> ShapedNDArray[_Shape, np.uint8]
Source code in chromatic/color/colorconv.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def hsv2rgb(hsv, /):
    arr = np.asarray(hsv, dtype=np.float32)
    shape = arr.shape
    h, s, v = np.unstack(np.atleast_2d(arr), axis=-1)
    h6 = h * 6.0
    i = np.floor(h6).astype(int)
    f = h6 - i
    xs = np.stack([v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)], axis=-1)
    P = np.array(
        [[0, 3, 1],
         [2, 0, 1],
         [1, 0, 3],
         [1, 2, 0],
         [3, 1, 0],
         [0, 1, 2]]
    )   # fmt: skip
    out = np.take_along_axis(xs, P[i % 6], axis=-1)
    return np.rint(out * 255).astype(np.uint8).reshape(shape)

int2rgb(x)

Source code in chromatic/color/colorconv.py
90
91
92
def int2rgb(x: int, /) -> Int3Tuple:
    x = int(x) & 0xFFFFFF
    return (x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF

is_u24(value, *, strict=False)

Check if value is an unsigned 24-bit integer.

Parameters:

Name Type Description Default
value

Input number

required
strict bool

Whether to return False or raise ValueError on failure

False

Raises:

Type Description
ValueError

Raised when strict=True and value is not u24

Source code in chromatic/color/colorconv.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def is_u24(value, *, strict: bool = False) -> bool:
    """Check if value is an unsigned 24-bit integer.

    Parameters
    ---------
    value
        Input number
    strict : bool
        Whether to return False or raise ValueError on failure

    Raises
    ------
    ValueError
        Raised when `strict=True` and value is not u24
    """
    if _supports_int(value.__class__):
        if 0 <= int(value) < (1 << 24):
            return True
        elif not strict:
            return False
    raise ValueError(f"{value!r} is not u24")

lab2lch(lab)

lab2lch(lab: Float3Tuple) -> ShapedNDArray[tuple[L[3]], np.float64]
lab2lch(lab: ShapedNDArray[_Shape, np.floating]) -> ShapedNDArray[_Shape, np.float64]
Source code in chromatic/color/colorconv.py
247
248
249
250
251
252
def lab2lch(lab, /):
    arr = np.asarray(lab, dtype=np.float64)
    L, a, b = np.unstack(arr, axis=-1)
    C = np.hypot(a, b)
    h = np.degrees(np.arctan2(b, a)) % 360
    return np.stack([L, C, h], axis=-1)

lab2rgb(lab)

lab2rgb(lab: Float3Tuple) -> ShapedNDArray[tuple[L[3]], np.uint8]
lab2rgb(lab: ShapedNDArray[_Shape, np.floating]) -> ShapedNDArray[_Shape, np.uint8]
Source code in chromatic/color/colorconv.py
239
240
def lab2rgb(lab, /):
    return xyz2rgb(lab2xyz(lab))

lab2xyz(lab)

lab2xyz(lab: Float3Tuple) -> ShapedNDArray[tuple[L[3]], np.float64]
lab2xyz(lab: ShapedNDArray[_Shape, np.floating]) -> ShapedNDArray[_Shape, np.float64]
Source code in chromatic/color/colorconv.py
138
139
140
141
142
143
144
145
146
147
148
def lab2xyz(lab, /):
    arr = np.asarray(lab, dtype=np.float64)
    shape = arr.shape
    L, a, b = np.unstack(np.atleast_2d(arr), axis=-1)
    fy = (L + 16.0) / 116.0
    fx = a / 500.0 + fy
    fz = fy - b / 200.0
    f = np.stack([fx, fy, fz], axis=-1)
    f3 = f**3
    n = np.where(f3 > EPS, f3, (f - (16 / 116)) / LIN)
    return (n * REFWT).reshape(shape)

lch2lab(lch)

lch2lab(lch: Float3Tuple) -> ShapedNDArray[tuple[L[3]], np.float64]
lch2lab(lch: ShapedNDArray[_Shape, np.floating]) -> ShapedNDArray[_Shape, np.float64]
Source code in chromatic/color/colorconv.py
255
256
257
258
259
def lch2lab(lch, /):
    arr = np.asarray(lch, dtype=np.float64)
    L, C, h = np.unstack(arr, axis=-1)
    h = np.radians(h)
    return np.stack([L, C * np.cos(h), C * np.sin(h)], axis=-1)

lch2rgb(lch)

lch2rgb(lch: Float3Tuple) -> ShapedNDArray[tuple[L[3]], np.uint8]
lch2rgb(lch: ShapedNDArray[_Shape, np.floating]) -> ShapedNDArray[_Shape, np.uint8]
Source code in chromatic/color/colorconv.py
262
263
def lch2rgb(lch, /):
    return lab2rgb(lch2lab(lch))

lerp_lch(lch1, lch2, /, num=8)

lerp_lch(lch1: Float3Tuple | ShapedNDArray[tuple[L[3]], np.floating], lch2: Float3Tuple | ShapedNDArray[tuple[L[3]], np.floating], /, num: _N = 8) -> ShapedNDArray[tuple[_N, L[3]], np.float64]
lerp_lch(lch1: ShapedNDArray[tuple[_D1, L[3]], np.floating], lch2: ShapedNDArray[tuple[_D1, L[3]], np.floating], /, num: _N = 8) -> ShapedNDArray[tuple[_D1, _N, L[3]], np.float64]
lerp_lch(lch1: ShapedNDArray[tuple[_D1, _D2, L[3]], np.floating], lch2: ShapedNDArray[tuple[_D1, _D2, L[3]], np.floating], /, num: _N = 8) -> ShapedNDArray[tuple[_D1, _D2, _N, L[3]], np.float64]
lerp_lch(lch1: np.typing.NDArray[np.floating], lch2: np.typing.NDArray[np.floating], /, num=8) -> np.typing.NDArray[np.float64]

Return a linear interpolation of the given LCh arrays.

Where lch1 and lch2 have dims ([D0[,...D-1],] 3) and num is N, the returned array will have dims ([D0[,...D-1],] N, 3).

Source code in chromatic/color/colorconv.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def lerp_lch(lch1, lch2, /, num=8):
    """Return a linear interpolation of the given LCh arrays.

    Where `lch1` and `lch2` have dims `([D0[,...D-1],] 3)` and `num` is `N`,
    the returned array will have dims `([D0[,...D-1],] N, 3)`.
    """
    lch1 = np.asarray(lch1, dtype=np.float64)
    lch2 = np.asarray(lch2, dtype=np.float64)
    L1, C1, h1 = np.unstack(lch1, axis=-1)
    L2, C2, h2 = np.unstack(lch2, axis=-1)
    h1 = np.where(C1 < 1e-6, h2, h1)
    h2 = np.where(C2 < 1e-6, h1, h2)
    dh = (h2 - h1 + 180) % 360 - 180
    t = np.linspace(0, 1, num).reshape(num, *[1] * (lch1.ndim - 1))
    L = L1 + t * (L2 - L1)
    C = C1 + t * (C2 - C1)
    h = (h1 + t * dh) % 360
    return np.moveaxis(np.stack([L, C, h], axis=0), [0, 1], [-1, -2])

nearest_ansi_4bit_rgb(rgb)

nearest_ansi_4bit_rgb(rgb: Int3Tuple) -> Int3Tuple
nearest_ansi_4bit_rgb(rgb: tp.Sequence[ConvertibleToInt]) -> Int3Tuple
nearest_ansi_4bit_rgb(rgb: ShapedNDArray[_Shape, np.number]) -> ShapedNDArray[_Shape, np.uint8]
Source code in chromatic/color/colorconv.py
348
349
350
351
352
def nearest_ansi_4bit_rgb(rgb, /):
    arr = np.asarray(rgb, dtype=np.uint8) >> 3
    r, g, b = np.unstack(arr, axis=-1)
    out = ANSI_4BIT_RGB_LUT[r, g, b]
    return tuple(out.tolist()) if arr.shape == (3,) else out

nearest_ansi_8bit_rgb(value)

nearest_ansi_8bit_rgb(rgb: Int3Tuple) -> Int3Tuple
nearest_ansi_8bit_rgb(rgb: tp.Sequence[ConvertibleToInt]) -> Int3Tuple
nearest_ansi_8bit_rgb(rgb: ShapedNDArray[_Shape, np.number]) -> ShapedNDArray[_Shape, np.uint8]
Source code in chromatic/color/colorconv.py
355
356
def nearest_ansi_8bit_rgb(value, /):
    return ansi_8bit_to_rgb(rgb_to_ansi_8bit(value))

rgb2hexstr(rgb)

Source code in chromatic/color/colorconv.py
81
82
def rgb2hexstr(rgb: RGBVectorLike, /) -> str:
    return "%02x%02x%02x" % tuple(rgb)

rgb2hsl(rgb)

rgb2hsl(rgb: Int3Tuple) -> ShapedNDArray[tuple[L[3]], np.float32]
rgb2hsl(rgb: ShapedNDArray[_Shape, np.number]) -> ShapedNDArray[_Shape, np.float32]
Source code in chromatic/color/colorconv.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def rgb2hsl(rgb, /):
    arr = np.asarray(rgb, dtype=np.float32) / 255.0
    shape = arr.shape
    r, g, b = np.unstack(arr := np.atleast_2d(arr), axis=-1)
    m = np.min(arr, axis=-1)
    v = np.max(arr, axis=-1)
    C = v - m
    L = (v + m) / 2.0
    s = np.zeros_like(v)
    denom = 1.0 - np.abs(2.0 * L - 1.0)
    ok = denom != 0
    s[ok] = C[ok] / denom[ok]
    nz = C != 0
    rmax = (v == r) & nz
    gmax = (v == g) & nz
    bmax = (v == b) & nz
    h = np.zeros_like(v)
    h[rmax] = ((g[rmax] - b[rmax]) / C[rmax]) % 6
    h[gmax] = ((b[gmax] - r[gmax]) / C[gmax]) + 2
    h[bmax] = ((r[bmax] - g[bmax]) / C[bmax]) + 4
    h = (h / 6.0) % 1.0
    return np.stack([h, s, L], axis=-1).reshape(shape)

rgb2hsv(rgb)

rgb2hsv(rgb: Int3Tuple) -> ShapedNDArray[tuple[L[3]], np.float32]
rgb2hsv(rgb: ShapedNDArray[_Shape, np.number]) -> ShapedNDArray[_Shape, np.float32]
Source code in chromatic/color/colorconv.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def rgb2hsv(rgb, /):
    arr = np.asarray(rgb, dtype=np.float32) / 255.0
    shape = arr.shape
    r, g, b = np.unstack(arr := np.atleast_2d(arr), axis=-1)
    m = np.min(arr, axis=-1)
    v = np.max(arr, axis=-1)
    C = v - m
    ok = v != 0
    s = np.zeros_like(v)
    s[ok] = C[ok] / v[ok]
    nz = C != 0
    rmax = (v == r) & nz
    gmax = (v == g) & nz
    bmax = (v == b) & nz
    h = np.zeros_like(v)
    h[rmax] = ((g[rmax] - b[rmax]) / C[rmax]) % 6
    h[gmax] = ((b[gmax] - r[gmax]) / C[gmax]) + 2
    h[bmax] = ((r[bmax] - g[bmax]) / C[bmax]) + 4
    h = (h / 6.0) % 1.0
    return np.stack([h, s, v], axis=-1).reshape(shape)

rgb2int(rgb)

Source code in chromatic/color/colorconv.py
85
86
87
def rgb2int(rgb: RGBVectorLike, /) -> int:
    r, g, b = map(int, rgb)
    return r << 16 | g << 8 | b

rgb2lab(rgb)

rgb2lab(rgb: Int3Tuple) -> ShapedNDArray[tuple[L[3]], np.float64]
rgb2lab(rgb: ShapedNDArray[_Shape, np.uint8]) -> ShapedNDArray[_Shape, np.float64]
Source code in chromatic/color/colorconv.py
243
244
def rgb2lab(rgb, /):
    return xyz2lab(rgb2xyz(rgb))

rgb2lch(rgb)

rgb2lch(rgb: Int3Tuple) -> ShapedNDArray[tuple[L[3]], np.float64]
rgb2lch(rgb: ShapedNDArray[_Shape, np.uint8]) -> ShapedNDArray[_Shape, np.float64]
Source code in chromatic/color/colorconv.py
266
267
def rgb2lch(rgb, /):
    return lab2lch(rgb2lab(rgb))

rgb2xyz(rgb)

Source code in chromatic/color/colorconv.py
122
123
def rgb2xyz(rgb, /):
    return (np.asarray(rgb, dtype=np.float64) / 255.0) @ M_RGB2XYZ.T

rgb_diff(rgb1, rgb2)

rgb_diff(rgb1: Int3Tuple, rgb2: Int3Tuple) -> ShapedNDArray[tuple[L[3]], np.uint8]
rgb_diff(rgb1: ShapedNDArray[_Shape, np.number], rgb2: ShapedNDArray[_Shape, np.number]) -> ShapedNDArray[_Shape, np.uint8]
Source code in chromatic/color/colorconv.py
290
291
def rgb_diff(rgb1, rgb2, /):
    return lab2rgb((rgb2lab(rgb1) + rgb2lab(rgb2)) / 2)

rgb_to_ansi_8bit(rgb)

rgb_to_ansi_8bit(rgb: Int3Tuple) -> int
rgb_to_ansi_8bit(rgb: tp.Sequence[ConvertibleToInt]) -> int
rgb_to_ansi_8bit(rgb: ShapedNDArray[tuple[_D1, L[3]], np.number]) -> ShapedNDArray[tuple[_D1], np.uint8]
rgb_to_ansi_8bit(rgb: ShapedNDArray[tuple[_D1, _D2, L[3]], np.number]) -> ShapedNDArray[tuple[_D1, _D2], np.uint8]
rgb_to_ansi_8bit(rgb: np.typing.NDArray[np.number]) -> np.typing.NDArray[np.uint8]
Source code in chromatic/color/colorconv.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def rgb_to_ansi_8bit(rgb, /) -> int | ShapedNDArray[tuple[int, ...], np.uint8]:
    arr = np.asarray(rgb, dtype=np.uint8)
    if arr.shape == (3,):
        return _rgb_to_ansi_8bit_fast(*arr.tolist())
    out = np.zeros(arr.shape[:-1], dtype=np.uint8)
    mask = np.ones(arr.shape[:-1], dtype=np.bool_)
    grey = (arr[..., 1:] == arr[..., 0:1]).all(axis=-1)
    c = arr[..., 0]
    r_lo = grey & (c < 8)
    r_hi = grey & (c > 248)
    mid = grey & ~(r_lo | r_hi)
    out[r_lo] = 16
    out[r_hi] = 231
    out[mid] = np.rint((c[mid] - 8) / 247 * 24) + 232
    mask &= ~grey
    rest = np.rint(arr[mask] / 255 * 5)
    r, g, b = np.unstack(rest, axis=-1)
    out[mask] = 16 + (36 * r) + (6 * g) + b
    return out

xyz2lab(xyz)

xyz2lab(xyz: Float3Tuple) -> ShapedNDArray[tuple[L[3]], np.float64]
xyz2lab(xyz: ShapedNDArray[_Shape, np.floating]) -> ShapedNDArray[_Shape, np.float64]
Source code in chromatic/color/colorconv.py
126
127
128
129
130
131
132
133
134
135
def xyz2lab(xyz, /):
    arr = np.asarray(xyz, dtype=np.float64)
    shape = arr.shape
    n = np.atleast_2d(arr) / REFWT
    f = np.where(n > EPS, np.cbrt(n), LIN * n + (16 / 116))
    fx, fy, fz = np.unstack(f, axis=-1)
    L = 116.0 * fy - 16.0
    a = 500.0 * (fx - fy)
    b = 200.0 * (fy - fz)
    return np.stack([L, a, b], axis=-1).reshape(shape)

xyz2rgb(xyz)

Source code in chromatic/color/colorconv.py
117
118
119
def xyz2rgb(xyz, /):
    out = np.clip(np.asarray(xyz, dtype=np.float64) @ M_XYZ2RGB.T, 0.0, 1.0)
    return np.rint(out * 255).astype(np.uint8)

get_ansi_type(typ=None)

get_ansi_type(typ: None = None) -> type[ansicolor8Bit | ansicolor4Bit]
get_ansi_type(typ: _T) -> _T
get_ansi_type(typ: Ansi4BitAlias) -> type[ansicolor4Bit]
get_ansi_type(typ: Ansi8BitAlias) -> type[ansicolor8Bit]
get_ansi_type(typ: Ansi24BitAlias) -> type[ansicolor24Bit]
Source code in chromatic/color/core.py
507
508
509
510
def get_ansi_type(typ=None, /):
    if typ is None:
        return DEFAULT_ANSI
    return _get_ansi_type(typ)

randcolor()

Return a random color as a Color object

Source code in chromatic/color/core.py
600
601
602
def randcolor():
    """Return a random color as a `Color` object"""
    return Color.from_bytes(random.randbytes(3))

rgb2ansi_escape(fmt, /, mode, rgb)

Source code in chromatic/color/core.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
def rgb2ansi_escape(
    fmt: AnsiColorAlias | AnsiColorType, /, mode: ColorDictKeys, rgb: Int3Tuple
):
    fmt = get_ansi_type(fmt)
    if len(rgb) != 3:
        raise ValueError("length of RGB value is not 3")
    try:
        if fmt is ansicolor4Bit:
            return b"%d" % _ANSI16C_KV2I[mode, nearest_ansi_4bit_rgb(rgb)]
        sgr = [_ANSI256_KEY2I[mode]]
        if fmt is ansicolor8Bit:
            sgr += [5, rgb_to_ansi_8bit(rgb)]
        else:
            sgr += [2, *rgb]
        return b";".join(map(b"%d".__mod__, sgr))
    except KeyError:
        pass
    if isinstance(mode, str):
        raise ValueError(f"invalid mode: {mode!r}")
    raise TypeError(
        f"expected 'mode' be {str.__name__!r}, "
        f"got {type(mode).__name__!r} object instead"
    )

set_default_ansi(typ)

Sets the global DEFAULT_ANSI variable to the specified ANSI color format

Source code in chromatic/color/core.py
513
514
515
516
517
def set_default_ansi(typ, /):
    """Sets the global `DEFAULT_ANSI` variable to the specified ANSI color format"""
    if valid_typ := get_ansi_type(typ):
        global DEFAULT_ANSI
        DEFAULT_ANSI = valid_typ

rgb_dispatch(*names, replace_defaults=True)

Returns a decorator which intercepts input arguments that are color name strings, and replaces those arguments with their RGB tuple counterparts before passing them to the wrapped function.

In the bare form, ie. @rgb_dispatch, the decorator treats all positional-only and variadic positional parameters as assignable.

In the named form, ie. @rgb_dispatch("a", "b", "c"), the decorator will only attempt to match and replace those parameter names, regardless of their parameter kind.

Parameters:

Name Type Description Default
*names str

Parameter names to target for color name to RGB tuple replacement.

()
replace_defaults bool

Whether to replace default argument values of the returned callable.

True

Examples:

>>> from chromatic.color.palette import rgb_dispatch
>>> @rgb_dispatch
... def func(r="red", b="blue", g="green", x="not a color", /):
...     return r, g, b, x
...
>>> func()
((255, 0, 0), (0, 128, 0), (0, 0, 255), 'not a color')
>>> func(None, None, None, "Hot Pink")
(None, None, None, (255, 105, 180))
>>> @rgb_dispatch
... def func(a, b, c, /, *args):
...     return a, b, c, *args
...
>>> func("red", "yellow", "pink", "dark magenta", "alice blue")
((255, 0, 0), (255, 255, 0), (255, 192, 203), (139, 0, 139), (240, 248, 255))
>>> @rgb_dispatch("c")
... def func(a, b, c, /, *args):
...     return a, b, c, *args
...
>>> func("red", "yellow", "pink", "dark magenta", "alice blue")
('red', 'yellow', (255, 192, 203), 'dark magenta', 'alice blue')
>>> @rgb_dispatch("color")
... def func(**kwargs):
...     return kwargs
...
>>> func(color="red")
{'color': (255, 0, 0)}
>>> @rgb_dispatch("kwargs")
... def func(**kwargs):
...     return kwargs
...
>>> func(color1="red", color2="yellow", color3="orange")
{'color1': (255, 0, 0), 'color2': (255, 255, 0), 'color3': (255, 165, 0)}
>>> @rgb_dispatch("kwargs")
... def func(a=None, /, **kwargs):
...     return a, kwargs
...
>>> func(a="green")
(None, {'a': (0, 128, 0)})
>>> @rgb_dispatch(replace_defaults=False)
... def func(fruit_or_color="orange", /):
...     res = "fruit" if isinstance(fruit_or_color, str) else "color"
...     return f"{fruit_or_color} is a {res}"
...
>>> func()
'orange is a fruit'
>>> func("orange")
'(255, 165, 0) is a color'
Source code in chromatic/color/palette.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def rgb_dispatch(*names, replace_defaults=True):
    """Returns a decorator which intercepts input arguments that are color
    name strings, and replaces those arguments with their RGB tuple
    counterparts before passing them to the wrapped function.

    In the bare form, ie. ``@rgb_dispatch``, the decorator treats all
    positional-only and variadic positional parameters as assignable.

    In the named form, ie. ``@rgb_dispatch("a", "b", "c")``, the decorator
    will only attempt to match and replace those parameter names, regardless
    of their parameter kind.

    Parameters
    ----------
    *names : str
        Parameter names to target for color name to RGB tuple replacement.
    replace_defaults : bool, default=True
        Whether to replace default argument values of the returned callable.

    Examples
    --------
    >>> from chromatic.color.palette import rgb_dispatch
    >>> @rgb_dispatch
    ... def func(r="red", b="blue", g="green", x="not a color", /):
    ...     return r, g, b, x
    ...
    >>> func()
    ((255, 0, 0), (0, 128, 0), (0, 0, 255), 'not a color')
    >>> func(None, None, None, "Hot Pink")
    (None, None, None, (255, 105, 180))

    >>> @rgb_dispatch
    ... def func(a, b, c, /, *args):
    ...     return a, b, c, *args
    ...
    >>> func("red", "yellow", "pink", "dark magenta", "alice blue")
    ((255, 0, 0), (255, 255, 0), (255, 192, 203), (139, 0, 139), (240, 248, 255))

    >>> @rgb_dispatch("c")
    ... def func(a, b, c, /, *args):
    ...     return a, b, c, *args
    ...
    >>> func("red", "yellow", "pink", "dark magenta", "alice blue")
    ('red', 'yellow', (255, 192, 203), 'dark magenta', 'alice blue')

    >>> @rgb_dispatch("color")
    ... def func(**kwargs):
    ...     return kwargs
    ...
    >>> func(color="red")
    {'color': (255, 0, 0)}

    >>> @rgb_dispatch("kwargs")
    ... def func(**kwargs):
    ...     return kwargs
    ...
    >>> func(color1="red", color2="yellow", color3="orange")
    {'color1': (255, 0, 0), 'color2': (255, 255, 0), 'color3': (255, 165, 0)}

    >>> @rgb_dispatch("kwargs")
    ... def func(a=None, /, **kwargs):
    ...     return a, kwargs
    ...
    >>> func(a="green")
    (None, {'a': (0, 128, 0)})

    >>> @rgb_dispatch(replace_defaults=False)
    ... def func(fruit_or_color="orange", /):
    ...     res = "fruit" if isinstance(fruit_or_color, str) else "color"
    ...     return f"{fruit_or_color} is a {res}"
    ...
    >>> func()
    'orange is a fruit'
    >>> func("orange")
    '(255, 165, 0) is a color'
    """

    def decorator(f: types.FunctionType, /):
        def _prepare():
            assert isinstance(names, set)
            code = f.__code__
            n_args = code.co_argcount
            n_posonly = code.co_posonlyargcount
            n_pos_or_kw = n_args - n_posonly
            n_kwonly = code.co_kwonlyargcount
            flags = code.co_flags
            has_varargs = bool(flags & 0x4)
            has_varkwds = bool(flags & 0x8)
            total = sum([n_args, n_kwonly, has_varargs, has_varkwds])
            params = list(code.co_varnames[:total])
            mask_params = {name: name in names for name in params}
            positions, keywords = [], {}
            if names:
                if total == 0 or not (has_varkwds or names <= mask_params.keys()):
                    unexpected = ", ".join(map(repr, names.difference(mask_params)))
                    raise ValueError(f"unexpected parameter names: {unexpected}")
            elif total == 0 or not (n_pos_or_kw or n_kwonly or has_varkwds):
                if total > 0:
                    positions.extend(range(n_posonly))
                    positions.append(slice(n_posonly, None))
                return tuple(positions), mappingproxy(keywords)
            else:
                raise ValueError("no parameters specified and none could be inferred")
            i = 0
            if n_posonly > 0:
                for name in params[:n_posonly]:
                    if mask_params[name]:
                        positions.append(i)
                    i += 1
                del params[:n_posonly]
            if n_pos_or_kw > 0:
                for name in params[:n_pos_or_kw]:
                    if mask_params[name]:
                        positions.append(i)
                        keywords[name] = positions[-1]
                    i += 1
                del params[:n_pos_or_kw]
            if n_kwonly > 0:
                for name in params[:n_kwonly]:
                    if mask_params[name]:
                        keywords[name] = None
                del params[:n_kwonly]
            if has_varargs:
                if mask_params[params.pop(0)]:
                    positions.append(slice(i, None))
            if has_varkwds:
                if mask_params[params.pop(0)]:
                    keywords[None] = None
                keywords |= dict.fromkeys(names.difference(code.co_varnames[:total]))
            return tuple(positions), mappingproxy(keywords)

        POSITIONS, KEYWORDS = _prepare()
        HAS_VARKW = None in KEYWORDS

        def _replace_defaults():
            argdefs = f.__defaults__
            kwdefaults = f.__kwdefaults__
            changed = False
            if argdefs is not None:
                argcount = f.__code__.co_argcount
                buf = list(argdefs)
                for i, (j, x) in zip(
                    range(argcount - len(argdefs), argcount), enumerate(argdefs)
                ):
                    if i in POSITIONS and isinstance(x, str):
                        try:
                            buf[j] = _rgb_lookup(x)
                        except KeyError:
                            continue
                        changed = True
                argdefs = tuple(buf)
            if kwdefaults is not None:
                kwdefaults = kwdefaults.copy()
                for k, v in kwdefaults.items():
                    if k in KEYWORDS and isinstance(v, str):
                        try:
                            kwdefaults[k] = _rgb_lookup(v)
                        except KeyError:
                            continue
                        changed = True
            if not changed:
                return f
            if sys.version_info >= (3, 13):
                f_new = types.FunctionType(
                    f.__code__,
                    f.__globals__,
                    name=f.__name__,
                    argdefs=argdefs,
                    closure=f.__closure__,
                    kwdefaults=kwdefaults,
                )
            else:
                f_new = types.FunctionType(
                    f.__code__,
                    f.__globals__,
                    name=f.__name__,
                    argdefs=argdefs,
                    closure=f.__closure__,
                )
                setattr(f_new, "__kwdefaults__", kwdefaults)
            setattr(f_new, "__wrapped__", f)
            return f_new

        if replace_defaults:
            f = _replace_defaults()

        @ft.wraps(f)
        def wrapper(*args, **kwargs):
            _kwargs = kwargs.copy()
            n_args = len(args)
            mask = [False] * n_args
            for idx in POSITIONS:
                if isinstance(idx, slice):
                    for i in range(*idx.indices(n_args)):
                        mask[i] = True
                elif idx < n_args:
                    mask[idx] = True
            for k, v in kwargs.items():
                if (k in KEYWORDS or HAS_VARKW) and isinstance(v, str):
                    try:
                        v = _rgb_lookup(v)
                    except KeyError:
                        continue
                    _kwargs[k] = v
                    if (i := KEYWORDS.get(k)) is None or i >= n_args:
                        continue
                    mask[i] = False
            _args = []
            for g, v in zip(mask, args):
                if g and isinstance(v, str):
                    try:
                        v = _rgb_lookup(v)
                    except KeyError:
                        pass
                _args.append(v)
            return f(*_args, **_kwargs)

        return wrapper

    f = None
    if names and callable(names[0]):
        f, *names = names
    names = set(names)
    return decorator if f is None else decorator(f)