tracecite-docs 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,427 @@
1
+ """Pandoc-backed parsing for native Markdown tables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shlex
8
+ import shutil
9
+ import subprocess
10
+ from collections.abc import Iterable
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from ._text import collapse_space, strip_caption_id, strip_html
16
+ from .models import TableDiagnostic, TableNormalisationError, expand_spans
17
+
18
+
19
+ @dataclass(slots=True)
20
+ class ParsedPandocTable:
21
+ table_id: str | None
22
+ caption: str | None
23
+ headers: list[str]
24
+ rows: list[list[str]]
25
+ alignments: list[str]
26
+ diagnostics: list[TableDiagnostic]
27
+ attributes: dict[str, str]
28
+
29
+
30
+ def resolve_pandoc(explicit: str | Path | None = None) -> list[str]:
31
+ """Resolve standalone Pandoc or Quarto's bundled Pandoc."""
32
+
33
+ configured = explicit or os.getenv("TRACECITE_PANDOC")
34
+ if configured:
35
+ command = shlex.split(str(configured))
36
+ if command and shutil.which(command[0]):
37
+ return command
38
+ path = Path(str(configured))
39
+ if path.is_file():
40
+ return [str(path)]
41
+ raise FileNotFoundError(
42
+ f"Configured Pandoc command is unavailable: {configured}"
43
+ )
44
+
45
+ quarto = shutil.which("quarto")
46
+ if quarto:
47
+ return [quarto, "pandoc"]
48
+
49
+ pandoc = shutil.which("pandoc")
50
+ if pandoc:
51
+ return [pandoc]
52
+
53
+ raise FileNotFoundError(
54
+ "Pandoc is required for full table normalisation. Install Pandoc or Quarto, "
55
+ "or configure TRACECITE_PANDOC."
56
+ )
57
+
58
+
59
+ def markdown_to_ast(
60
+ markdown: str,
61
+ *,
62
+ pandoc: str | Path | None = None,
63
+ timeout: float = 30.0,
64
+ ) -> dict[str, Any]:
65
+ command = [
66
+ *resolve_pandoc(pandoc),
67
+ "--from=markdown+pipe_tables+grid_tables+multiline_tables+table_captions+raw_html",
68
+ "--to=json",
69
+ ]
70
+ completed = subprocess.run(
71
+ command,
72
+ input=markdown,
73
+ text=True,
74
+ capture_output=True,
75
+ timeout=timeout,
76
+ check=False,
77
+ )
78
+ if completed.returncode != 0:
79
+ message = (
80
+ completed.stderr.strip() or completed.stdout.strip() or "Pandoc failed"
81
+ )
82
+ raise TableNormalisationError(message)
83
+ try:
84
+ return json.loads(completed.stdout)
85
+ except json.JSONDecodeError as error:
86
+ raise TableNormalisationError("Pandoc returned invalid JSON") from error
87
+
88
+
89
+ def parse_pandoc_tables(
90
+ markdown: str,
91
+ *,
92
+ pandoc: str | Path | None = None,
93
+ ) -> list[ParsedPandocTable]:
94
+ ast = markdown_to_ast(markdown, pandoc=pandoc)
95
+ return [
96
+ parse_table_node(node) for node in _walk_nodes(ast) if node.get("t") == "Table"
97
+ ]
98
+
99
+
100
+ def parse_table_node(node: dict[str, Any]) -> ParsedPandocTable:
101
+ try:
102
+ attr, caption_value, colspecs, head, bodies, foot = node["c"]
103
+ except (KeyError, TypeError, ValueError) as error:
104
+ raise TableNormalisationError("Unsupported Pandoc Table AST shape") from error
105
+
106
+ diagnostics: list[TableDiagnostic] = []
107
+ table_id, classes, key_values = _attr(attr)
108
+ attributes = {key: value for key, value in key_values}
109
+ if classes:
110
+ attributes["classes"] = " ".join(classes)
111
+
112
+ caption = _caption_text(caption_value)
113
+ caption, caption_id = strip_caption_id(caption or "")
114
+ if not table_id:
115
+ table_id = caption_id
116
+ caption = caption or None
117
+
118
+ alignments = [_alignment(spec[0]) for spec in colspecs]
119
+ ncols = len(colspecs)
120
+
121
+ header_rows = _rows_from_section(head)
122
+ expanded_headers = _expand_rows(header_rows, ncols, diagnostics, section="header")
123
+ if not ncols:
124
+ ncols = max((len(row) for row in expanded_headers), default=0)
125
+
126
+ body_rows: list[list[Any]] = []
127
+ for body in bodies:
128
+ try:
129
+ _body_attr, row_head_columns, intermediate_heads, rows = body
130
+ except (TypeError, ValueError) as error:
131
+ raise TableNormalisationError(
132
+ "Unsupported Pandoc table body shape"
133
+ ) from error
134
+ if row_head_columns:
135
+ diagnostics.append(
136
+ TableDiagnostic(
137
+ "table.row-head-columns",
138
+ "info",
139
+ f"Pandoc marks {row_head_columns} body column(s) as row headers.",
140
+ )
141
+ )
142
+ if intermediate_heads:
143
+ diagnostics.append(
144
+ TableDiagnostic(
145
+ "table.intermediate-headers",
146
+ "warning",
147
+ "Intermediate body headers were flattened into ordinary rows.",
148
+ )
149
+ )
150
+ body_rows.extend(intermediate_heads)
151
+ body_rows.extend(rows)
152
+
153
+ expanded_rows = _expand_rows(body_rows, ncols, diagnostics, section="body")
154
+ foot_rows = _rows_from_section(foot)
155
+ if foot_rows:
156
+ diagnostics.append(
157
+ TableDiagnostic(
158
+ "table.footer-rows",
159
+ "warning",
160
+ "Footer rows were appended to the normalised body.",
161
+ )
162
+ )
163
+ expanded_rows.extend(
164
+ _expand_rows(foot_rows, ncols, diagnostics, section="footer")
165
+ )
166
+
167
+ headers = _combine_header_rows(expanded_headers, ncols)
168
+ if not headers:
169
+ headers = [f"Column {index}" for index in range(1, ncols + 1)]
170
+ if all(not value for value in headers):
171
+ headers = [f"Column {index}" for index in range(1, ncols + 1)]
172
+ diagnostics.append(
173
+ TableDiagnostic(
174
+ "table.generated-headers",
175
+ "warning",
176
+ "The source table had no usable headers; deterministic column names were generated.",
177
+ )
178
+ )
179
+ else:
180
+ for index, value in enumerate(headers):
181
+ if not value:
182
+ headers[index] = f"Column {index + 1}"
183
+ diagnostics.append(
184
+ TableDiagnostic(
185
+ "table.empty-header",
186
+ "warning",
187
+ f"Header {index + 1} was empty and was replaced by a deterministic name.",
188
+ column=index + 1,
189
+ )
190
+ )
191
+
192
+ if len(alignments) < len(headers):
193
+ alignments.extend(["default"] * (len(headers) - len(alignments)))
194
+
195
+ return ParsedPandocTable(
196
+ table_id=table_id or None,
197
+ caption=caption,
198
+ headers=headers,
199
+ rows=[(row + [""] * len(headers))[: len(headers)] for row in expanded_rows],
200
+ alignments=alignments[: len(headers)],
201
+ diagnostics=diagnostics,
202
+ attributes=attributes,
203
+ )
204
+
205
+
206
+ def ast_tables_with_sections(
207
+ markdown: str,
208
+ *,
209
+ pandoc: str | Path | None = None,
210
+ ) -> list[tuple[tuple[str, ...], ParsedPandocTable]]:
211
+ """Return every Pandoc table with the heading path active at that node."""
212
+
213
+ ast = markdown_to_ast(markdown, pandoc=pandoc)
214
+ headings: list[str] = []
215
+ result: list[tuple[tuple[str, ...], ParsedPandocTable]] = []
216
+
217
+ def visit_blocks(blocks: Iterable[dict[str, Any]]) -> None:
218
+ nonlocal headings
219
+ for block in blocks:
220
+ kind = block.get("t")
221
+ if kind == "Header":
222
+ level, _attr_value, inlines = block["c"]
223
+ title = _inlines_text(inlines)
224
+ headings = headings[: max(0, level - 1)]
225
+ while len(headings) < level - 1:
226
+ headings.append("")
227
+ headings.append(title)
228
+ elif kind == "Table":
229
+ result.append(
230
+ (tuple(item for item in headings if item), parse_table_node(block))
231
+ )
232
+ else:
233
+ for nested in _nested_block_lists(block):
234
+ visit_blocks(nested)
235
+
236
+ visit_blocks(ast.get("blocks", []))
237
+ return result
238
+
239
+
240
+ def _walk_nodes(value: Any) -> Iterable[dict[str, Any]]:
241
+ if isinstance(value, dict):
242
+ yield value
243
+ for item in value.values():
244
+ yield from _walk_nodes(item)
245
+ elif isinstance(value, list):
246
+ for item in value:
247
+ yield from _walk_nodes(item)
248
+
249
+
250
+ def _nested_block_lists(node: dict[str, Any]) -> Iterable[list[dict[str, Any]]]:
251
+ kind = node.get("t")
252
+ value: Any = node.get("c")
253
+ if kind == "Div" and isinstance(value, list) and len(value) == 2:
254
+ yield value[1]
255
+ elif kind in {"BlockQuote"} and isinstance(value, list):
256
+ yield value
257
+ elif kind in {"BulletList", "OrderedList"}:
258
+ items = value if kind == "BulletList" else value[1]
259
+ yield from items
260
+ elif kind == "DefinitionList":
261
+ for _term, definitions in value:
262
+ yield from definitions
263
+
264
+
265
+ def _attr(value: Any) -> tuple[str, list[str], list[tuple[str, str]]]:
266
+ if not isinstance(value, list) or len(value) != 3:
267
+ return "", [], []
268
+ identifier, classes, key_values = value
269
+ return (
270
+ str(identifier),
271
+ [str(item) for item in classes],
272
+ [(str(key), str(item)) for key, item in key_values],
273
+ )
274
+
275
+
276
+ def _caption_text(value: Any) -> str:
277
+ if not isinstance(value, list) or len(value) != 2:
278
+ return ""
279
+ short, blocks = value
280
+ if short:
281
+ return _inlines_text(short)
282
+ return _blocks_text(blocks)
283
+
284
+
285
+ def _rows_from_section(value: Any) -> list[Any]:
286
+ if not isinstance(value, list) or len(value) != 2:
287
+ return []
288
+ return list(value[1])
289
+
290
+
291
+ def _expand_rows(
292
+ rows: list[Any],
293
+ ncols: int,
294
+ diagnostics: list[TableDiagnostic],
295
+ *,
296
+ section: str,
297
+ ) -> list[list[str]]:
298
+ cell_rows = [
299
+ row[1] if isinstance(row, list) and len(row) == 2 else [] for row in rows
300
+ ]
301
+ if not ncols:
302
+ ncols = max(
303
+ (sum(max(1, int(cell[3])) for cell in cells) for cells in cell_rows),
304
+ default=0,
305
+ )
306
+ return expand_spans(
307
+ ([_cell_span(cell) for cell in cells] for cells in cell_rows),
308
+ ncols,
309
+ diagnostics,
310
+ section,
311
+ )
312
+
313
+
314
+ def _cell_span(cell: Any) -> tuple[int, int, str] | None:
315
+ try:
316
+ _attr, _align, rowspan, colspan, blocks = cell
317
+ except (TypeError, ValueError):
318
+ return None
319
+ return max(1, int(rowspan)), max(1, int(colspan)), _blocks_text(blocks)
320
+
321
+
322
+ def _combine_header_rows(rows: list[list[str]], ncols: int) -> list[str]:
323
+ if not rows or not ncols:
324
+ return []
325
+ combined: list[str] = []
326
+ for column in range(ncols):
327
+ values: list[str] = []
328
+ for row in rows:
329
+ value = collapse_space(row[column] if column < len(row) else "")
330
+ if value and value not in values:
331
+ values.append(value)
332
+ combined.append(" / ".join(values))
333
+ return combined
334
+
335
+
336
+ def _alignment(value: Any) -> str:
337
+ if isinstance(value, dict):
338
+ name = value.get("t", "AlignDefault")
339
+ else:
340
+ name = str(value)
341
+ return {
342
+ "AlignLeft": "left",
343
+ "AlignCenter": "center",
344
+ "AlignRight": "right",
345
+ }.get(name, "default")
346
+
347
+
348
+ def _blocks_text(blocks: Any) -> str:
349
+ if not isinstance(blocks, list):
350
+ return ""
351
+ parts: list[str] = []
352
+ for block in blocks:
353
+ if not isinstance(block, dict):
354
+ continue
355
+ kind = block.get("t")
356
+ value: Any = block.get("c")
357
+ if kind in {"Plain", "Para", "Header"}:
358
+ inlines = value if kind != "Header" else value[2]
359
+ parts.append(_inlines_text(inlines))
360
+ elif kind == "CodeBlock":
361
+ parts.append(f"`{value[1]}`")
362
+ elif kind == "RawBlock":
363
+ fmt, raw = value
364
+ parts.append(strip_html(raw) if fmt == "html" else str(raw))
365
+ elif kind == "BlockQuote":
366
+ parts.append(_blocks_text(value))
367
+ elif kind == "BulletList":
368
+ parts.append("; ".join(_blocks_text(item) for item in value))
369
+ elif kind == "OrderedList":
370
+ parts.append("; ".join(_blocks_text(item) for item in value[1]))
371
+ elif kind == "DefinitionList":
372
+ for term, definitions in value:
373
+ definition = "; ".join(_blocks_text(item) for item in definitions)
374
+ parts.append(f"{_inlines_text(term)}: {definition}")
375
+ elif kind == "Div":
376
+ parts.append(_blocks_text(value[1]))
377
+ elif kind == "HorizontalRule":
378
+ parts.append("—")
379
+ return collapse_space(" ".join(item for item in parts if item))
380
+
381
+
382
+ def _inlines_text(inlines: Any) -> str:
383
+ if not isinstance(inlines, list):
384
+ return ""
385
+ parts: list[str] = []
386
+ for inline in inlines:
387
+ if not isinstance(inline, dict):
388
+ continue
389
+ kind = inline.get("t")
390
+ value: Any = inline.get("c")
391
+ if kind == "Str":
392
+ parts.append(str(value))
393
+ elif kind in {"Space", "SoftBreak", "LineBreak"}:
394
+ parts.append(" ")
395
+ elif kind == "Code":
396
+ parts.append(f"`{value[1]}`")
397
+ elif kind == "Math":
398
+ parts.append(f"${value[1]}$")
399
+ elif kind in {
400
+ "Emph",
401
+ "Strong",
402
+ "Strikeout",
403
+ "Superscript",
404
+ "Subscript",
405
+ "SmallCaps",
406
+ "Underline",
407
+ }:
408
+ parts.append(_inlines_text(value))
409
+ elif kind == "Quoted":
410
+ parts.append(_inlines_text(value[1]))
411
+ elif kind in {"Span", "Cite"}:
412
+ nested = value[1]
413
+ parts.append(_inlines_text(nested))
414
+ elif kind == "Link":
415
+ label = _inlines_text(value[1])
416
+ target = value[2][0]
417
+ parts.append(f"{label} ({target})" if target else label)
418
+ elif kind == "Image":
419
+ label = _inlines_text(value[1]) or "image"
420
+ target = value[2][0]
421
+ parts.append(f"{label} ({target})" if target else label)
422
+ elif kind == "RawInline":
423
+ fmt, raw = value
424
+ parts.append(strip_html(raw) if fmt == "html" else str(raw))
425
+ elif kind == "Note":
426
+ parts.append(_blocks_text(value))
427
+ return collapse_space("".join(parts))
@@ -0,0 +1,248 @@
1
+ """Optional DataFrame helper for emitting safe Pandoc pipe tables.
2
+
3
+ The caller supplies the pandas DataFrame, so pandas is imported only when a
4
+ helper runs.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from collections.abc import Callable, Mapping, Sequence
12
+ from datetime import date, datetime
13
+ from html import escape as html_escape
14
+ from typing import TYPE_CHECKING, Any
15
+
16
+ from tabulate import tabulate
17
+
18
+ if TYPE_CHECKING:
19
+ import pandas as pd
20
+
21
+ Formatter = str | Callable[[Any], str]
22
+ _TABLE_ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.:-]*$")
23
+
24
+
25
+ def knowledge_table(
26
+ table: pd.DataFrame,
27
+ *,
28
+ table_id: str,
29
+ caption: str | None = None,
30
+ columns: Sequence[str] | None = None,
31
+ labels: Mapping[str, str] | None = None,
32
+ formats: Mapping[str, Formatter] | None = None,
33
+ units: Mapping[str, str] | None = None,
34
+ ordering: str | None = None,
35
+ row_identity: Sequence[str] | None = None,
36
+ description: str | None = None,
37
+ summary: bool | Sequence[str] = False,
38
+ ) -> str:
39
+ """Return one Pandoc table with optional semantic metadata."""
40
+
41
+ if not _TABLE_ID_RE.fullmatch(table_id):
42
+ raise ValueError(
43
+ "table_id must start with a letter and contain only letters, digits, "
44
+ "underscore, dot, colon, or hyphen"
45
+ )
46
+
47
+ labels = dict(labels or {})
48
+ formats = dict(formats or {})
49
+ units = dict(units or {})
50
+ selected = list(columns or table.columns)
51
+ _require_columns(table, selected)
52
+ _require_known_keys("labels", labels, selected)
53
+ _require_known_keys("formats", formats, selected)
54
+ _require_known_keys("units", units, selected)
55
+
56
+ identity = list(row_identity or [])
57
+ _require_columns(table, identity)
58
+ display_headers = [labels.get(column, _humanise(column)) for column in selected]
59
+ if len(set(display_headers)) != len(display_headers):
60
+ raise ValueError("Displayed column labels must be unique")
61
+
62
+ rows = [
63
+ [
64
+ _escape_cell(_format_value(value, formats.get(column)))
65
+ for column, value in zip(selected, row, strict=True)
66
+ ]
67
+ for row in table.loc[:, selected].itertuples(index=False, name=None)
68
+ ]
69
+ import pandas as pd
70
+
71
+ alignments = tuple(
72
+ "right" if pd.api.types.is_numeric_dtype(table[column]) else "left"
73
+ for column in selected
74
+ )
75
+
76
+ metadata = table_metadata_comment(
77
+ table_id=table_id if caption is None else None,
78
+ description=description,
79
+ ordering=ordering,
80
+ units={
81
+ labels.get(column, _humanise(column)): unit
82
+ for column, unit in units.items()
83
+ },
84
+ row_identity=[labels.get(column, _humanise(column)) for column in identity],
85
+ )
86
+ parts: list[str] = []
87
+ if metadata:
88
+ parts.extend([metadata, ""])
89
+ parts.extend(
90
+ [
91
+ tabulate(
92
+ rows,
93
+ headers=[_escape_cell(header) for header in display_headers],
94
+ tablefmt="pipe",
95
+ disable_numparse=True,
96
+ colalign=alignments,
97
+ ),
98
+ "",
99
+ ]
100
+ )
101
+ if caption is not None:
102
+ parts.append(f": {caption} {{#{table_id}}}")
103
+
104
+ if summary is not False:
105
+ summary_columns = selected if summary is True else list(summary)
106
+ _require_columns(table, summary_columns)
107
+ parts.extend(
108
+ [
109
+ "",
110
+ computed_first_row_summary(
111
+ table,
112
+ columns=summary_columns,
113
+ labels=labels,
114
+ units=units,
115
+ formats=formats,
116
+ ),
117
+ ]
118
+ )
119
+ return "\n".join(parts)
120
+
121
+
122
+ def table_metadata_comment(
123
+ *,
124
+ table_id: str | None = None,
125
+ description: str | None = None,
126
+ ordering: str | None = None,
127
+ labels: Mapping[str, str] | None = None,
128
+ units: Mapping[str, str] | None = None,
129
+ row_identity: Sequence[str] | None = None,
130
+ ) -> str:
131
+ payload = {
132
+ key: value
133
+ for key, value in {
134
+ "table_id": table_id,
135
+ "description": description,
136
+ "ordering": ordering,
137
+ "labels": dict(labels or {}),
138
+ "units": dict(units or {}),
139
+ "row_identity": list(row_identity or []),
140
+ }.items()
141
+ if value
142
+ }
143
+ if not payload:
144
+ return ""
145
+ return f"<!-- tracecite-table: {json.dumps(payload, ensure_ascii=False, sort_keys=True)} -->"
146
+
147
+
148
+ def computed_first_row_summary(
149
+ table: pd.DataFrame,
150
+ *,
151
+ columns: Sequence[str] | None = None,
152
+ labels: Mapping[str, str] | None = None,
153
+ units: Mapping[str, str] | None = None,
154
+ formats: Mapping[str, Formatter] | None = None,
155
+ prefix: str = "First-row finding",
156
+ ) -> str:
157
+ """Describe the first row using only values computed in ``table``."""
158
+
159
+ labels = dict(labels or {})
160
+ units = dict(units or {})
161
+ formats = dict(formats or {})
162
+ selected = list(table.columns if columns is None else columns)
163
+ _require_columns(table, selected)
164
+ if not selected:
165
+ return f"**{prefix}.** No fields were selected."
166
+ if table.empty:
167
+ return f"**{prefix}.** The table contains no rows."
168
+
169
+ row = table.iloc[0]
170
+ fields: list[tuple[str, str]] = []
171
+ for column in selected:
172
+ label = labels.get(column, _humanise(column))
173
+ value = _format_value(row[column], formats.get(column))
174
+ if column in units and value != "not available":
175
+ value = f"{value} {units[column]}"
176
+ fields.append((label, _escape_inline(value)))
177
+ if len(fields) == 1:
178
+ label, value = fields[0]
179
+ return f"**{prefix}.** {label[:1].upper() + label[1:]} is **{value}**."
180
+ subject = fields[0][1]
181
+ predicates = [
182
+ f"{label[:1].lower() + label[1:]} is **{value}**" for label, value in fields[1:]
183
+ ]
184
+ return f"**{prefix}.** For **{subject}**, {_join(predicates)}."
185
+
186
+
187
+ def _format_value(value: Any, formatter: Formatter | None = None) -> str:
188
+ import pandas as pd
189
+
190
+ if pd.api.types.is_scalar(value) and pd.isna(value):
191
+ return "not available"
192
+ if formatter is not None:
193
+ return str(
194
+ formatter(value) if callable(formatter) else format(value, formatter)
195
+ )
196
+ if isinstance(value, pd.Timestamp):
197
+ return (
198
+ value.date().isoformat()
199
+ if value == value.normalize()
200
+ else value.isoformat()
201
+ )
202
+ if isinstance(value, (datetime, date)):
203
+ return value.isoformat()
204
+ if isinstance(value, float):
205
+ return f"{value:g}"
206
+ return str(value)
207
+
208
+
209
+ def _escape_cell(value: str) -> str:
210
+ text = html_escape(str(value), quote=False)
211
+ for character in ("\\", "|", "$", "*", "_", "~", "`", "[", "]"):
212
+ text = text.replace(character, f"\\{character}")
213
+ return text
214
+
215
+
216
+ def _escape_inline(value: str) -> str:
217
+ text = str(value)
218
+ for character in ("\\", "$", "*", "_", "~", "`", "[", "]", "<", ">"):
219
+ text = text.replace(character, f"\\{character}")
220
+ return text
221
+
222
+
223
+ def _humanise(name: str) -> str:
224
+ return str(name).replace("_", " ").strip()
225
+
226
+
227
+ def _require_columns(table: pd.DataFrame, columns: Sequence[str]) -> None:
228
+ unknown = [column for column in columns if column not in table.columns]
229
+ if unknown:
230
+ raise KeyError(f"Columns are not present in the DataFrame: {unknown}")
231
+
232
+
233
+ def _require_known_keys(
234
+ name: str, values: Mapping[str, Any], columns: Sequence[str]
235
+ ) -> None:
236
+ unknown = [column for column in values if column not in columns]
237
+ if unknown:
238
+ raise KeyError(f"{name} contains columns not selected for display: {unknown}")
239
+
240
+
241
+ def _join(fields: Sequence[str]) -> str:
242
+ if not fields:
243
+ return "no selected fields"
244
+ if len(fields) == 1:
245
+ return fields[0]
246
+ if len(fields) == 2:
247
+ return f"{fields[0]} and {fields[1]}"
248
+ return ", ".join(fields[:-1]) + f", and {fields[-1]}"