Skip to content

Commit 8a5ab3e

Browse files
committed
Allow Colour name to be overridden.
1 parent 1cac3f4 commit 8a5ab3e

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

consolekit/terminal_colours.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,21 +213,39 @@ class Colour(str):
213213
:type stack: :class:`~typing.List`\[:class:`str`\]
214214
:param reset: The escape sequence to reset the style.
215215
:type reset: :class:`str`
216+
:param name: A friendly name for the style.
217+
:type name: :class:`str`
216218
219+
.. versionchanged:: 1.10.0 Added ``name`` parameter.
217220
.. autosummary-widths:: 7/16
218221
"""
219222

220-
__slots__ = ("style", "reset", "stack")
223+
__slots__ = ("style", "reset", "stack", "name")
221224

222225
style: str
223226
reset: str
224227
stack: Union[Deque[str], List[str]]
228+
name: str
225229

226-
def __new__(cls, style: str, stack: Union[Deque[str], List[str]], reset: str) -> "Colour": # noqa: D102
230+
def __repr__(self) -> str:
231+
if self.name:
232+
return f"<Colour({super().__repr__()}, name={self.name!r})>"
233+
else:
234+
return f"<Colour({super().__repr__()})>"
235+
236+
def __new__( # noqa: D102
237+
cls,
238+
style: str,
239+
stack: Union[Deque[str], List[str]],
240+
reset: str,
241+
*,
242+
name: Optional[str] = None,
243+
) -> "Colour":
227244
self = super().__new__(cls, style) # type: ignore[import]
228245
self.style = style
229246
self.stack = stack
230247
self.reset = reset
248+
self.name = name # Friendly name
231249

232250
return self
233251

@@ -460,7 +478,7 @@ def __init_subclass__(cls, **kwargs) -> None: # noqa: PRM002
460478
for name in dir(cls):
461479
if not name.startswith('_'):
462480
value = getattr(cls, name)
463-
setattr(cls, name, Colour(code_to_chars(value), cls._stack, cls._reset))
481+
setattr(cls, name, Colour(code_to_chars(value), cls._stack, cls._reset, name=name))
464482

465483
def __new__(cls: Type[_AC], *args, **kwargs) -> Type[_AC]: # noqa: D102
466484
return cls

tests/test_terminal_colours.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,14 @@ def test_from_hex(self):
9797
assert yellow == "\u001b[48;2;252;186;3m"
9898
assert yellow("Hello") == "\u001b[48;2;252;186;3mHello\u001b[49m"
9999

100+
def test_repr(self):
101+
black = Colour.from_code(30)
102+
assert repr(black) == "<Colour('\\x1b[30m')>"
103+
104+
yellow = Colour.from_hex("#fcba03", background=True)
105+
yellow.name = "yellow"
106+
assert repr(yellow) == "<Colour('\\x1b[48;2;252;186;3m', name='yellow')>"
107+
100108

101109
def test_print_256_colour_testpattern(
102110
monkeypatch,

0 commit comments

Comments
 (0)