flexablelib 2.0.15__tar.gz → 2.0.16__tar.gz

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.
Files changed (47) hide show
  1. {flexablelib-2.0.15 → flexablelib-2.0.16}/CHANGELOG.md +25 -0
  2. {flexablelib-2.0.15/flexablelib.egg-info → flexablelib-2.0.16}/PKG-INFO +1 -1
  3. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/readers.py +44 -3
  4. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/table.py +455 -21
  5. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/utils.py +26 -0
  6. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/writers.py +16 -2
  7. {flexablelib-2.0.15 → flexablelib-2.0.16/flexablelib.egg-info}/PKG-INFO +1 -1
  8. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib.egg-info/SOURCES.txt +1 -0
  9. {flexablelib-2.0.15 → flexablelib-2.0.16}/package.json +1 -1
  10. flexablelib-2.0.16/tests/test_v216_features.py +155 -0
  11. {flexablelib-2.0.15 → flexablelib-2.0.16}/LICENSE +0 -0
  12. {flexablelib-2.0.15 → flexablelib-2.0.16}/MANIFEST.in +0 -0
  13. {flexablelib-2.0.15 → flexablelib-2.0.16}/README.md +0 -0
  14. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/__init__.py +0 -0
  15. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/_speedups.c +0 -0
  16. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/_width_tables.h +0 -0
  17. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/cells.py +0 -0
  18. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/colors.py +0 -0
  19. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/columns.py +0 -0
  20. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/fast.py +0 -0
  21. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/merges.py +0 -0
  22. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/options.py +0 -0
  23. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/style_compositions.py +0 -0
  24. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/table_strings.py +0 -0
  25. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib/text_width.py +0 -0
  26. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib.egg-info/dependency_links.txt +0 -0
  27. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib.egg-info/requires.txt +0 -0
  28. {flexablelib-2.0.15 → flexablelib-2.0.16}/flexablelib.egg-info/top_level.txt +0 -0
  29. {flexablelib-2.0.15 → flexablelib-2.0.16}/setup.cfg +0 -0
  30. {flexablelib-2.0.15 → flexablelib-2.0.16}/setup.py +0 -0
  31. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_cells.py +0 -0
  32. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_columns.py +0 -0
  33. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_excel.py +0 -0
  34. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_features.py +0 -0
  35. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_issues.py +0 -0
  36. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_merge_edge_matrix.py +0 -0
  37. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_merges.py +0 -0
  38. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_readme_examples.py +0 -0
  39. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_styles.py +0 -0
  40. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_text_width.py +0 -0
  41. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_two_pass_measurement.py +0 -0
  42. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_upstream_issues.py +0 -0
  43. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_v213_features.py +0 -0
  44. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_v214_features.py +0 -0
  45. {flexablelib-2.0.15 → flexablelib-2.0.16}/tests/test_v215_features.py +0 -0
  46. {flexablelib-2.0.15 → flexablelib-2.0.16}/tools/benchmark.py +0 -0
  47. {flexablelib-2.0.15 → flexablelib-2.0.16}/tools/generate_width_tables.py +0 -0
@@ -2,6 +2,31 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [2.0.16] - 2026-10-28
6
+
7
+ ### Added
8
+ - ``Table.index_title``: rename the ``show_index`` column header (default ``i``).
9
+ - ``Table.roman_index``: render index values as Roman numerals.
10
+ - ``Table.number_columns``: display data headers as ``1``, ``2``, … (stored names kept).
11
+ - ``Table.strip_cells``: strip whitespace from string cells on display.
12
+ - ``Table.hrules`` / ``Table.vrules``: PrettyTable-style rule toggles
13
+ (``all`` / ``frame`` / ``header`` / ``none`` for hrules; ``all`` / ``frame`` /
14
+ ``none`` for vrules).
15
+ - ``Table.add_dividers(*indexes)`` and ``Table.divide_every(n, start=0)``.
16
+ - ``Table.fit_terminal(margin=0)``: pin ``max_width`` to the live terminal.
17
+ - Aliases ``max_table_width`` (``max_width``) and ``justify`` (``table_align``).
18
+ - ``Table.suppress_empty``: hide empty rows and columns together.
19
+ - CSV dialect extras on ``from_csv`` / ``to_csv``: ``dialect``, ``quoting``,
20
+ ``quotechar``, ``escapechar``, ``doublequote``, ``lineterminator``,
21
+ ``skipinitialspace``, ``strict``.
22
+ - Themes: ``solarized``, ``neon``, ``mono``, ``autumn``, ``contrast``,
23
+ ``forest``, ``ember``, ``slate``.
24
+ - ``paginate(..., freeze_header=True, page_label=False)``: opt-out of repeating
25
+ headers after page 1; optional ``page k/n`` title labels.
26
+
27
+ ### Notes
28
+ - ``from_html`` was already present (2.0.x); no API change this release.
29
+
5
30
  ## [2.0.15] - 2026-10-28
6
31
 
7
32
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flexablelib
3
- Version: 2.0.15
3
+ Version: 2.0.16
4
4
  Summary: Flexible console and HTML tables for Python
5
5
  Home-page: https://github.com/Opus-Perpetuus/flexablelib
6
6
  Download-URL:
