From 800c50aeab5e8a9caa8ca0c9edff27a211ee6a3e Mon Sep 17 00:00:00 2001 From: Matthew Peveler Date: Mon, 9 Sep 2019 06:41:35 -0300 Subject: [PATCH] Add random() to select a color at random (#14) --- crayons.py | 20 +++++++++++++++++--- test_crayons.py | 2 ++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/crayons.py b/crayons.py index 2cd82f9..fba7c79 100644 --- a/crayons.py +++ b/crayons.py @@ -2,6 +2,7 @@ """A simple and elegant wrapper for colorama.""" import os +from random import choice, seed import re import sys @@ -13,11 +14,13 @@ PY3 = sys.version_info[0] >= 3 __all__ = ( 'red', 'green', 'yellow', 'blue', 'black', 'magenta', 'cyan', 'white', - 'clean', 'disable', 'enable' + 'clean', 'disable', 'enable', 'random' ) colorama.init() -COLORS = __all__[:-2] +seed() +COLORS = __all__[:-4] + if 'get_ipython' in dir(): """ @@ -123,7 +126,7 @@ def clean(s): return txt -_colors = {x: x.upper() for x in __all__[:-3]} +_colors = {x: x.upper() for x in COLORS} _colors['normal'] = 'RESET' for key, val in _colors.items(): @@ -134,6 +137,17 @@ for key, val in _colors.items(): del key, val, _colors, function +def random(string, always=False, bold=False, colors=COLORS): + """Selects a color at random from a list.""" + colors = list(filter(lambda color: color in COLORS, colors)) or COLORS + return ColoredString( + choice(colors).upper(), + string, + always_color=always, + bold=bold + ) + + def disable(): """Disables colors.""" global DISABLE_COLOR diff --git a/test_crayons.py b/test_crayons.py index 3c84386..4ea7279 100755 --- a/test_crayons.py +++ b/test_crayons.py @@ -13,3 +13,5 @@ print(crayons.red('red string', bold=True)) print(crayons.yellow('yellow string', bold=True)) print(crayons.magenta('magenta string', bold=True)) print(crayons.white('white string', bold=True)) +print(crayons.random('random color')) +print(crayons.random('random and bold', bold=True))