0
# Factory Functions
1
2
Utilities for creating PrettyTable instances from various data sources including CSV files, JSON data, HTML tables, database cursors, and MediaWiki markup. These functions simplify table creation from existing structured data.
3
4
## Capabilities
5
6
### CSV Import
7
8
Create tables from CSV files or file-like objects with configurable field names and parsing options.
9
10
```python { .api }
11
def from_csv(fp, field_names: Sequence[str] | None = None, **kwargs) -> PrettyTable:
12
"""
13
Create PrettyTable from CSV file or file-like object.
14
15
Parameters:
16
- fp: File path, file object, or file-like object containing CSV data
17
- field_names: Sequence of field names (uses first row if None)
18
- **kwargs: Additional PrettyTable constructor arguments
19
20
Returns:
21
PrettyTable instance with CSV data loaded
22
"""
23
```
24
25
Usage examples:
26
27
```python
28
from prettytable import from_csv
29
30
# From file path
31
table = from_csv("data.csv")
32
33
# From file object
34
with open("data.csv", "r") as f:
35
table = from_csv(f)
36
37
# With custom field names
38
table = from_csv("data.csv", field_names=["Name", "Age", "City"])
39
40
# With formatting options
41
table = from_csv("data.csv", padding_width=2, align="l")
42
43
# From StringIO
44
import io
45
csv_data = "Name,Age\nAlice,25\nBob,30"
46
table = from_csv(io.StringIO(csv_data))
47
```
48
49
### JSON Import
50
51
Create tables from JSON strings with support for various JSON structures.
52
53
```python { .api }
54
def from_json(json_string: str | bytes, **kwargs) -> PrettyTable:
55
"""
56
Create PrettyTable from JSON string.
57
58
Parameters:
59
- json_string: JSON formatted string or bytes containing table data
60
- **kwargs: Additional PrettyTable constructor arguments
61
62
Returns:
63
PrettyTable instance with JSON data loaded
64
"""
65
```
66
67
Usage examples:
68
69
```python
70
from prettytable import from_json
71
72
# From JSON array of objects
73
json_data = '''[
74
{"Name": "Alice", "Age": 25, "City": "New York"},
75
{"Name": "Bob", "Age": 30, "City": "Boston"}
76
]'''
77
table = from_json(json_data)
78
79
# With formatting options
80
table = from_json(json_data, align="l", padding_width=3)
81
```
82
83
### HTML Import
84
85
Extract tables from HTML markup with support for multiple tables per document.
86
87
```python { .api }
88
def from_html(html_code: str, **kwargs) -> list[PrettyTable]:
89
"""
90
Create list of PrettyTables from HTML containing multiple tables.
91
92
Parameters:
93
- html_code: HTML string containing table elements
94
- **kwargs: Additional PrettyTable constructor arguments
95
96
Returns:
97
List of PrettyTable instances, one for each HTML table found
98
"""
99
100
def from_html_one(html_code: str, **kwargs) -> PrettyTable:
101
"""
102
Create single PrettyTable from HTML containing one table.
103
104
Parameters:
105
- html_code: HTML string containing exactly one table element
106
- **kwargs: Additional PrettyTable constructor arguments
107
108
Returns:
109
PrettyTable instance with HTML table data loaded
110
111
Raises:
112
Exception if HTML contains no tables or multiple tables
113
"""
114
```
115
116
Usage examples:
117
118
```python
119
from prettytable import from_html, from_html_one
120
121
# HTML with multiple tables
122
html_multi = '''
123
<table>
124
<tr><th>Name</th><th>Age</th></tr>
125
<tr><td>Alice</td><td>25</td></tr>
126
</table>
127
<table>
128
<tr><th>Product</th><th>Price</th></tr>
129
<tr><td>Widget</td><td>$10</td></tr>
130
</table>
131
'''
132
tables = from_html(html_multi) # Returns list of 2 tables
133
134
# HTML with single table
135
html_single = '''
136
<table>
137
<tr><th>Name</th><th>Score</th></tr>
138
<tr><td>Alice</td><td>95</td></tr>
139
<tr><td>Bob</td><td>87</td></tr>
140
</table>
141
'''
142
table = from_html_one(html_single) # Returns single table
143
144
# With formatting options
145
table = from_html_one(html_single, align="c", border=True)
146
```
147
148
### Database Cursor Import
149
150
Create tables directly from database query results using cursor objects.
151
152
```python { .api }
153
def from_db_cursor(cursor, **kwargs) -> PrettyTable | None:
154
"""
155
Create PrettyTable from database cursor.
156
157
Parameters:
158
- cursor: Database cursor object (sqlite3.Cursor or compatible)
159
- **kwargs: Additional PrettyTable constructor arguments
160
161
Returns:
162
PrettyTable instance with query results, or None if cursor is empty
163
"""
164
```
165
166
Usage examples:
167
168
```python
169
from prettytable import from_db_cursor
170
import sqlite3
171
172
# From SQLite cursor
173
conn = sqlite3.connect("database.db")
174
cursor = conn.cursor()
175
cursor.execute("SELECT name, age, city FROM users")
176
table = from_db_cursor(cursor)
177
178
# With formatting options
179
cursor.execute("SELECT * FROM products")
180
table = from_db_cursor(cursor, align="l", padding_width=2)
181
182
# Handle empty results
183
cursor.execute("SELECT * FROM empty_table")
184
table = from_db_cursor(cursor) # Returns None if no results
185
186
conn.close()
187
```
188
189
### MediaWiki Import
190
191
Parse MediaWiki table markup to create formatted tables.
192
193
```python { .api }
194
def from_mediawiki(wiki_text: str, **kwargs) -> PrettyTable:
195
"""
196
Create PrettyTable from MediaWiki table markup.
197
198
Parameters:
199
- wiki_text: MediaWiki formatted table markup string
200
- **kwargs: Additional PrettyTable constructor arguments
201
202
Returns:
203
PrettyTable instance with MediaWiki table data loaded
204
"""
205
```
206
207
Usage examples:
208
209
```python
210
from prettytable import from_mediawiki
211
212
# MediaWiki table markup
213
wiki_markup = '''
214
{| class="wikitable"
215
|-
216
! Name !! Age !! City
217
|-
218
| Alice || 25 || New York
219
|-
220
| Bob || 30 || Boston
221
|}
222
'''
223
table = from_mediawiki(wiki_markup)
224
225
# With formatting options
226
table = from_mediawiki(wiki_markup, align="c", border=True)
227
```
228
229
### HTML Table Handler
230
231
Internal HTML parser class used by HTML import functions, available for advanced use cases.
232
233
```python { .api }
234
class TableHandler(HTMLParser):
235
"""HTML parser for converting HTML tables to PrettyTable objects."""
236
237
def __init__(self, **kwargs):
238
"""
239
Initialize HTML parser.
240
241
Parameters:
242
- **kwargs: PrettyTable constructor arguments
243
"""
244
245
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
246
"""Handle HTML start tags."""
247
248
def handle_endtag(self, tag: str) -> None:
249
"""Handle HTML end tags."""
250
251
def handle_data(self, data: str) -> None:
252
"""Handle HTML text data."""
253
254
def generate_table(self, rows: list[list[str]]) -> PrettyTable:
255
"""
256
Generate PrettyTable from parsed data.
257
258
Parameters:
259
- rows: List of row data from HTML parsing
260
261
Returns:
262
PrettyTable instance
263
"""
264
265
def make_fields_unique(self, fields: list[str]) -> list[str]:
266
"""
267
Ensure field names are unique.
268
269
Parameters:
270
- fields: List of field names
271
272
Returns:
273
List of unique field names
274
"""
275
```
276
277
Usage example:
278
279
```python
280
from prettytable import TableHandler
281
282
# Advanced HTML parsing
283
handler = TableHandler(align="l", padding_width=2)
284
handler.feed(html_string)
285
# Use handler methods for custom parsing logic
286
```
287
288
## Error Handling
289
290
Factory functions handle various error conditions gracefully:
291
292
- **File not found**: `from_csv()` raises appropriate file system exceptions
293
- **Invalid JSON**: `from_json()` raises JSON parsing exceptions
294
- **Malformed HTML**: HTML functions skip malformed tables or raise parsing exceptions
295
- **Database errors**: `from_db_cursor()` may raise database-specific exceptions
296
- **Empty data**: Most functions create empty tables or return None for `from_db_cursor()`
297
298
Example error handling:
299
300
```python
301
try:
302
table = from_csv("nonexistent.csv")
303
except FileNotFoundError:
304
print("CSV file not found")
305
306
try:
307
table = from_json("invalid json")
308
except json.JSONDecodeError:
309
print("Invalid JSON format")
310
311
# Database cursor may return None
312
table = from_db_cursor(cursor)
313
if table is None:
314
print("No data returned from query")
315
```