@@ -132,20 +132,61 @@ def from_dicts(table_class, records: Iterable[Dict[str, Any]],
132
132
  return _new_table(table_class, headers, rows, parse_numbers, **options)
133
133
 
134
134
 
135
+ def _csv_reader_kwargs(delimiter=',', dialect=None, quoting=None,
136
+ quotechar=None, escapechar=None, doublequote=None,
137
+ lineterminator=None, skipinitialspace=None,
138
+ strict=None):
139
+ """Build kwargs for ``csv.reader`` / ``csv.writer`` from optional extras."""
140
+ kwargs = {}
141
+ if dialect is not None:
142
+ kwargs['dialect'] = dialect
143
+ else:
144
+ kwargs['delimiter'] = delimiter
145
+ for key, value in (
146
+ ('quoting', quoting),
147
+ ('quotechar', quotechar),
148
+ ('escapechar', escapechar),
149
+ ('doublequote', doublequote),
150
+ ('lineterminator', lineterminator),
151
+ ('skipinitialspace', skipinitialspace),
152
+ ('strict', strict),
153
+ ):
154
+ if value is not None:
155
+ kwargs[key] = value
156
+ # dialect already carries delimiter; still allow override when both given
157
+ if dialect is not None and delimiter is not None and delimiter != ',':
158
+ kwargs['delimiter'] = delimiter
159
+ return kwargs
160
+
161
+
135
162
  def from_csv(table_class, source, parse_numbers: bool = True,
136
163
  has_header: bool = True, delimiter: str = ',',
137
- encoding: str = 'utf-8', **options):
164
+ encoding: str = 'utf-8', dialect=None, quoting=None,
165
+ quotechar=None, escapechar=None, doublequote=None,
166
+ lineterminator=None, skipinitialspace=None, strict=None,
167
+ **options):
138
168
  """
139
169
  Build from a CSV file path, or any open text handle.
140
170
 
141
171
  With ``has_header`` false, columns are named automatically.
172
+
173
+ Extra ``csv`` dialect knobs (``quoting``, ``quotechar``, ``escapechar``,
174
+ ``doublequote``, ``lineterminator``, ``skipinitialspace``, ``strict``,
175
+ and a registered ``dialect`` name or Dialect instance) are forwarded to
176
+ ``csv.reader``.
142
177
  """
178
+ reader_kwargs = _csv_reader_kwargs(
179
+ delimiter=delimiter, dialect=dialect, quoting=quoting,
180
+ quotechar=quotechar, escapechar=escapechar,
181
+ doublequote=doublequote, lineterminator=lineterminator,
182
+ skipinitialspace=skipinitialspace, strict=strict,
183
+ )
143
184
  if hasattr(source, 'read'):
144
- reader = _csv.reader(source, delimiter=delimiter)
185
+ reader = _csv.reader(source, **reader_kwargs)
145
186
  rows = [row for row in reader]
146
187
  else:
147
188
  with open(source, 'r', newline='', encoding=encoding) as handle:
148
- rows = [row for row in _csv.reader(handle, delimiter=delimiter)]
189
+ rows = [row for row in _csv.reader(handle, **reader_kwargs)]
149
190
 
150
191
  if not rows:
151
192
  return table_class(**options)
@@ -39,7 +39,8 @@ from .utils import (
39
39
  is_empty_cell,
40
40
  ValuePlacer,
41
41
  IndexCounter,
42
- IndexColumnTitle
42
+ IndexColumnTitle,
43
+ to_roman,
43
44
  )
44
45
  from .options import (
45
46
  NONE_VALUE_REPLACEMENT,
@@ -50,7 +51,8 @@ from .options import (
50
51
  COLUMN_ALIGNS,
51
52
  ALIGNMENT_CODES,
52
53
  MIN_COLUMN_SIZE,
53
- CELL_MARGIN
54
+ CELL_MARGIN,
55
+ INVISIBLE_SEPARATOR,
54
56
  )
55
57
  from .cells import (
56
58
  _wrap_rows,
@@ -785,6 +787,15 @@ class Table(object):
785
787
  self.__i_start = 0
786
788
  self.__i_step = 1
787
789
  self.__index_counter = IndexCounter()
790
+ # Display-only: number data columns 1..n instead of header names.
791
+ self.__number_columns = False
792
+ # Strip leading/trailing whitespace from displayed cell strings.
793
+ self.__strip_cells = False
794
+ # PrettyTable-style rule toggles: None keeps the style as authored.
795
+ # Values: 'all' | 'frame' | 'header' | 'none' (hrules);
796
+ # 'all' | 'frame' | 'none' (vrules).
797
+ self.__hrules = None
798
+ self.__vrules = None
788
799
  self.__parse_numbers = True
789
800
  self.__parse_str_numbers = False
790
801
  self.__auto_wrap_table = False
@@ -1578,6 +1589,75 @@ class Table(object):
1578
1589
  Amount between each index number.
1579
1590
  """
1580
1591
  return self.__i_step
1592
+
1593
+ @property
1594
+ def index_title(self):
1595
+ """
1596
+ Header label for the index column when ``show_index`` is True.
1597
+
1598
+ Default is ``'i'``. Changing it rebinds the internal index key so
1599
+ existing rows keep their index cells.
1600
+ """
1601
+ return str(self.__index_title)
1602
+
1603
+ @property
1604
+ def roman_index(self):
1605
+ """
1606
+ When True with ``show_index``, index values render as Roman numerals.
1607
+ """
1608
+ return self.__roman_index
1609
+
1610
+ @property
1611
+ def number_columns(self):
1612
+ """
1613
+ When True, data column headers display as ``1``, ``2``, … (1-based).
1614
+
1615
+ Stored header names are unchanged; only the composed table uses
1616
+ numbers. The index column (if shown) keeps ``index_title``.
1617
+ """
1618
+ return self.__number_columns
1619
+
1620
+ @property
1621
+ def strip_cells(self):
1622
+ """
1623
+ When True, strip leading/trailing whitespace from string cells on
1624
+ display (storage untouched).
1625
+ """
1626
+ return self.__strip_cells
1627
+
1628
+ @property
1629
+ def hrules(self):
1630
+ """
1631
+ Horizontal rule mode: ``None``/``'all'`` (style default), ``'frame'``
1632
+ (top/bottom only), ``'header'`` (no body separators), or ``'none'``.
1633
+ """
1634
+ return self.__hrules
1635
+
1636
+ @property
1637
+ def vrules(self):
1638
+ """
1639
+ Vertical rule mode: ``None``/``'all'`` (style default), ``'frame'``
1640
+ (outer edges only), or ``'none'``.
1641
+ """
1642
+ return self.__vrules
1643
+
1644
+ @property
1645
+ def max_table_width(self):
1646
+ """Alias of :attr:`max_width` (PrettyTable / comfy-table naming)."""
1647
+ return self.max_width
1648
+
1649
+ @property
1650
+ def justify(self):
1651
+ """Alias of :attr:`table_align` (whole-table left/center/right)."""
1652
+ return self.table_align
1653
+
1654
+ @property
1655
+ def suppress_empty(self):
1656
+ """
1657
+ When True, hide both empty rows and empty columns
1658
+ (``show_empty_rows`` / ``show_empty_columns`` become False).
1659
+ """
1660
+ return (not self.__show_empty_rows) and (not self.__show_empty_columns)
1581
1661
 
1582
1662
  @property
1583
1663
  def auto_wrap(self):
@@ -1940,6 +2020,38 @@ class Table(object):
1940
2020
  raise ValueError('after_row must be >= 0')
1941
2021
  self.__dividers.add(after_row)
1942
2022
 
2023
+ def add_dividers(self, *indexes):
2024
+ """
2025
+ Place several horizontal rules at once.
2026
+
2027
+ Each argument is a 0-based ``after_row`` index (same as
2028
+ :meth:`add_divider`). A single iterable argument is also accepted.
2029
+ """
2030
+ if len(indexes) == 1 and not isinstance(indexes[0], (int, bool)):
2031
+ try:
2032
+ indexes = tuple(indexes[0])
2033
+ except TypeError:
2034
+ pass
2035
+ for index in indexes:
2036
+ self.add_divider(index)
2037
+
2038
+ def divide_every(self, n, start=0):
2039
+ """
2040
+ Insert a divider after every ``n`` body rows, starting at ``start``.
2041
+
2042
+ Example: ``divide_every(3)`` rules after rows 2, 5, 8, …
2043
+ """
2044
+ n = int(n)
2045
+ start = int(start)
2046
+ if n < 1:
2047
+ raise ValueError('n must be >= 1')
2048
+ if start < 0:
2049
+ raise ValueError('start must be >= 0')
2050
+ # First divider after row (start + n - 1).
2051
+ first = start + n - 1
2052
+ for after in range(first, self.__real_row_count, n):
2053
+ self.__dividers.add(after)
2054
+
1943
2055
  def clear_dividers(self):
1944
2056
  """Remove every divider placed with :meth:`add_divider`."""
1945
2057
  self.__dividers.clear()
@@ -1961,6 +2073,110 @@ class Table(object):
1961
2073
  self.__i_step = int(value)
1962
2074
  except ValueError:
1963
2075
  self.__i_step = 1
2076
+
2077
+ @index_title.setter
2078
+ def index_title(self, value):
2079
+ label = I_COL_TIT if value is None else str(value)
2080
+ new_title = IndexColumnTitle(label)
2081
+ old_title = self.__index_title
2082
+ if new_title is old_title:
2083
+ return
2084
+ for mapping in (
2085
+ self.__columns_with_i,
2086
+ self.__cell_types_with_i,
2087
+ self.__column_types_with_i,
2088
+ self.__column_alignments_with_i,
2089
+ self.__column_widths_with_i,
2090
+ self.__float_columns_widths_with_i,
2091
+ self.__processed_columns_with_i,
2092
+ self.__semi_processed_columns_with_i,
2093
+ ):
2094
+ if old_title in mapping:
2095
+ mapping[new_title] = mapping.pop(old_title)
2096
+ if self.__headers_with_i and self.__headers_with_i[0] is old_title:
2097
+ self.__headers_with_i[0] = new_title
2098
+ self.__index_title = new_title
2099
+
2100
+ @roman_index.setter
2101
+ def roman_index(self, value: bool):
2102
+ self.__roman_index = bool(value)
2103
+
2104
+ @number_columns.setter
2105
+ def number_columns(self, value: bool):
2106
+ self.__number_columns = bool(value)
2107
+
2108
+ @strip_cells.setter
2109
+ def strip_cells(self, value: bool):
2110
+ self.__strip_cells = bool(value)
2111
+
2112
+ @hrules.setter
2113
+ def hrules(self, value):
2114
+ if value is None or value is False:
2115
+ self.__hrules = None
2116
+ return
2117
+ if value is True:
2118
+ self.__hrules = 'all'
2119
+ return
2120
+ mode = str(value).lower()
2121
+ aliases = {
2122
+ 'all': 'all', 'a': 'all',
2123
+ 'frame': 'frame', 'f': 'frame',
2124
+ 'header': 'header', 'h': 'header',
2125
+ 'none': 'none', 'n': 'none', 'off': 'none',
2126
+ }
2127
+ if mode not in aliases:
2128
+ raise ValueError(
2129
+ "hrules must be 'all', 'frame', 'header', or 'none', got {0!r}"
2130
+ .format(value)
2131
+ )
2132
+ self.__hrules = aliases[mode]
2133
+
2134
+ @vrules.setter
2135
+ def vrules(self, value):
2136
+ if value is None or value is False:
2137
+ self.__vrules = None
2138
+ return
2139
+ if value is True:
2140
+ self.__vrules = 'all'
2141
+ return
2142
+ mode = str(value).lower()
2143
+ aliases = {
2144
+ 'all': 'all', 'a': 'all',
2145
+ 'frame': 'frame', 'f': 'frame',
2146
+ 'none': 'none', 'n': 'none', 'off': 'none',
2147
+ }
2148
+ if mode not in aliases:
2149
+ raise ValueError(
2150
+ "vrules must be 'all', 'frame', or 'none', got {0!r}"
2151
+ .format(value)
2152
+ )
2153
+ self.__vrules = aliases[mode]
2154
+
2155
+ @max_table_width.setter
2156
+ def max_table_width(self, value):
2157
+ self.max_width = value
2158
+
2159
+ @justify.setter
2160
+ def justify(self, value):
2161
+ self.table_align = value
2162
+
2163
+ @suppress_empty.setter
2164
+ def suppress_empty(self, value):
2165
+ show = not bool(value)
2166
+ self.__show_empty_rows = show
2167
+ self.__show_empty_columns = show
2168
+
2169
+ def fit_terminal(self, margin=0):
2170
+ """
2171
+ Set ``max_width`` to the current terminal width minus ``margin``.
2172
+
2173
+ Returns ``self`` for chaining. Equivalent in spirit to comfy-table /
2174
+ tty-table "fit the window" helpers; ``max_width=None`` already tracks
2175
+ the live terminal, but this pins an explicit budget.
2176
+ """
2177
+ cols, _ = get_window_size()
2178
+ self.max_width = max(1, int(cols) - int(margin))
2179
+ return self
1964
2180
 
1965
2181
  @auto_wrap.setter
1966
2182
  def auto_wrap(self, value: bool):
@@ -2019,7 +2235,9 @@ class Table(object):
2019
2235
  Gets the style composition using a checked name.
2020
2236
 
2021
2237
  ``cell_padding`` overrides the style's per-side margin; ``show_margin``
2022
- False forces margin 0 when no explicit padding is set.
2238
+ False forces margin 0 when no explicit padding is set. ``hrules`` /
2239
+ ``vrules`` optionally thin out horizontal / vertical separators
2240
+ (PrettyTable-style) without changing the named style.
2023
2241
  """
2024
2242
  base = style_catalogue.__getattribute__(self.__checked_style_name)
2025
2243
  if self.__cell_padding is not None:
@@ -2028,9 +2246,97 @@ class Table(object):
2028
2246
  margin = 0
2029
2247
  else:
2030
2248
  margin = base.margin
2031
- if margin == base.margin:
2249
+ replacements = {}
2250
+ if margin != base.margin:
2251
+ replacements['margin'] = margin
2252
+ hrules = self.__hrules
2253
+ if hrules is not None and hrules != 'all':
2254
+ replacements.update(self.__hrules_replacements(base, hrules))
2255
+ vrules = self.__vrules
2256
+ if vrules is not None and vrules != 'all':
2257
+ replacements.update(self.__vrules_replacements(base, vrules))
2258
+ if not replacements:
2032
2259
  return base
2033
- return base._replace(margin=margin)
2260
+ return base._replace(**replacements)
2261
+
2262
+ @staticmethod
2263
+ def __hrules_replacements(base, mode):
2264
+ """Map hrules mode -> TableComposition field overrides."""
2265
+ mode = str(mode).lower()
2266
+ none = {
2267
+ 'superior_header_line': None,
2268
+ 'inferior_header_line': None,
2269
+ 'superior_header_line_no_header': None,
2270
+ 'table_body_line': None,
2271
+ 'table_end_line': None,
2272
+ }
2273
+ if mode in ('none', 'n', 'off', 'false', '0'):
2274
+ return none
2275
+ if mode in ('frame', 'f'):
2276
+ # Top + bottom only; drop body separators and header underline.
2277
+ return {
2278
+ 'inferior_header_line': None,
2279
+ 'table_body_line': None,
2280
+ }
2281
+ if mode in ('header', 'h'):
2282
+ # Keep only the header underline (and top/bottom frame if present).
2283
+ return {
2284
+ 'table_body_line': None,
2285
+ }
2286
+ raise ValueError(
2287
+ "hrules must be 'all', 'frame', 'header', or 'none', got {0!r}"
2288
+ .format(mode)
2289
+ )
2290
+
2291
+ @staticmethod
2292
+ def __vrules_replacements(base, mode):
2293
+ """Map vrules mode -> vertical SeparatorLine overrides."""
2294
+ mode = str(mode).lower()
2295
+ invisible = SeparatorLine(None, INVISIBLE_SEPARATOR, None, None)
2296
+
2297
+ def drop_intersections(sep):
2298
+ """Horizontal rule without column junctions (vrules none/frame)."""
2299
+ if sep is None:
2300
+ return None
2301
+ # Keep the fill character; blank the junction so no leftover ┬/┼.
2302
+ fill = sep.middle if sep.middle not in (None, '') else INVISIBLE_SEPARATOR
2303
+ return SeparatorLine(sep.left, fill, fill, sep.right)
2304
+
2305
+ if mode in ('none', 'n', 'off', 'false', '0'):
2306
+ return {
2307
+ 'vertical_header_lines': invisible,
2308
+ 'vertical_table_body_lines': invisible,
2309
+ 'superior_header_line': drop_intersections(base.superior_header_line),
2310
+ 'inferior_header_line': drop_intersections(base.inferior_header_line),
2311
+ 'superior_header_line_no_header': drop_intersections(
2312
+ base.superior_header_line_no_header
2313
+ ),
2314
+ 'table_body_line': drop_intersections(base.table_body_line),
2315
+ 'table_end_line': drop_intersections(base.table_end_line),
2316
+ }
2317
+ if mode in ('frame', 'f'):
2318
+ def frame_only(sep):
2319
+ if sep is None:
2320
+ return SeparatorLine(None, INVISIBLE_SEPARATOR, None, None)
2321
+ return SeparatorLine(
2322
+ sep.left, INVISIBLE_SEPARATOR, None, sep.right
2323
+ )
2324
+ return {
2325
+ 'vertical_header_lines': frame_only(base.vertical_header_lines),
2326
+ 'vertical_table_body_lines': frame_only(
2327
+ base.vertical_table_body_lines
2328
+ ),
2329
+ 'superior_header_line': drop_intersections(base.superior_header_line),
2330
+ 'inferior_header_line': drop_intersections(base.inferior_header_line),
2331
+ 'superior_header_line_no_header': drop_intersections(
2332
+ base.superior_header_line_no_header
2333
+ ),
2334
+ 'table_body_line': drop_intersections(base.table_body_line),
2335
+ 'table_end_line': drop_intersections(base.table_end_line),
2336
+ }
2337
+ raise ValueError(
2338
+ "vrules must be 'all', 'frame', or 'none', got {0!r}".format(mode)
2339
+ )
2034
2340
 
2035
2341
  @property
2036
2342
  def __checked_style_name(self) -> str:
@@ -3642,19 +3948,28 @@ class Table(object):
3642
3948
  else:
3643
3949
  formatted = value
3644
3950
 
3951
+ if self.__strip_cells and isinstance(formatted, str):
3952
+ formatted = formatted.strip()
3953
+
3645
3954
  custom = self.__custom_format
3646
3955
  if custom is None:
3647
3956
  return formatted
3648
3957
  if callable(custom) and not isinstance(custom, dict):
3649
- return custom(formatted)
3650
- if isinstance(custom, dict):
3958
+ result = custom(formatted)
3959
+ elif isinstance(custom, dict):
3651
3960
  spec = custom.get(header)
3652
3961
  if spec is None and column_i is not None:
3653
3962
  # Allow integer keys for positional columns.
3654
3963
  spec = custom.get(column_i)
3655
3964
  if spec is not None:
3656
- return self.__apply_format_spec(formatted, spec)
3657
- return formatted
3965
+ result = self.__apply_format_spec(formatted, spec)
3966
+ else:
3967
+ result = formatted
3968
+ else:
3969
+ result = formatted
3970
+ if self.__strip_cells and isinstance(result, str):
3971
+ return result.strip()
3972
+ return result
3658
3973
 
3659
3974
  def __bound_for_column(self, bounds, header, column_i):
3660
3975
  """Resolve a per-column min/max width for one column."""
@@ -3983,6 +4298,11 @@ class Table(object):
3983
4298
  self.__i_step,
3984
4299
  )
3985
4300
 
4301
+ if self.__roman_index and rows_with_i:
4302
+ for row_i, row in enumerate(rows_with_i):
4303
+ if row:
4304
+ rows_with_i[row_i][0] = to_roman(row[0])
4305
+
3986
4306
  headers = list(self.__headers)
3987
4307
  for row_i, row in enumerate(rows):
3988
4308
  for column_i, header in enumerate(headers):
@@ -4117,6 +4437,25 @@ class Table(object):
4117
4437
  self.__column_alignments_as_list_with_i.append(column_alignment)
4118
4438
  self.__column_types_as_list_with_i.append(column_type)
4119
4439
 
4440
+ def __display_header_labels(self, headers):
4441
+ """
4442
+ Headers as shown: optional 1-based numbering for data columns.
4443
+
4444
+ Index column (``IndexColumnTitle``) keeps ``index_title``. Dict keys
4445
+ elsewhere still use the real header objects.
4446
+ """
4447
+ if not self.__number_columns:
4448
+ return list(headers)
4449
+ labels = []
4450
+ n = 0
4451
+ for header in headers:
4452
+ if isinstance(header, IndexColumnTitle):
4453
+ labels.append(header)
4454
+ else:
4455
+ n += 1
4456
+ labels.append(str(n))
4457
+ return labels
4458
+
4120
4459
  def __wrap_data(self,
4121
4460
  rows,
4122
4461
  rows_with_i,
@@ -4142,11 +4481,12 @@ class Table(object):
4142
4481
  # Fitting can hand back a one-shot zip(); materialise before any
4143
4482
  # pass that walks the rows (valign resolution would otherwise empty it).
4144
4483
  rows = list(rows) if rows is not None else []
4484
+ display_headers = self.__display_header_labels(headers)
4145
4485
  header_valigns, row_valigns = self.__valigns_for_wrap(
4146
4486
  headers, rows
4147
4487
  )
4148
4488
  wrapped_headers, wrapped_rows = _wrap_rows(
4149
- headers,
4489
+ display_headers,
4150
4490
  rows,
4151
4491
  header_valigns=header_valigns,
4152
4492
  row_valigns=row_valigns,
@@ -5093,17 +5433,29 @@ class Table(object):
5093
5433
 
5094
5434
  @classmethod
5095
5435
  def from_csv(cls, source, parse_numbers=True, has_header=True,
5096
- delimiter=',', encoding='utf-8', **options):
5436
+ delimiter=',', encoding='utf-8', dialect=None, quoting=None,
5437
+ quotechar=None, escapechar=None, doublequote=None,
5438
+ lineterminator=None, skipinitialspace=None, strict=None,
5439
+ **options):
5097
5440
  """
5098
5441
  Build a table from a CSV path or open handle.
5099
5442
 
5100
5443
  Numeric-looking text is converted by default; a column left as strings
5101
5444
  would be left-aligned and look wrong. Pass ``parse_numbers=False`` to
5102
5445
  keep the text exactly as written.
5446
+
5447
+ Dialect extras (``dialect``, ``quoting``, ``quotechar``,
5448
+ ``escapechar``, ``doublequote``, ``lineterminator``,
5449
+ ``skipinitialspace``, ``strict``) go to ``csv.reader``.
5103
5450
  """
5104
5451
  from .readers import from_csv
5105
- return from_csv(cls, source, parse_numbers, has_header, delimiter,
5106
- encoding, **options)
5452
+ return from_csv(
5453
+ cls, source, parse_numbers, has_header, delimiter, encoding,
5454
+ dialect=dialect, quoting=quoting, quotechar=quotechar,
5455
+ escapechar=escapechar, doublequote=doublequote,
5456
+ lineterminator=lineterminator, skipinitialspace=skipinitialspace,
5457
+ strict=strict, **options
5458
+ )
5107
5459
 
5108
5460
  @classmethod
5109
5461
  def from_html(cls, source, index=0, parse_numbers=True, encoding='utf-8',
@@ -5198,6 +5550,62 @@ class Table(object):
5198
5550
  'border_color': '#0074d9',
5199
5551
  'zebra': ('', 'on #001f3f'),
5200
5552
  },
5553
+ 'solarized': {
5554
+ 'style_name': 'sharp',
5555
+ 'use_colors': True,
5556
+ 'header_color': 'bold #268bd2',
5557
+ 'border_color': '#586e75',
5558
+ 'zebra': ('', 'on #073642'),
5559
+ },
5560
+ 'neon': {
5561
+ 'style_name': 'bold_borderline',
5562
+ 'use_colors': True,
5563
+ 'header_color': 'bold magenta',
5564
+ 'border_color': 'cyan',
5565
+ 'zebra': ('', 'on #1a0033'),
5566
+ },
5567
+ 'mono': {
5568
+ 'style_name': 'simple',
5569
+ 'use_colors': True,
5570
+ 'header_color': 'bold',
5571
+ 'border_color': 'dim',
5572
+ 'zebra': 'dim',
5573
+ },
5574
+ 'autumn': {
5575
+ 'style_name': 'rounded',
5576
+ 'use_colors': True,
5577
+ 'header_color': 'bold #d75f00',
5578
+ 'border_color': '#af5f00',
5579
+ 'zebra': ('', 'on #3a1f00'),
5580
+ },
5581
+ 'contrast': {
5582
+ 'style_name': 'ascii',
5583
+ 'use_colors': True,
5584
+ 'header_color': 'bold reverse',
5585
+ 'border_color': 'bold',
5586
+ 'zebra': ('', 'reverse'),
5587
+ },
5588
+ 'forest': {
5589
+ 'style_name': 'modern',
5590
+ 'use_colors': True,
5591
+ 'header_color': 'bold #87d787',
5592
+ 'border_color': '#005f00',
5593
+ 'zebra': ('', 'on #002200'),
5594
+ },
5595
+ 'ember': {
5596
+ 'style_name': 'bold_borderline',
5597
+ 'use_colors': True,
5598
+ 'header_color': 'bold #ffaf00',
5599
+ 'border_color': '#d70000',
5600
+ 'zebra': ('', 'on #2a0000'),
5601
+ },
5602
+ 'slate': {
5603
+ 'style_name': 'psql',
5604
+ 'use_colors': True,
5605
+ 'header_color': 'bold #a8a8a8',
5606
+ 'border_color': '#6c6c6c',
5607
+ 'zebra': ('', 'on #303030'),
5608
+ },
5201
5609
  }
5202
5610
 
5203
5611
  def apply_theme(self, name):
@@ -5205,7 +5613,9 @@ class Table(object):
5205
5613
  Apply a named theme: style plus header/border/zebra colours.
5206
5614
 
5207
5615
  Themes: ``plain``, ``dark``, ``midnight``, ``matrix``, ``report``,
5208
- ``markdown``, ``ocean``. Returns ``self`` for chaining.
5616
+ ``markdown``, ``ocean``, ``solarized``, ``neon``, ``mono``, ``autumn``,
5617
+ ``contrast``, ``forest``, ``ember``, ``slate``. Returns ``self`` for
5618
+ chaining. See ``THEMES`` for the full map.
5209
5619
  """
5210
5620
  if name not in self.THEMES:
5211
5621
  raise ValueError(
@@ -5349,7 +5759,9 @@ class Table(object):
5349
5759
  'border_color', 'use_colors', 'zebra', 'footer_rows', 'footer_color',
5350
5760
  'cell_padding', 'overflow', 'auto_wrap', 'valign', 'col_valign',
5351
5761
  'panel', 'shadow', 'col_alignment', 'header_align', 'max_width',
5352
- 'table_align', 'hide_columns',
5762
+ 'table_align', 'hide_columns', 'index_title', 'roman_index',
5763
+ 'number_columns', 'strip_cells', 'hrules', 'vrules',
5764
+ 'index_start', 'index_step',
5353
5765
  ):
5354
5766
  try:
5355
5767
  setattr(out, attr, getattr(self, attr))
@@ -5406,11 +5818,13 @@ class Table(object):
5406
5818
  """Alias of :meth:`transpose` (tabled naming)."""
5407
5819
  return self.transpose(**options)
5408
5820
 
5409
- def paginate(self, page_length=20):
5821
+ def paginate(self, page_length=20, freeze_header=True, page_label=False):
5410
5822
  """
5411
5823
  Split the table into composed string pages of ``page_length`` body rows.
5412
5824
 
5413
- Each page is a full table (headers/title/caption/panel repeated).
5825
+ Each page is a full table. With ``freeze_header`` True (default),
5826
+ headers repeat on every page; with False, only the first page shows
5827
+ them. ``page_label`` adds ``page k/n`` to each page title.
5414
5828
  Returns a list of strings. ``page_length`` must be >= 1.
5415
5829
  Inspired by PrettyTable ``paginate`` / go-pretty.
5416
5830
  """
@@ -5421,8 +5835,9 @@ class Table(object):
5421
5835
  n = self.row_count
5422
5836
  if n == 0:
5423
5837
  return [self.compose()]
5838
+ total_pages = (n + page_length - 1) // page_length
5424
5839
  pages = []
5425
- for start in range(0, n, page_length):
5840
+ for page_num, start in enumerate(range(0, n, page_length), start=1):
5426
5841
  end = min(start + page_length, n)
5427
5842
  slice_rows = []
5428
5843
  for row_i in range(start, end):
@@ -5442,12 +5857,21 @@ class Table(object):
5442
5857
  'cell_padding', 'overflow', 'auto_wrap', 'valign', 'col_valign',
5443
5858
  'panel', 'shadow', 'col_alignment', 'header_align', 'max_width',
5444
5859
  'column_min_width', 'column_max_width', 'table_align',
5445
- 'hide_columns',
5860
+ 'hide_columns', 'index_title', 'roman_index', 'number_columns',
5861
+ 'strip_cells', 'hrules', 'vrules', 'index_start', 'index_step',
5446
5862
  ):
5447
5863
  try:
5448
5864
  setattr(page, attr, getattr(self, attr))
5449
5865
  except Exception:
5450
5866
  pass
5867
+ if not freeze_header and page_num > 1:
5868
+ page.show_headers = False
5869
+ if page_label:
5870
+ label = 'page {0}/{1}'.format(page_num, total_pages)
5871
+ existing = page.title
5872
+ page.title = (
5873
+ '{0} ({1})'.format(existing, label) if existing else label
5874
+ )
5451
5875
  if self.__cell_colors:
5452
5876
  # Remap absolute row indexes into the page's local indexes.
5453
5877
  remapped = {}
@@ -5477,15 +5901,25 @@ class Table(object):
5477
5901
  return to_records(self, include_index)
5478
5902
 
5479
5903
  def to_csv(self, target=None, include_index=False, delimiter=',',
5480
- encoding='utf-8'):
5904
+ encoding='utf-8', dialect=None, quoting=None, quotechar=None,
5905
+ escapechar=None, doublequote=None, lineterminator=None,
5906
+ skipinitialspace=None, strict=None):
5481
5907
  """
5482
5908
  Write the table as CSV.
5483
5909
 
5484
5910
  Returns the CSV as a string when no target is given. Colour is
5485
5911
  stripped -- escape sequences would corrupt the fields.
5912
+
5913
+ Dialect extras are forwarded to ``csv.writer``.
5486
5914
  """
5487
5915
  from .writers import to_csv
5488
- return to_csv(self, target, include_index, delimiter, encoding)
5916
+ return to_csv(
5917
+ self, target, include_index, delimiter, encoding,
5918
+ dialect=dialect, quoting=quoting, quotechar=quotechar,
5919
+ escapechar=escapechar, doublequote=doublequote,
5920
+ lineterminator=lineterminator, skipinitialspace=skipinitialspace,
5921
+ strict=strict,
5922
+ )
5489
5923
 
5490
5924
  def to_markdown(self, include_index=False, align=True):
5491
5925
  """
@@ -230,3 +230,29 @@ class ValuePlacer(object):
230
230
  def __call__(self, value):
231
231
  return value
232
232
 
233
+
234
+
235
+ def to_roman(number):
236
+ """
237
+ Convert a non-negative integer to a Roman numeral string.
238
+
239
+ ``0`` and negatives fall back to decimal (Romans had no zero). Values
240
+ above 3999 use additive ``M`` thousands rather than overlines.
241
+ """
242
+ try:
243
+ number = int(number)
244
+ except (TypeError, ValueError):
245
+ return str(number)
246
+ if number <= 0:
247
+ return str(number)
248
+ parts = []
249
+ table = (
250
+ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
251
+ (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
252
+ (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'),
253
+ )
254
+ for value, numeral in table:
255
+ while number >= value:
256
+ parts.append(numeral)
257
+ number -= value
258
+ return ''.join(parts)
@@ -165,17 +165,31 @@ def to_simple_html(table, include_index: bool = False) -> str:
165
165
 
166
166
 
167
167
  def to_csv(table, target=None, include_index: bool = False,
168
- delimiter: str = ',', encoding: str = 'utf-8') -> Optional[str]:
168
+ delimiter: str = ',', encoding: str = 'utf-8',
169
+ dialect=None, quoting=None, quotechar=None, escapechar=None,
170
+ doublequote=None, lineterminator=None, skipinitialspace=None,
171
+ strict=None) -> Optional[str]:
169
172
  """
170
173
  Write CSV.
171
174
 
172
175
  With no target, returns the CSV as a string; otherwise writes to the given
173
176
  path or open handle and returns None.
177
+
178
+ Dialect extras (``quoting``, ``quotechar``, ``escapechar``,
179
+ ``doublequote``, ``lineterminator``, ``skipinitialspace``, ``strict``,
180
+ ``dialect``) are forwarded to ``csv.writer``.
174
181
  """
175
182
  headers, rows = _table_data(table, include_index)
183
+ from .readers import _csv_reader_kwargs
184
+ writer_kwargs = _csv_reader_kwargs(
185
+ delimiter=delimiter, dialect=dialect, quoting=quoting,
186
+ quotechar=quotechar, escapechar=escapechar,
187
+ doublequote=doublequote, lineterminator=lineterminator,
188
+ skipinitialspace=skipinitialspace, strict=strict,
189
+ )
176
190
 
177
191
  def dump(handle):
178
- writer = _csv.writer(handle, delimiter=delimiter)
192
+ writer = _csv.writer(handle, **writer_kwargs)
179
193
  writer.writerow([_plain(header) for header in headers])
180
194
  for row in rows:
181
195
  writer.writerow([_plain(cell) for cell in row])
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flexablelib
3
- Version: 2.0.15
3
+ Version: 2.0.16
4
4
  Summary: Flexible console and HTML tables for Python
5
5
  Home-page: https://github.com/Opus-Perpetuus/flexablelib
6
6
  Download-URL:
@@ -41,5 +41,6 @@ tests/test_upstream_issues.py
41
41
  tests/test_v213_features.py
42
42
  tests/test_v214_features.py
43
43
  tests/test_v215_features.py
44
+ tests/test_v216_features.py
44
45
  tools/benchmark.py
45
46
  tools/generate_width_tables.py
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flexablelib",
3
- "version": "2.0.15",
3
+ "version": "2.0.16",
4
4
  "description": "Flexible console and HTML tables for Python: styles, merges, colors, widths, decimal alignment.",
5
5
  "main": "__init__.py",
6
6
  "scripts": {
@@ -0,0 +1,155 @@
1
+ """Features shipped in 2.0.16 (index polish, rules, CSV dialect, themes…)."""
2
+ import csv
3
+ import io
4
+ import re
5
+
6
+ import pytest
7
+
8
+ from flexablelib.table import Table
9
+ from flexablelib.utils import to_roman
10
+
11
+
12
+ def bare(text: str) -> str:
13
+ return re.sub(r'\x1b\[[0-9;]*m', '', text)
14
+
15
+
16
+ def test_to_roman_helper():
17
+ assert to_roman(1) == 'I'
18
+ assert to_roman(4) == 'IV'
19
+ assert to_roman(9) == 'IX'
20
+ assert to_roman(2026) == 'MMXXVI'
21
+ assert to_roman(0) == '0'
22
+ assert to_roman(-3) == '-3'
23
+
24
+
25
+ def test_index_title_and_roman_index():
26
+ t = Table.from_records(
27
+ [['a', 1], ['b', 2]],
28
+ headers=['N', 'V'],
29
+ style_name='sharp',
30
+ )
31
+ t.show_index = True
32
+ t.index_title = '#'
33
+ t.roman_index = True
34
+ t.index_start = 1
35
+ out = bare(t.compose())
36
+ assert '#' in out
37
+ assert '│ I │' in out or 'I' in out
38
+ assert 'II' in out
39
+ # stored headers unchanged
40
+ assert t.headers == ['N', 'V']
41
+
42
+
43
+ def test_number_columns_and_strip_cells():
44
+ t = Table.from_records(
45
+ [[' x ', ' y '], ['z', 'w']],
46
+ headers=['Name', 'Val'],
47
+ style_name='sharp',
48
+ )
49
+ t.number_columns = True
50
+ t.strip_cells = True
51
+ out = bare(t.compose())
52
+ assert 'Name' not in out and 'Val' not in out
53
+ assert '│ 1 │' in out or '| 1 |' in out or ' 1 ' in out
54
+ assert 'x' in out and ' x ' not in out
55
+
56
+
57
+ def test_suppress_empty():
58
+ t = Table.from_records(
59
+ [['a', 1], ['', ''], ['b', 2]],
60
+ headers=['N', 'V'],
61
+ style_name='simple',
62
+ )
63
+ t.suppress_empty = True
64
+ assert t.show_empty_rows is False
65
+ assert t.show_empty_columns is False
66
+ out = bare(t.compose())
67
+ # three data lines would include blank; suppressed leaves two body rows
68
+ assert out.count('\n') >= 2
69
+ assert 'a' in out and 'b' in out
70
+
71
+
72
+ def test_hrules_and_vrules():
73
+ t = Table.from_records([[1, 2]], headers=['A', 'B'], style_name='pretty_grid')
74
+ t.hrules = 'none'
75
+ out = bare(t.compose())
76
+ # no horizontal box lines
77
+ assert '═' not in out and '─' not in out
78
+ t.hrules = 'all'
79
+ t.vrules = 'none'
80
+ out2 = bare(t.compose())
81
+ assert '│' not in out2
82
+ t.vrules = 'frame'
83
+ out3 = bare(t.compose())
84
+ assert '│' in out3
85
+ with pytest.raises(ValueError):
86
+ t.hrules = 'diagonal'
87
+
88
+
89
+ def test_divide_every_and_add_dividers():
90
+ t = Table.from_records(
91
+ [[i, i] for i in range(6)],
92
+ headers=['a', 'b'],
93
+ style_name='presto',
94
+ )
95
+ t.divide_every(2)
96
+ out = bare(t.compose())
97
+ # presto body separators are dashes
98
+ assert out.count('----') >= 2 or out.count('-') > 10
99
+ t.clear_dividers()
100
+ t.add_dividers(0, 3)
101
+ assert 0 in t._Table__dividers and 3 in t._Table__dividers
102
+
103
+
104
+ def test_fit_terminal_and_aliases():
105
+ t = Table.from_records([[1]], headers=['A'])
106
+ t.fit_terminal(margin=5)
107
+ assert t.max_width is not None and t.max_width >= 1
108
+ t.max_table_width = 40
109
+ assert t.max_width == 40
110
+ t.justify = 'c'
111
+ assert t.table_align in ('c', 'tc')
112
+
113
+
114
+ def test_csv_dialect_roundtrip():
115
+ raw = 'a;b\n"1;x";2\n'
116
+ t = Table.from_csv(
117
+ io.StringIO(raw),
118
+ delimiter=';',
119
+ quotechar='"',
120
+ parse_numbers=False,
121
+ )
122
+ assert t.headers == ['a', 'b']
123
+ assert t.columns['a'] == ['1;x']
124
+ dumped = t.to_csv(quoting=csv.QUOTE_ALL, quotechar="'")
125
+ assert "'a'" in dumped and "'1;x'" in dumped
126
+
127
+
128
+ def test_themes_expanded():
129
+ for name in (
130
+ 'solarized', 'neon', 'mono', 'autumn', 'contrast',
131
+ 'forest', 'ember', 'slate',
132
+ ):
133
+ assert name in Table.THEMES
134
+ t = Table.from_records([[1]], headers=['x'])
135
+ t.apply_theme('forest')
136
+ assert t.header_color == 'bold #87d787'
137
+
138
+
139
+ def test_paginate_freeze_header_and_page_label():
140
+ t = Table.from_records(
141
+ [[i, i] for i in range(4)],
142
+ headers=['A', 'B'],
143
+ style_name='rounded',
144
+ )
145
+ pages = t.paginate(2, freeze_header=True, page_label=True)
146
+ assert len(pages) == 2
147
+ assert 'page 1/2' in bare(pages[0])
148
+ assert 'page 2/2' in bare(pages[1])
149
+ assert 'A' in bare(pages[1])
150
+ pages2 = t.paginate(2, freeze_header=False)
151
+ assert 'A' in bare(pages2[0])
152
+ # second page should not repeat header label row
153
+ body = bare(pages2[1])
154
+ # title absent; header cells A/B should be gone
155
+ assert '│ A │' not in body and '| A |' not in body
File without changes
File without changes
File without changes
File without changes
File without changes