Colorful
Colorful is a Python library that provides expressive and consistent terminal string styling. It supports various color modes including 8 ANSI, 256 ANSI, and true colors, along with predefined styles (like Solarized) and custom color palettes. The current version is 0.5.8, and it is actively maintained with several releases per year.
Warnings
- breaking Python 2 support was officially dropped in `colorful` version 0.5.5. Attempts to use versions 0.5.5 or newer with Python 2 will result in `ImportError` or other compatibility issues.
- gotcha Versions prior to 0.5.7 might encounter an `AttributeError: 'DualOutput' object has no attribute 'isatty'` when interacting with specific terminal output streams, particularly in certain environments or configurations.
- gotcha In versions older than 0.5.5, there were known issues with `setup(colormode=NO_COLORS)` not behaving as expected and the `__str__` representation of `ColorfulString` objects not always correctly returning a plain string.
- gotcha Older versions (prior to 0.5.4) had an incorrect implementation of the `__getattr__` protocol, which could lead to unexpected behavior when dynamically accessing color and style attributes (e.g., `cf.some_color_name`).
- gotcha Although `colorful` generally manages color resets, explicitly using `cf.reset` or context managers (`with cf.with_...`) is good practice. Without proper resets, especially if a script terminates unexpectedly, terminal color settings might 'bleed' into subsequent shell output, affecting the console's appearance after your program exits.
Install
-
pip install colorful
Imports
- colorful
import colorful as cf
Quickstart
import colorful as cf
import os
# Basic text styling
print(cf.red('Hello, red World!'))
print(cf.bold_green('This is bold and green.'))
# Combining styles using bitwise operators
print(cf.italic & cf.coral_on_beige | 'Styled with italic, coral text on beige background.')
# Using f-strings (Python >= 3.6)
user_name = os.environ.get('USER', 'Guest')
print(f'{cf.blue_on_white}Hello, {user_name}! Enjoy Colorful!{cf.reset}')
# Extending the default color palette
cf.update_palette({'companyOrange': '#f4b942', 'companyBlue': '#4287f5'})
print(cf.companyOrange_on_companyBlue('Custom company colors!'))
# Using a context manager for temporary color mode
with cf.with_8_ansi_colors() as c:
print(c.bold_magenta('This text uses 8 ANSI colors only.'))
# Printing with format-string like syntax
cf.print('{c.cyan}Formatted {c.underline}output{c.reset} with {c.yellow}placeholders{c.reset}',
name=cf.bold_white('Colorful'))