Terminal colored text. Example: >>> c = colored(enabled=True) >>> print(str(c.red('the quick '), c.blue('brown ', c.bold('fox ')), ... c.magenta(c.underline('jumps over')), ... c.yellow(' the lazy '), ... c.green('dog ')))
| 34 | |
| 35 | |
| 36 | class colored: |
| 37 | """Terminal colored text. |
| 38 | |
| 39 | Example: |
| 40 | >>> c = colored(enabled=True) |
| 41 | >>> print(str(c.red('the quick '), c.blue('brown ', c.bold('fox ')), |
| 42 | ... c.magenta(c.underline('jumps over')), |
| 43 | ... c.yellow(' the lazy '), |
| 44 | ... c.green('dog '))) |
| 45 | """ |
| 46 | |
| 47 | def __init__(self, *s: object, **kwargs: Any) -> None: |
| 48 | self.s: tuple[object, ...] = s |
| 49 | self.enabled: bool = not IS_WINDOWS and kwargs.get('enabled', True) |
| 50 | self.op: str = kwargs.get('op', '') |
| 51 | self.names: dict[str, Any] = { |
| 52 | 'black': self.black, |
| 53 | 'red': self.red, |
| 54 | 'green': self.green, |
| 55 | 'yellow': self.yellow, |
| 56 | 'blue': self.blue, |
| 57 | 'magenta': self.magenta, |
| 58 | 'cyan': self.cyan, |
| 59 | 'white': self.white, |
| 60 | } |
| 61 | |
| 62 | def _add(self, a: object, b: object) -> str: |
| 63 | return f"{a}{b}" |
| 64 | |
| 65 | def _fold_no_color(self, a: Any, b: Any) -> str: |
| 66 | try: |
| 67 | A = a.no_color() |
| 68 | except AttributeError: |
| 69 | A = str(a) |
| 70 | try: |
| 71 | B = b.no_color() |
| 72 | except AttributeError: |
| 73 | B = str(b) |
| 74 | |
| 75 | return f"{A}{B}" |
| 76 | |
| 77 | def no_color(self) -> str: |
| 78 | if self.s: |
| 79 | return str(reduce(self._fold_no_color, self.s)) |
| 80 | return '' |
| 81 | |
| 82 | def embed(self) -> str: |
| 83 | prefix = '' |
| 84 | if self.enabled: |
| 85 | prefix = self.op |
| 86 | return f"{prefix}{reduce(self._add, self.s)}" |
| 87 | |
| 88 | def __str__(self) -> str: |
| 89 | suffix = '' |
| 90 | if self.enabled: |
| 91 | suffix = RESET_SEQ |
| 92 | return f"{self.embed()}{suffix}" |
| 93 |
no outgoing calls