How to call a random color?
hagfelsh opened this issue · comments
Happy Thanksgiving!
TLDR: How can I ask blessed to give me a random color's name so I can reuse it later in a memoizer?
I'm puzzling out how to make a unique color memoizer for strings. The idea is the first time 'string' is used, I shove it through the memoizer and it randomly chooses one of the x11 colors you have in colorspace.py's X11_COLORNAMES_TO_RGB
class.
It stores the random choice in a {some_unique_string: term_color_name}
entry in the dict and returns it. Future visits are just looked up and returned the same.
Example:
I send in 'turkey' to the memoizer; it's not a key in the memo dict so it does magic and saves an associated term x11 color with 'turkey' as the key and then returns the randomly chosen color's name.
However... being rather new at this stuff, I've not figured out how to stuff a string like 'bold_blue'
into a proper python statement like this:
print(term. + get_stored_color(string)('special colored words'))
which would operate the same as
print(term.bold_blue('special colored words'))
As you might imagine python has nothing good to say about me doing it this way... I'm certain I have the wrong idea, but I hoping this headache of mine is a one sentence one-shot for you.
I got close by using Terminal.color_rgb()
after I figured out how to harvest r/g/b out of the X11_COLORNAMES_TO_RGB
object. Trouble with that is I get the literal sequences and I can't leverage ljust
or similar. Or can I and I've not figured out how?
Thanks for your time :)
ps: I'm quite new to python and programming in general and I must say... Blessed is written and documented so well that it just works every time all the time. It's a delight to use.
This type of question is better asked on a platform like Stack Overflow. It's a more appropriate forum and you'll often get a faster response. That said, this is pretty simple and I didn't get to do any coding today, so here's an answer.
I think you were on the right track, but just missing some of the things that make doing this easier, specifically:
functools.cache() - Easy memoization
getattr() - Retrieve an attribute by name
random.choice() - Returns a random value from a sequence
import functools
import random
import blessed
import blessed.colorspace
X11_COLORS = tuple(blessed.colorspace.X11_COLORNAMES_TO_RGB)
@functools.cache
def get_stored_color(key):
return random.choice(X11_COLORS)
term = blessed.Terminal()
key1 = 'turkey'
text1 = 'The key was turkey'
key2 = 'stuffing'
text2 = 'The key was stuffing'
print(getattr(term, get_stored_color(key1))(text1))
print(getattr(term, get_stored_color(key2))(text2))
print(term.center(getattr(term, get_stored_color(key1))(text1)))