Colab Print

Colab Print is a Python library that enhances the display capabilities of Jupyter and Google Colab notebooks, providing beautiful, customizable HTML outputs for text, lists, dictionaries, tables, pandas DataFrames, and progress bars.
Features
- 🎨 Rich Text Styling - Display text with predefined styles or custom CSS
- 📊 Beautiful DataFrame Display - Present pandas DataFrames with extensive styling options
- 📑 Customizable Tables - Create HTML tables with headers, rows, and custom styling
- 📜 Formatted Lists - Display Python lists and tuples as ordered or unordered HTML lists
- 📖 Readable Dictionaries - Render dictionaries as structured definition lists
- 🎭 Extensible Themes - Use built-in themes or create your own custom styles
- 📏 Smart Row/Column Limiting - Automatically display large DataFrames with sensible limits
- 🔍 Cell Highlighting - Highlight specific rows, columns, or individual cells in tables and DataFrames
- 📊 Progress Tracking - Display elegant progress bars with tqdm compatibility
- 🔄 Graceful Fallbacks - Works even outside Jupyter/IPython environments
- 🧩 Structured Data Detection - Automatic handling of nested structures, matrices, and array-like objects
Installation
pip install colab-print
Quick Start
from colab_print import Printer, header, success, progress
import pandas as pd
import time
printer = Printer()
header("Colab Print Demo")
success("Library loaded successfully!")
printer.display("Hello, World!", style="highlight")
my_list = ['apple', 'banana', ['nested', 'item'], 'cherry', {'key': 'value'}]
printer.display_list(my_list, ordered=True, style="info")
for i in progress(range(10), desc="Processing"):
time.sleep(0.2)
my_dict = {
'name': 'Alice',
'age': 30,
'address': {'street': '123 Main St', 'city': 'Anytown'}
}
printer.display_dict(my_dict, style="success")
headers = ["Name", "Age", "City"]
rows = [
["Alice", 28, "New York"],
["Bob", 34, "London"],
["Charlie", 22, "Paris"]
]
printer.display_table(headers, rows, style="default")
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [28, 34, 22],
'City': ['New York', 'London', 'Paris']
})
printer.display_df(df,
highlight_cols=['Name'],
highlight_cells={(0, 'Age'): "background-color: #FFEB3B;"},
caption="Sample DataFrame")
Styling & Shortcut Functions
Predefined Style Shortcuts
Colab Print provides convenient shortcut functions with pre-configured styling:
from colab_print import (
header, title, subtitle, section_divider, subheader,
code, card, quote, badge, data_highlight, footer,
highlight, info, success, warning, error, muted, primary, secondary,
dfd, table, list_, dict_, progress
)
header("Main Section")
title("Document Title")
subtitle("Supporting information")
success("Operation completed!")
warning("Proceed with caution")
error("An error occurred")
code("print('Hello World')")
table(headers, rows)
list_(my_list, ordered=True)
dict_(my_dict)
dfd(df, highlight_cols=["Name"])
Predefined Styles
default
- Clean, professional styling
highlight
- Stand-out text with emphasis
info
- Informational blue text
success
- Positive green message
warning
- Attention-grabbing yellow alert
error
- Critical red message
muted
- Subtle gray text
primary
- Primary blue-themed text
secondary
- Secondary purple-themed text
code
- Code-like display with monospace font
card
- Card-like container with shadow
quote
- Styled blockquote
notice
- Attention-drawing notice
badge
- Compact badge-style display
Custom Styling
You can add your own styles:
printer = Printer()
printer.add_style("custom", "color: purple; font-size: 20px; font-weight: bold;")
printer.display("Custom styled text", style="custom")
Display Methods
printer.display(text, style="default", **inline_styles)
: Displays styled text.
printer.display_list(items, ordered=False, style="default", item_style=None, **inline_styles)
: Displays lists/tuples.
printer.display_dict(data, style="default", key_style=None, value_style=None, **inline_styles)
: Displays dictionaries.
printer.display_table(headers, rows, style="default", **table_options)
: Displays basic tables.
printer.display_df(df, style="default", **df_options)
: Displays pandas DataFrames with many options.
printer.display_progress(total, desc="", style="default", **progress_options)
: Displays a progress bar.
Progress Tracking
Colab Print offers powerful progress tracking with tqdm compatibility:
from colab_print import progress, Printer
import time
for i in progress(range(100), desc="Processing"):
time.sleep(0.01)
printer = Printer()
progress_id = printer.display_progress(total=50, desc="Manual progress")
for i in range(50):
time.sleep(0.05)
printer.update_progress(progress_id, i+1)
for i in progress(range(100),
desc="Custom progress",
color="#9C27B0",
height="25px",
style="card"):
time.sleep(0.01)
progress_id = printer.display_progress(total=None, desc="Loading...", animated=True)
time.sleep(3)
DataFrame Display Options
The display_df
method supports numerous customization options:
printer.display_df(df,
style='default',
max_rows=20,
max_cols=10,
precision=2,
header_style="...",
odd_row_style="...",
even_row_style="...",
index=True,
width="100%",
caption="My DataFrame",
highlight_cols=["col1"],
highlight_rows=[0, 2],
highlight_cells={(0,0): "..."},
font_size="14px",
text_align="center")
Advanced List Display
Colab Print automatically detects and optimally displays complex data structures:
from colab_print import list_
import numpy as np
import pandas as pd
nested_list = [1, 2, [3, 4, [5, 6]], 7]
list_(nested_list)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list_(matrix)
np_array = np.array([[1, 2, 3], [4, 5, 6]])
list_(np_array)
series = pd.Series([1, 2, 3, 4])
list_(series)
list_(matrix, matrix_mode=False)
Advanced Usage
Creating Custom Themes
custom_themes = {
'dark': 'color: white; background-color: #333; font-size: 16px;',
'fancy': 'color: #8A2BE2; font-family: "Brush Script MT", cursive; font-size: 20px;'
}
printer = Printer(additional_styles=custom_themes)
printer.display("Dark theme", style="dark")
printer.display("Fancy theme", style="fancy")
Creating Reusable Display Functions
my_header = printer.create_styled_display("header", color="#FF5722", font_size="24px")
my_header("First Section")
my_header("Second Section")
my_header("Special Section", color="#9C27B0")
Handling Non-Notebook Environments
The library gracefully handles non-IPython environments by printing fallback text representations:
printer.display_list([1, 2, 3])
printer.display_dict({'a': 1})
printer.display_df(df)
Exception Handling
Colab Print includes a comprehensive exception hierarchy for robust error handling:
from colab_print import (
ColabPrintError,
StyleNotFoundError,
DataFrameError,
InvalidParameterError,
HTMLRenderingError
)
try:
printer.display("Some text", style="non_existent_style")
except StyleNotFoundError as e:
print(f"Style error: {e}")
Full Examples
For a comprehensive demonstration of all features, please see the example script:
example.py
This script covers:
- Text, List, Dictionary, Table, and DataFrame display
- Using built-in styles and inline styles
- Adding custom styles
- Creating a Printer instance with custom themes
- Highlighting options for DataFrames
- Progress bar usage and customization
- Advanced list and nested structure display
- Exception handling
- Fallback behavior notes
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.