tartley / colorama

Simple cross-platform colored terminal text in Python
BSD 3-Clause "New" or "Revised" License
3.51k stars 249 forks source link

Can we make formatting strings from AnsiCodes object attributes #373

Open KommuSoft opened 1 year ago

KommuSoft commented 1 year ago

In the AnsiCodes, we use some logic in the __init__ to make Fore.RED for example to a string.

We could subclass the str class to make it callable, for example:

class FormattingString(str):
    def __call__(self, val):
        return f'{self}{val}{Fore.RESET}'

Then in the code_to_chars method, we can wrap the string into a FormattingString:

def code_to_chars(code):
    return FormattingString(CSI + str(code) + 'm')

This makes it useful for short formatting, like:

print(Fore.RED('foo'))

which will print the foo into red, and then reset it, so:

In [5]: Fore.RED('foo')
Out[5]: '\x1b[31mfoo\x1b[39m'

Is this an improvement that might be considered?

RamonOpazo commented 1 year ago

I like this idea, for it is a common use case to just style lines of text (and not bleed the effects to the rest of the output). The extension of functionality to add a call behavior is simple enough, but it's also very opinionated.