Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can we make formatting strings from AnsiCodes object attributes #373

Open
KommuSoft opened this issue Mar 3, 2023 · 2 comments
Open

Can we make formatting strings from AnsiCodes object attributes #373

KommuSoft opened this issue Mar 3, 2023 · 2 comments

Comments

@KommuSoft
Copy link

KommuSoft commented Mar 3, 2023

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
Copy link

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.

@KommuSoft
Copy link
Author

Rethinking this, perhaps the __call__ is indeed a bad idea, but perhaps just adding an extra method like .sandwich(..) could be useful?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants