I have output lines that contain various elements that I want to display with different colors using ANSI escape codes.
- I cannot add the escape codes before formatting because the length of the escape codes is taken in account by the Python formatter, and this won't work with numbers or conversions such as
!ranyway. - I can format every item separately as a single string, add the escape codes, and splice all these together to create the final string but this makes for bulky code.
- I can add the escape codes in the format string but this makes it quite unreadable and hard to maintain (where did I use the red?)
- I can improve on this by putting the escape codes in strings and add these to the variables used in the formatting, but this pollutes the "true variables" list (and I have to add before/after sequences...)
There has got to be a better way?
It turns out there is, by using a subclass of the Python
string.Formatter.It appears that the standard Formatter parses out the format specs in a rather lenient way, so if one adds a color specification such as the
:bluein{hexNum:04x:blue}, the format spec downstream is04x:blue, so in the overriddenformat_field(value,format_spec)method it can be split into the "standard" part that is passed to the default formatter, and the "extra" part that is used to post-process the string returned by the default formatter.In practice:
Example of use:
The rendered output:
Caveat: this works with my Python 3.10.12, I didn't try it with other versions