Skip to content

Instantly share code, notes, and snippets.

@mtalimanchuk
Created September 14, 2019 12:08
Show Gist options
  • Save mtalimanchuk/688e3e81a0ff23917299eef357167e15 to your computer and use it in GitHub Desktop.
Save mtalimanchuk/688e3e81a0ff23917299eef357167e15 to your computer and use it in GitHub Desktop.
Class representing console colors
class colors:
BLACK = "\u001b[30m"
PALE_RED = "\u001b[31m"
PALE_GREEN = "\u001b[32m"
PALE_YELLOW = "\u001b[33m"
PALE_BLUE = "\u001b[34m"
PALE_MAGENTA = "\u001b[35m"
PALE_CYAN = "\u001b[36m"
GRAY = "\u001b[90m"
RED = "\u001b[91m"
GREEN = "\u001b[92m"
YELLOW = "\u001b[93m"
BLUE = "\u001b[94m"
MAGENTA = "\u001b[95m"
CYAN = "\u001b[96m"
WHITE = "\u001b[97m"
BG_GRAY = "\u001b[100m"
BG_RED = "\u001b[41m"
BG_GREEN = "\u001b[42m"
BG_YELLOW = "\u001b[43m"
BG_BLUE = "\u001b[44m"
BG_MAGENTA = "\u001b[45m"
BG_CYAN = "\u001b[46m"
BG_WHITE = "\u001b[47m"
BOLD = "\u001b[1m"
RESET = "\u001b[0m"
@totekuh
Copy link

totekuh commented Sep 14, 2019

@staticmethod
def colored(text, color=WHITE):
    return f"{color}{text}{colors.RESET}"

@staticmethod
def print_colored(text, color=WHITE):
    print(colors.colored(text, color))

@staticmethod
def red(text):
    return colors.colored(text, colors.RED)

@staticmethod
def green(text):
    return colors.colored(text, colors.GREEN)

@staticmethod
def yellow(text):
    return colors.colored(text, colors.YELLOW)

@staticmethod
def bold(text):
    return colors.colored(text, colors.BOLD)

@staticmethod
def print_red(text):
    colors.print_colored(text, colors.RED)

@staticmethod
def print_bold(text):
    print(colors.bold(text))

@staticmethod
def print_green(text):
    print(colors.green(text))

@mtalimanchuk
Copy link
Author

@derstolz nice example, thanks. Although putting colors into an f-string directly looks more flexible:
f"{colors.RED}{colors.BG_GRAY} Red text on gray bg {colors.BG_CYAN} Still red text but on cyan bg {colors.RESET}"

@totekuh
Copy link

totekuh commented Sep 17, 2019

@mtalimanchuk
I don't think so, because it's not portable to older version of Python

@mtalimanchuk
Copy link
Author

@derstolz
"{0}{1} Red text on gray bg {2} Still red text but on cyan bg {3}".format(colors.RED, colors.BG_GRAY, colors.BG_CYAN, colors.RESET)

@mtalimanchuk
Copy link
Author

Anyway static methods are good for wrapping your custom tasks, e.g.:

@staticmethod
def colorize_article(title, text, comments):
    title = f"{colors.BG_GRAY}{colors.YELLOW}{title}{colors.RESET}"
    text = f"{colors.BOLD}{text}{colors.RESET}"
    comments = f"{colors.BG_YELLOW}{comments}{colors.RESET}"
    return '\n'.join([title, text, comments])

@totekuh
Copy link

totekuh commented Sep 19, 2019

@mtalimanchuk you don't have to define positional arguments with .format() method:
image

@mtalimanchuk
Copy link
Author

@derstolz I know, I used them for readability

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment