In C curses, it is possible to store a character and associated attributes in a variable of type chtype
(which is usually an unsigned int
). This is useful when you want, for example, an easily reusable string where some characters have different attributes, that requires only a single call to addchstr()
per use. The following C program exemplifies this:
#include <curses.h>
static const chtype hello[] = {
'H' | A_BOLD,
'e' | COLOR_PAIR(1) | A_UNDERLINE,
'l' | COLOR_PAIR(2) | A_REVERSE,
'l' | COLOR_PAIR(3) | A_ITALIC,
'o',
' ' | COLOR_PAIR(1),
'W' | COLOR_PAIR(2) | A_BOLD,
'o' | COLOR_PAIR(3) | A_STANDOUT,
'r' | A_BOLD,
'l' | COLOR_PAIR(1) | A_ITALIC | A_UNDERLINE | A_BLINK,
'd' | COLOR_PAIR(2),
'!' | COLOR_PAIR(3) | A_BOLD | A_REVERSE | A_UNDERLINE | A_ITALIC,
'\0'
};
int main(void){
initscr();
start_color();
cbreak();
noecho();
curs_set(0);
use_default_colors();
init_pair(1, COLOR_YELLOW, COLOR_BLUE);
init_pair(2, COLOR_WHITE, COLOR_GREEN);
init_pair(3, COLOR_RED, COLOR_CYAN);
addchstr(hello);
refresh();
getch();
endwin();
return 0;
}
Define it once and reuse as many times as you want with minimal calls, very practical and keeps the code body concise.
Now, I'm fairly new to Python, but after some reading of the Python curses library page, I figured this behavior could be replicated on individual characters by doing essentially the same thing:
c = ord('A') | curses.A_BOLD
stdscr.addch(c)
But I couldn't find an equivalent for strings. It seems an alternative way is to chain window.addstr()
calls whenever an attribute changes, one for each substring sharing the same attributes, which at least seems better than following the example above and calling window.addch()
on each character, but it still seems excessive and overly verbose. Is there a way or workaround to get this same "define once to reuse easily" behavior for a predefined string without redoing multiple calls for small sections whenever you want to write it again?
Apparently not. Python curses only knows about adding/modifying color/attributes of a window, while C curses has attributed strings.
A chtype
is the older version, while cchar_t
is the newer one, but it's the same concept (with different character capabilities): both are data structures. These functions write strings of those structures:
The problem from Python's point of view is that it would complicate the binding by having to maintain that state (e.g., manage updates to the string itself to set/modify the attributes rather than get the curses library to work with simpler char/wchar_t data types while the attributes are set separately).