0
# Format & Table Utilities
1
2
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.
3
4
## Capabilities
5
6
### Format String Processing
7
8
Advanced format string manipulation and analysis utilities.
9
10
```python { .api }
11
def split_format_str(fstr):
12
"""
13
Split format string into components.
14
15
Parameters:
16
- fstr (str): Format string to split
17
18
Returns:
19
list: List of format string components
20
"""
21
22
def construct_format_field_str(fname, fspec, conv):
23
"""
24
Build format field strings.
25
26
Parameters:
27
- fname (str): Field name
28
- fspec (str): Format specification
29
- conv (str): Conversion type
30
31
Returns:
32
str: Constructed format field string
33
"""
34
35
def infer_positional_format_args(fstr):
36
"""
37
Infer positional argument count from format string.
38
39
Parameters:
40
- fstr (str): Format string to analyze
41
42
Returns:
43
int: Number of positional arguments required
44
"""
45
46
def get_format_args(fstr):
47
"""
48
Extract all format arguments from format string.
49
50
Parameters:
51
- fstr (str): Format string to analyze
52
53
Returns:
54
list: List of format argument specifications
55
"""
56
57
def tokenize_format_str(fstr, resolve_pos=True):
58
"""
59
Tokenize format string into components.
60
61
Parameters:
62
- fstr (str): Format string to tokenize
63
- resolve_pos (bool): Resolve positional arguments
64
65
Returns:
66
list: List of format tokens
67
"""
68
```
69
70
### Format Field Representation
71
72
Classes for representing format field components.
73
74
```python { .api }
75
class BaseFormatField:
76
"""Base class for format field representation."""
77
def __init__(self, fname, fspec, conv): ...
78
@property
79
def field_name(self): ...
80
@property
81
def format_spec(self): ...
82
@property
83
def conversion(self): ...
84
def __str__(self): ...
85
86
class DeferredValue:
87
"""Wrapper for values computed at format time."""
88
def __init__(self, func, *args, **kwargs): ...
89
def get_value(self): ...
90
```
91
92
### Table Data Structure
93
94
Flexible table implementation supporting multiple input and output formats.
95
96
```python { .api }
97
class Table:
98
"""Flexible table data structure with multiple input/output formats."""
99
def __init__(self, data=None, headers=None, **kwargs): ...
100
101
# Properties
102
@property
103
def headers(self): ...
104
@property
105
def data(self): ...
106
@property
107
def row_count(self): ...
108
@property
109
def col_count(self): ...
110
111
# Data manipulation
112
def add_row(self, row_data): ...
113
def add_column(self, header, column_data): ...
114
def extend(self, table_data): ...
115
def sort(self, key=None, reverse=False): ...
116
117
# Output formats
118
def to_html(self, **kwargs): ...
119
def to_text(self, **kwargs): ...
120
def to_csv(self, **kwargs): ...
121
def to_list(self): ...
122
def to_dict(self): ...
123
124
# Iteration
125
def __iter__(self): ...
126
def __getitem__(self, index): ...
127
```
128
129
### Table Input Type Handlers
130
131
Specialized handlers for different table data input formats.
132
133
```python { .api }
134
class InputType:
135
"""Base class for table input type handlers."""
136
def __init__(self, **kwargs): ...
137
def normalize_data(self, data): ...
138
139
class DictInputType(InputType):
140
"""Handler for dictionary-based table data."""
141
def normalize_data(self, data): ...
142
143
class ObjectInputType(InputType):
144
"""Handler for object-based table data."""
145
def normalize_data(self, data): ...
146
147
class ListInputType(InputType):
148
"""Handler for list-based table data."""
149
def normalize_data(self, data): ...
150
151
class TupleInputType(InputType):
152
"""Handler for tuple-based table data."""
153
def normalize_data(self, data): ...
154
155
class NamedTupleInputType(InputType):
156
"""Handler for namedtuple-based table data."""
157
def normalize_data(self, data): ...
158
```
159
160
### Text Conversion Utilities
161
162
Utilities for converting objects to text representations.
163
164
```python { .api }
165
def to_text(obj, maxlen=None):
166
"""
167
Convert object to text representation.
168
169
Parameters:
170
- obj: Object to convert
171
- maxlen (int, optional): Maximum length for text
172
173
Returns:
174
str: Text representation of object
175
"""
176
177
def escape_html(obj, maxlen=None):
178
"""
179
HTML-escape object representation.
180
181
Parameters:
182
- obj: Object to escape
183
- maxlen (int, optional): Maximum length before truncation
184
185
Returns:
186
str: HTML-escaped text representation
187
"""
188
```
189
190
## Usage Examples
191
192
```python
193
from boltons.formatutils import get_format_args, split_format_str
194
from boltons.tableutils import Table, to_text
195
196
# Format string analysis
197
format_str = "Hello {name}, you have {count:d} {item}s!"
198
args = get_format_args(format_str)
199
print(args) # Information about format arguments
200
201
components = split_format_str(format_str)
202
print(components) # Format string broken into components
203
204
# Table creation from various data sources
205
# From list of dictionaries
206
dict_data = [
207
{'name': 'Alice', 'age': 30, 'city': 'New York'},
208
{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
209
{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
210
]
211
212
table = Table(dict_data)
213
print(table.to_text())
214
215
# HTML output
216
html_table = table.to_html(
217
table_class='data-table',
218
border=1,
219
cellpadding=5
220
)
221
print(html_table)
222
223
# From list of lists with headers
224
list_data = [
225
['Alice', 30, 'New York'],
226
['Bob', 25, 'Los Angeles'],
227
['Charlie', 35, 'Chicago']
228
]
229
headers = ['Name', 'Age', 'City']
230
231
table2 = Table(list_data, headers=headers)
232
csv_output = table2.to_csv()
233
print(csv_output)
234
235
# From objects
236
class Person:
237
def __init__(self, name, age, city):
238
self.name = name
239
self.age = age
240
self.city = city
241
242
people = [
243
Person('Alice', 30, 'New York'),
244
Person('Bob', 25, 'Los Angeles'),
245
Person('Charlie', 35, 'Chicago')
246
]
247
248
table3 = Table(people)
249
print(table3.to_text(max_col_width=15))
250
```
251
252
### Advanced Table Operations
253
254
```python
255
from boltons.tableutils import Table
256
257
# Create table and manipulate data
258
sales_data = [
259
{'product': 'Widget', 'quantity': 100, 'price': 10.50},
260
{'product': 'Gadget', 'quantity': 75, 'price': 25.00},
261
{'product': 'Doohickey', 'quantity': 50, 'price': 15.75}
262
]
263
264
table = Table(sales_data)
265
266
# Add calculated column
267
revenue_data = [row['quantity'] * row['price'] for row in sales_data]
268
table.add_column('Revenue', revenue_data)
269
270
# Sort by revenue (descending)
271
table.sort(key=lambda row: row[-1], reverse=True) # Sort by last column (Revenue)
272
273
# Add totals row
274
total_qty = sum(row[1] for row in table.data)
275
total_revenue = sum(row[3] for row in table.data)
276
table.add_row(['TOTAL', total_qty, '', total_revenue])
277
278
# Generate formatted output
279
print("Sales Report:")
280
print("=" * 60)
281
print(table.to_text(max_col_width=12))
282
283
# Custom HTML formatting
284
html_output = table.to_html(
285
table_class='sales-report',
286
table_style='border-collapse: collapse; width: 100%;',
287
th_style='background-color: #f2f2f2; padding: 8px;',
288
td_style='padding: 8px; border-bottom: 1px solid #ddd;'
289
)
290
291
# Export to various formats
292
with open('sales_report.csv', 'w') as f:
293
f.write(table.to_csv())
294
295
# Iterate through table data
296
print("Individual rows:")
297
for i, row in enumerate(table):
298
print(f"Row {i}: {row}")
299
300
# Access specific cells
301
print(f"Product in first row: {table[0][0]}")
302
print(f"Revenue in second row: {table[1][3]}")
303
```
304
305
### Format String Processing
306
307
```python
308
from boltons.formatutils import (
309
tokenize_format_str, infer_positional_format_args,
310
BaseFormatField, DeferredValue
311
)
312
313
# Analyze complex format strings
314
complex_format = "Item: {item.name:>20}, Price: ${item.price:8.2f}, Stock: {stock:d}"
315
316
# Tokenize the format string
317
tokens = tokenize_format_str(complex_format)
318
print("Format tokens:")
319
for token in tokens:
320
print(f" {token}")
321
322
# Infer argument requirements
323
pos_args_needed = infer_positional_format_args("{0} + {1} = {2}")
324
print(f"Positional arguments needed: {pos_args_needed}") # 3
325
326
# Dynamic value formatting with DeferredValue
327
import datetime
328
329
def current_time():
330
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
331
332
deferred_time = DeferredValue(current_time)
333
334
# Format string with deferred evaluation
335
log_format = "Log entry at {timestamp}: {message}"
336
formatted = log_format.format(
337
timestamp=deferred_time.get_value(),
338
message="System started"
339
)
340
print(formatted)
341
```
342
343
## Types
344
345
```python { .api }
346
# Exceptions
347
class UnsupportedData(TypeError):
348
"""Exception for unsupported data types in table processing."""
349
pass
350
351
# Format field components
352
FormatToken = tuple # (literal_text, field_spec) pairs from tokenized format strings
353
```