When they're not builtins, they're boltons.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
String formatting utilities, tabular data handling, and HTML table generation. Includes format string parsing, table creation from various data sources, and flexible output formatting for structured data presentation.
Advanced format string manipulation and analysis utilities.
def split_format_str(fstr):
"""
Split format string into components.
Parameters:
- fstr (str): Format string to split
Returns:
list: List of format string components
"""
def construct_format_field_str(fname, fspec, conv):
"""
Build format field strings.
Parameters:
- fname (str): Field name
- fspec (str): Format specification
- conv (str): Conversion type
Returns:
str: Constructed format field string
"""
def infer_positional_format_args(fstr):
"""
Infer positional argument count from format string.
Parameters:
- fstr (str): Format string to analyze
Returns:
int: Number of positional arguments required
"""
def get_format_args(fstr):
"""
Extract all format arguments from format string.
Parameters:
- fstr (str): Format string to analyze
Returns:
list: List of format argument specifications
"""
def tokenize_format_str(fstr, resolve_pos=True):
"""
Tokenize format string into components.
Parameters:
- fstr (str): Format string to tokenize
- resolve_pos (bool): Resolve positional arguments
Returns:
list: List of format tokens
"""Classes for representing format field components.
class BaseFormatField:
"""Base class for format field representation."""
def __init__(self, fname, fspec, conv): ...
@property
def field_name(self): ...
@property
def format_spec(self): ...
@property
def conversion(self): ...
def __str__(self): ...
class DeferredValue:
"""Wrapper for values computed at format time."""
def __init__(self, func, *args, **kwargs): ...
def get_value(self): ...Flexible table implementation supporting multiple input and output formats.
class Table:
"""Flexible table data structure with multiple input/output formats."""
def __init__(self, data=None, headers=None, **kwargs): ...
# Properties
@property
def headers(self): ...
@property
def data(self): ...
@property
def row_count(self): ...
@property
def col_count(self): ...
# Data manipulation
def add_row(self, row_data): ...
def add_column(self, header, column_data): ...
def extend(self, table_data): ...
def sort(self, key=None, reverse=False): ...
# Output formats
def to_html(self, **kwargs): ...
def to_text(self, **kwargs): ...
def to_csv(self, **kwargs): ...
def to_list(self): ...
def to_dict(self): ...
# Iteration
def __iter__(self): ...
def __getitem__(self, index): ...Specialized handlers for different table data input formats.
class InputType:
"""Base class for table input type handlers."""
def __init__(self, **kwargs): ...
def normalize_data(self, data): ...
class DictInputType(InputType):
"""Handler for dictionary-based table data."""
def normalize_data(self, data): ...
class ObjectInputType(InputType):
"""Handler for object-based table data."""
def normalize_data(self, data): ...
class ListInputType(InputType):
"""Handler for list-based table data."""
def normalize_data(self, data): ...
class TupleInputType(InputType):
"""Handler for tuple-based table data."""
def normalize_data(self, data): ...
class NamedTupleInputType(InputType):
"""Handler for namedtuple-based table data."""
def normalize_data(self, data): ...Utilities for converting objects to text representations.
def to_text(obj, maxlen=None):
"""
Convert object to text representation.
Parameters:
- obj: Object to convert
- maxlen (int, optional): Maximum length for text
Returns:
str: Text representation of object
"""
def escape_html(obj, maxlen=None):
"""
HTML-escape object representation.
Parameters:
- obj: Object to escape
- maxlen (int, optional): Maximum length before truncation
Returns:
str: HTML-escaped text representation
"""from boltons.formatutils import get_format_args, split_format_str
from boltons.tableutils import Table, to_text
# Format string analysis
format_str = "Hello {name}, you have {count:d} {item}s!"
args = get_format_args(format_str)
print(args) # Information about format arguments
components = split_format_str(format_str)
print(components) # Format string broken into components
# Table creation from various data sources
# From list of dictionaries
dict_data = [
{'name': 'Alice', 'age': 30, 'city': 'New York'},
{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]
table = Table(dict_data)
print(table.to_text())
# HTML output
html_table = table.to_html(
table_class='data-table',
border=1,
cellpadding=5
)
print(html_table)
# From list of lists with headers
list_data = [
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
headers = ['Name', 'Age', 'City']
table2 = Table(list_data, headers=headers)
csv_output = table2.to_csv()
print(csv_output)
# From objects
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
people = [
Person('Alice', 30, 'New York'),
Person('Bob', 25, 'Los Angeles'),
Person('Charlie', 35, 'Chicago')
]
table3 = Table(people)
print(table3.to_text(max_col_width=15))from boltons.tableutils import Table
# Create table and manipulate data
sales_data = [
{'product': 'Widget', 'quantity': 100, 'price': 10.50},
{'product': 'Gadget', 'quantity': 75, 'price': 25.00},
{'product': 'Doohickey', 'quantity': 50, 'price': 15.75}
]
table = Table(sales_data)
# Add calculated column
revenue_data = [row['quantity'] * row['price'] for row in sales_data]
table.add_column('Revenue', revenue_data)
# Sort by revenue (descending)
table.sort(key=lambda row: row[-1], reverse=True) # Sort by last column (Revenue)
# Add totals row
total_qty = sum(row[1] for row in table.data)
total_revenue = sum(row[3] for row in table.data)
table.add_row(['TOTAL', total_qty, '', total_revenue])
# Generate formatted output
print("Sales Report:")
print("=" * 60)
print(table.to_text(max_col_width=12))
# Custom HTML formatting
html_output = table.to_html(
table_class='sales-report',
table_style='border-collapse: collapse; width: 100%;',
th_style='background-color: #f2f2f2; padding: 8px;',
td_style='padding: 8px; border-bottom: 1px solid #ddd;'
)
# Export to various formats
with open('sales_report.csv', 'w') as f:
f.write(table.to_csv())
# Iterate through table data
print("Individual rows:")
for i, row in enumerate(table):
print(f"Row {i}: {row}")
# Access specific cells
print(f"Product in first row: {table[0][0]}")
print(f"Revenue in second row: {table[1][3]}")from boltons.formatutils import (
tokenize_format_str, infer_positional_format_args,
BaseFormatField, DeferredValue
)
# Analyze complex format strings
complex_format = "Item: {item.name:>20}, Price: ${item.price:8.2f}, Stock: {stock:d}"
# Tokenize the format string
tokens = tokenize_format_str(complex_format)
print("Format tokens:")
for token in tokens:
print(f" {token}")
# Infer argument requirements
pos_args_needed = infer_positional_format_args("{0} + {1} = {2}")
print(f"Positional arguments needed: {pos_args_needed}") # 3
# Dynamic value formatting with DeferredValue
import datetime
def current_time():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
deferred_time = DeferredValue(current_time)
# Format string with deferred evaluation
log_format = "Log entry at {timestamp}: {message}"
formatted = log_format.format(
timestamp=deferred_time.get_value(),
message="System started"
)
print(formatted)# Exceptions
class UnsupportedData(TypeError):
"""Exception for unsupported data types in table processing."""
pass
# Format field components
FormatToken = tuple # (literal_text, field_spec) pairs from tokenized format stringsInstall with Tessl CLI
npx tessl i tessl/pypi-boltons