summaryrefslogtreecommitdiff
path: root/cmd2/ansi.py
diff options
context:
space:
mode:
authorKevin Van Brunt <kmvanbrunt@gmail.com>2020-02-07 13:08:35 -0500
committerKevin Van Brunt <kmvanbrunt@gmail.com>2020-02-07 13:08:35 -0500
commit0d7d533f9077fcd422d8192dc675f4a2f8f32cbb (patch)
tree5b76244bbf17756b0c1c09a21509e2a2515f958f /cmd2/ansi.py
parenta73d30035c212cefab1c11c33d943d616728ce89 (diff)
downloadcmd2-git-0d7d533f9077fcd422d8192dc675f4a2f8f32cbb.tar.gz
Added __str__() back to ColorBase for more flexibility in its usage
Updated documentation and added unit tests
Diffstat (limited to 'cmd2/ansi.py')
-rw-r--r--cmd2/ansi.py22
1 files changed, 18 insertions, 4 deletions
diff --git a/cmd2/ansi.py b/cmd2/ansi.py
index 27086d4a..3a106776 100644
--- a/cmd2/ansi.py
+++ b/cmd2/ansi.py
@@ -32,13 +32,27 @@ class ColorBase(Enum):
Base class for fg and bg classes
This expects the child classes to define enums of: color name -> ANSI color sequence
"""
+ def __str__(self) -> str:
+ """
+ Return ANSI color sequence instead of enum name
+ This is helpful when using a ColorBase in an f-string or format() call
+ e.g. my_str = "{}hello{}".format(fg.blue, fg.reset)
+ """
+ return self.value
+
def __add__(self, other: Any) -> str:
- """Return self + other as string"""
- return self.value + other
+ """
+ Support building a color string when self is the left operand
+ e.g. fg.blue + "hello"
+ """
+ return str(self) + other
def __radd__(self, other: Any) -> str:
- """Return other + self as string"""
- return other + self.value
+ """
+ Support building a color string when self is the right operand
+ e.g. "hello" + fg.reset
+ """
+ return other + str(self)
@classmethod
def colors(cls) -> List[str]: