Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/rich/table.py: 81%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

412 statements  

1from dataclasses import dataclass, field, replace 

2from typing import TYPE_CHECKING, Iterable, NamedTuple, Sequence 

3 

4from . import box, errors 

5from ._loop import loop_first_last, loop_last 

6from ._pick import pick_bool 

7from ._ratio import ratio_distribute, ratio_reduce 

8from .align import VerticalAlignMethod 

9from .jupyter import JupyterMixin 

10from .measure import Measurement 

11from .padding import Padding, PaddingDimensions 

12from .protocol import is_renderable 

13from .segment import Segment 

14from .style import Style, StyleType 

15from .text import Text, TextType 

16 

17if TYPE_CHECKING: 

18 from .console import ( 

19 Console, 

20 ConsoleOptions, 

21 JustifyMethod, 

22 OverflowMethod, 

23 RenderableType, 

24 RenderResult, 

25 ) 

26 

27 

28@dataclass 

29class Column: 

30 """Defines a column within a ~Table. 

31 

32 Args: 

33 title (str | Text, optional): The title of the table rendered at the top. Defaults to None. 

34 caption (str | Text, optional): The table caption rendered below. Defaults to None. 

35 width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None. 

36 min_width (int | None, optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None. 

37 box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD. 

38 safe_box (bool | None, optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True. 

39 padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1). 

40 collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False. 

41 pad_edge (bool, optional): Enable padding of edge cells. Defaults to True. 

42 show_header (bool, optional): Show a header row. Defaults to True. 

43 show_footer (bool, optional): Show a footer row. Defaults to False. 

44 show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True. 

45 show_lines (bool, optional): Draw lines between every row. Defaults to False. 

46 leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0. 

47 style (str | Style, optional): Default style for the table. Defaults to "none". 

48 row_styles (list[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None. 

49 header_style (str | Style, optional): Style of the header. Defaults to "table.header". 

50 footer_style (str | Style, optional): Style of the footer. Defaults to "table.footer". 

51 border_style (str | Style, optional): Style of the border. Defaults to None. 

52 title_style (str | Style, optional): Style of the title. Defaults to None. 

53 caption_style (str | Style, optional): Style of the caption. Defaults to None. 

54 title_justify (str, optional): Justify method for title. Defaults to "center". 

55 caption_justify (str, optional): Justify method for caption. Defaults to "center". 

56 highlight (bool, optional): Highlight cell contents (if str). Defaults to False. 

57 """ 

58 

59 header: "RenderableType" = "" 

60 """RenderableType: Renderable for the header (typically a string)""" 

61 

62 footer: "RenderableType" = "" 

63 """RenderableType: Renderable for the footer (typically a string)""" 

64 

65 header_style: StyleType = "" 

66 """StyleType: The style of the header.""" 

67 

68 footer_style: StyleType = "" 

69 """StyleType: The style of the footer.""" 

70 

71 style: StyleType = "" 

72 """StyleType: The style of the column.""" 

73 

74 justify: "JustifyMethod" = "left" 

75 """str: How to justify text within the column ("left", "center", "right", or "full")""" 

76 

77 vertical: "VerticalAlignMethod" = "top" 

78 """str: How to vertically align content ("top", "middle", or "bottom")""" 

79 

80 overflow: "OverflowMethod" = "ellipsis" 

81 """str: Overflow method.""" 

82 

83 width: int | None = None 

84 """int | None: Width of the column, or ``None`` (default) to auto calculate width.""" 

85 

86 min_width: int | None = None 

87 """int | None: Minimum width of column, or ``None`` for no minimum. Defaults to None.""" 

88 

89 max_width: int | None = None 

90 """int | None: Maximum width of column, or ``None`` for no maximum. Defaults to None.""" 

91 

92 ratio: int | None = None 

93 """int | None: Ratio to use when calculating column width, or ``None`` (default) to adapt to column contents.""" 

94 

95 no_wrap: bool = False 

96 """bool: Prevent wrapping of text within the column. Defaults to ``False``.""" 

97 

98 highlight: bool = False 

99 """bool: Apply highlighter to column. Defaults to ``False``.""" 

100 

101 _index: int = 0 

102 """Index of column.""" 

103 

104 _cells: list["RenderableType"] = field(default_factory=list) 

105 

106 def copy(self) -> "Column": 

107 """Return a copy of this Column.""" 

108 return replace(self, _cells=[]) 

109 

110 @property 

111 def cells(self) -> Iterable["RenderableType"]: 

112 """Get all cells in the column, not including header.""" 

113 yield from self._cells 

114 

115 @property 

116 def flexible(self) -> bool: 

117 """Check if this column is flexible.""" 

118 return self.ratio is not None 

119 

120 

121@dataclass 

122class Row: 

123 """Information regarding a row.""" 

124 

125 style: StyleType | None = None 

126 """Style to apply to row.""" 

127 

128 end_section: bool = False 

129 """Indicated end of section, which will force a line beneath the row.""" 

130 

131 

132class _Cell(NamedTuple): 

133 """A single cell in a table.""" 

134 

135 style: StyleType 

136 """Style to apply to cell.""" 

137 renderable: "RenderableType" 

138 """Cell renderable.""" 

139 vertical: VerticalAlignMethod 

140 """Cell vertical alignment.""" 

141 

142 

143class Table(JupyterMixin): 

144 """A console renderable to draw a table. 

145 

146 Args: 

147 *headers (Column | str): Column headers, either as a string, or :class:`~rich.table.Column` instance. 

148 title (str | Text, optional): The title of the table rendered at the top. Defaults to None. 

149 caption (str | Text, optional): The table caption rendered below. Defaults to None. 

150 width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None. 

151 min_width (int | None, optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None. 

152 box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD. 

153 safe_box (bool | None, optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True. 

154 padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1). 

155 collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False. 

156 pad_edge (bool, optional): Enable padding of edge cells. Defaults to True. 

157 expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False. 

158 show_header (bool, optional): Show a header row. Defaults to True. 

159 show_footer (bool, optional): Show a footer row. Defaults to False. 

160 show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True. 

161 show_lines (bool, optional): Draw lines between every row. Defaults to False. 

162 leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0. 

163 style (str | Style, optional): Default style for the table. Defaults to "none". 

164 row_styles (list[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None. 

165 header_style (str | Style, optional): Style of the header. Defaults to "table.header". 

166 footer_style (str | Style, optional): Style of the footer. Defaults to "table.footer". 

167 border_style (str | Style, optional): Style of the border. Defaults to None. 

168 title_style (str | Style, optional): Style of the title. Defaults to None. 

169 caption_style (str | Style, optional): Style of the caption. Defaults to None. 

170 title_justify (str, optional): Justify method for title. Defaults to "center". 

171 caption_justify (str, optional): Justify method for caption. Defaults to "center". 

172 highlight (bool, optional): Highlight cell contents (if str). Defaults to False. 

173 """ 

174 

175 columns: list[Column] 

176 rows: list[Row] 

177 

178 def __init__( 

179 self, 

180 *headers: Column | str, 

181 title: TextType | None = None, 

182 caption: TextType | None = None, 

183 width: int | None = None, 

184 min_width: int | None = None, 

185 box: box.Box | None = box.HEAVY_HEAD, 

186 safe_box: bool | None = None, 

187 padding: PaddingDimensions = (0, 1), 

188 collapse_padding: bool = False, 

189 pad_edge: bool = True, 

190 expand: bool = False, 

191 show_header: bool = True, 

192 show_footer: bool = False, 

193 show_edge: bool = True, 

194 show_lines: bool = False, 

195 leading: int = 0, 

196 style: StyleType = "none", 

197 row_styles: Iterable[StyleType] | None = None, 

198 header_style: StyleType | None = "table.header", 

199 footer_style: StyleType | None = "table.footer", 

200 border_style: StyleType | None = None, 

201 title_style: StyleType | None = None, 

202 caption_style: StyleType | None = None, 

203 title_justify: "JustifyMethod" = "center", 

204 caption_justify: "JustifyMethod" = "center", 

205 highlight: bool = False, 

206 ) -> None: 

207 self.columns: list[Column] = [] 

208 self.rows: list[Row] = [] 

209 self.title = title 

210 self.caption = caption 

211 self.width = width 

212 self.min_width = min_width 

213 self.box = box 

214 self.safe_box = safe_box 

215 self._padding = Padding.unpack(padding) 

216 self.pad_edge = pad_edge 

217 self._expand = expand 

218 self.show_header = show_header 

219 self.show_footer = show_footer 

220 self.show_edge = show_edge 

221 self.show_lines = show_lines 

222 self.leading = leading 

223 self.collapse_padding = collapse_padding 

224 self.style = style 

225 self.header_style = header_style or "" 

226 self.footer_style = footer_style or "" 

227 self.border_style = border_style 

228 self.title_style = title_style 

229 self.caption_style = caption_style 

230 self.title_justify: "JustifyMethod" = title_justify 

231 self.caption_justify: "JustifyMethod" = caption_justify 

232 self.highlight = highlight 

233 self.row_styles: Sequence[StyleType] = list(row_styles or []) 

234 append_column = self.columns.append 

235 for header in headers: 

236 if isinstance(header, str): 

237 self.add_column(header=header) 

238 else: 

239 header._index = len(self.columns) 

240 append_column(header) 

241 

242 @classmethod 

243 def grid( 

244 cls, 

245 *headers: Column | str, 

246 padding: PaddingDimensions = 0, 

247 collapse_padding: bool = True, 

248 pad_edge: bool = False, 

249 expand: bool = False, 

250 ) -> "Table": 

251 """Get a table with no lines, headers, or footer. 

252 

253 Args: 

254 *headers (Column | str): Column headers, either as a string, or :class:`~rich.table.Column` instance. 

255 padding (PaddingDimensions, optional): Get padding around cells. Defaults to 0. 

256 collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to True. 

257 pad_edge (bool, optional): Enable padding around edges of table. Defaults to False. 

258 expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False. 

259 

260 Returns: 

261 Table: A table instance. 

262 """ 

263 return cls( 

264 *headers, 

265 box=None, 

266 padding=padding, 

267 collapse_padding=collapse_padding, 

268 show_header=False, 

269 show_footer=False, 

270 show_edge=False, 

271 pad_edge=pad_edge, 

272 expand=expand, 

273 ) 

274 

275 @property 

276 def expand(self) -> bool: 

277 """Setting a non-None self.width implies expand.""" 

278 return self._expand or self.width is not None 

279 

280 @expand.setter 

281 def expand(self, expand: bool) -> None: 

282 """Set expand.""" 

283 self._expand = expand 

284 

285 @property 

286 def _extra_width(self) -> int: 

287 """Get extra width to add to cell content.""" 

288 width = 0 

289 if self.box and self.show_edge: 

290 width += 2 

291 if self.box: 

292 width += len(self.columns) - 1 

293 return width 

294 

295 @property 

296 def row_count(self) -> int: 

297 """Get the current number of rows.""" 

298 return len(self.rows) 

299 

300 def get_row_style(self, console: "Console", index: int) -> StyleType: 

301 """Get the current row style.""" 

302 style = Style.null() 

303 if self.row_styles: 

304 style += console.get_style(self.row_styles[index % len(self.row_styles)]) 

305 row_style = self.rows[index].style 

306 if row_style is not None: 

307 style += console.get_style(row_style) 

308 return style 

309 

310 def __rich_measure__( 

311 self, console: "Console", options: "ConsoleOptions" 

312 ) -> Measurement: 

313 max_width = options.max_width 

314 if self.width is not None: 

315 max_width = self.width 

316 if max_width < 0: 

317 return Measurement(0, 0) 

318 

319 extra_width = self._extra_width 

320 max_width = sum( 

321 self._calculate_column_widths( 

322 console, options.update_width(max_width - extra_width) 

323 ) 

324 ) 

325 _measure_column = self._measure_column 

326 

327 measurements = [ 

328 _measure_column(console, options.update_width(max_width), column) 

329 for column in self.columns 

330 ] 

331 minimum_width = ( 

332 sum(measurement.minimum for measurement in measurements) + extra_width 

333 ) 

334 maximum_width = ( 

335 sum(measurement.maximum for measurement in measurements) + extra_width 

336 if (self.width is None) 

337 else self.width 

338 ) 

339 measurement = Measurement(minimum_width, maximum_width) 

340 measurement = measurement.clamp(self.min_width) 

341 return measurement 

342 

343 @property 

344 def padding(self) -> tuple[int, int, int, int]: 

345 """Get cell padding.""" 

346 return self._padding 

347 

348 @padding.setter 

349 def padding(self, padding: PaddingDimensions) -> "Table": 

350 """Set cell padding.""" 

351 self._padding = Padding.unpack(padding) 

352 return self 

353 

354 def add_column( 

355 self, 

356 header: "RenderableType" = "", 

357 footer: "RenderableType" = "", 

358 *, 

359 header_style: StyleType | None = None, 

360 highlight: bool | None = None, 

361 footer_style: StyleType | None = None, 

362 style: StyleType | None = None, 

363 justify: "JustifyMethod" = "left", 

364 vertical: "VerticalAlignMethod" = "top", 

365 overflow: "OverflowMethod" = "ellipsis", 

366 width: int | None = None, 

367 min_width: int | None = None, 

368 max_width: int | None = None, 

369 ratio: int | None = None, 

370 no_wrap: bool = False, 

371 ) -> None: 

372 """Add a column to the table. 

373 

374 Args: 

375 header (RenderableType, optional): Text or renderable for the header. 

376 Defaults to "". 

377 footer (RenderableType, optional): Text or renderable for the footer. 

378 Defaults to "". 

379 header_style (str | Style, optional): Style for the header, or None for default. Defaults to None. 

380 highlight (bool, optional): Whether to highlight the text. The default of None uses the value of the table (self) object. 

381 footer_style (str | Style, optional): Style for the footer, or None for default. Defaults to None. 

382 style (str | Style, optional): Style for the column cells, or None for default. Defaults to None. 

383 justify (JustifyMethod, optional): Alignment for cells. Defaults to "left". 

384 vertical (VerticalAlignMethod, optional): Vertical alignment, one of "top", "middle", or "bottom". Defaults to "top". 

385 overflow (OverflowMethod): Overflow method: "crop", "fold", "ellipsis". Defaults to "ellipsis". 

386 width (int, optional): Desired width of column in characters, or None to fit to contents. Defaults to None. 

387 min_width (int | None, optional): Minimum width of column, or ``None`` for no minimum. Defaults to None. 

388 max_width (int | None, optional): Maximum width of column, or ``None`` for no maximum. Defaults to None. 

389 ratio (int, optional): Flexible ratio for the column (requires ``Table.expand`` or ``Table.width``). Defaults to None. 

390 no_wrap (bool, optional): Set to ``True`` to disable wrapping of this column. 

391 """ 

392 

393 column = Column( 

394 _index=len(self.columns), 

395 header=header, 

396 footer=footer, 

397 header_style=header_style or "", 

398 highlight=highlight if highlight is not None else self.highlight, 

399 footer_style=footer_style or "", 

400 style=style or "", 

401 justify=justify, 

402 vertical=vertical, 

403 overflow=overflow, 

404 width=width, 

405 min_width=min_width, 

406 max_width=max_width, 

407 ratio=ratio, 

408 no_wrap=no_wrap, 

409 ) 

410 self.columns.append(column) 

411 

412 def add_row( 

413 self, 

414 *renderables: "RenderableType | None", 

415 style: StyleType | None = None, 

416 end_section: bool = False, 

417 ) -> None: 

418 """Add a row of renderables. 

419 

420 Args: 

421 *renderables (None or renderable): Each cell in a row must be a renderable object (including str), 

422 or ``None`` for a blank cell. 

423 style (StyleType, optional): An optional style to apply to the entire row. Defaults to None. 

424 end_section (bool, optional): End a section and draw a line. Defaults to False. 

425 

426 Raises: 

427 errors.NotRenderableError: If you add something that can't be rendered. 

428 """ 

429 

430 def add_cell(column: Column, renderable: "RenderableType") -> None: 

431 column._cells.append(renderable) 

432 

433 cell_renderables: "list[RenderableType | None]" = list(renderables) 

434 

435 columns = self.columns 

436 if len(cell_renderables) < len(columns): 

437 cell_renderables = [ 

438 *cell_renderables, 

439 *[None] * (len(columns) - len(cell_renderables)), 

440 ] 

441 for index, renderable in enumerate(cell_renderables): 

442 if index == len(columns): 

443 column = Column(_index=index, highlight=self.highlight) 

444 for _ in self.rows: 

445 add_cell(column, Text("")) 

446 self.columns.append(column) 

447 else: 

448 column = columns[index] 

449 if renderable is None: 

450 add_cell(column, "") 

451 elif is_renderable(renderable): 

452 add_cell(column, renderable) 

453 else: 

454 raise errors.NotRenderableError( 

455 f"unable to render {type(renderable).__name__}; a string or other renderable object is required" 

456 ) 

457 self.rows.append(Row(style=style, end_section=end_section)) 

458 

459 def add_section(self) -> None: 

460 """Add a new section (draw a line after current row).""" 

461 

462 if self.rows: 

463 self.rows[-1].end_section = True 

464 

465 def __rich_console__( 

466 self, console: "Console", options: "ConsoleOptions" 

467 ) -> "RenderResult": 

468 if not self.columns: 

469 yield Segment("\n") 

470 return 

471 

472 max_width = options.max_width 

473 if self.width is not None: 

474 max_width = self.width 

475 

476 extra_width = self._extra_width 

477 

478 widths = self._calculate_column_widths( 

479 console, options.update_width(max_width - extra_width) 

480 ) 

481 table_width = sum(widths) + extra_width 

482 

483 render_options = options.update( 

484 width=table_width, highlight=self.highlight, height=None 

485 ) 

486 

487 def render_annotation( 

488 text: TextType, style: StyleType, justify: "JustifyMethod" = "center" 

489 ) -> "RenderResult": 

490 render_text = ( 

491 console.render_str(text, style=style, highlight=False) 

492 if isinstance(text, str) 

493 else text 

494 ) 

495 return console.render( 

496 render_text, options=render_options.update(justify=justify) 

497 ) 

498 

499 if self.title: 

500 yield from render_annotation( 

501 self.title, 

502 style=Style.pick_first(self.title_style, "table.title"), 

503 justify=self.title_justify, 

504 ) 

505 yield from self._render(console, render_options, widths) 

506 if self.caption: 

507 yield from render_annotation( 

508 self.caption, 

509 style=Style.pick_first(self.caption_style, "table.caption"), 

510 justify=self.caption_justify, 

511 ) 

512 

513 def _calculate_column_widths( 

514 self, console: "Console", options: "ConsoleOptions" 

515 ) -> list[int]: 

516 """Calculate the widths of each column, including padding, not including borders.""" 

517 max_width = options.max_width 

518 columns = self.columns 

519 width_ranges = [ 

520 self._measure_column(console, options, column) for column in columns 

521 ] 

522 widths = [_range.maximum or 1 for _range in width_ranges] 

523 

524 get_padding_width = self._get_padding_width 

525 extra_width = self._extra_width 

526 if self.expand: 

527 ratios = [col.ratio or 0 for col in columns if col.flexible] 

528 if any(ratios): 

529 fixed_widths = [ 

530 0 if column.flexible else _range.maximum 

531 for _range, column in zip(width_ranges, columns) 

532 ] 

533 flex_minimum = [ 

534 (column.width or 1) + get_padding_width(column._index) 

535 for column in columns 

536 if column.flexible 

537 ] 

538 flexible_width = max_width - sum(fixed_widths) 

539 flex_widths = ratio_distribute(flexible_width, ratios, flex_minimum) 

540 iter_flex_widths = iter(flex_widths) 

541 for index, column in enumerate(columns): 

542 if column.flexible: 

543 widths[index] = fixed_widths[index] + next(iter_flex_widths) 

544 table_width = sum(widths) 

545 

546 if table_width > max_width: 

547 widths = self._collapse_widths( 

548 widths, 

549 [(column.width is None and not column.no_wrap) for column in columns], 

550 max_width, 

551 ) 

552 table_width = sum(widths) 

553 # last resort, reduce columns evenly 

554 if table_width > max_width: 

555 excess_width = table_width - max_width 

556 widths = ratio_reduce(excess_width, [1] * len(widths), widths, widths) 

557 table_width = sum(widths) 

558 

559 width_ranges = [ 

560 self._measure_column(console, options.update_width(width), column) 

561 for width, column in zip(widths, columns) 

562 ] 

563 widths = [_range.maximum or 0 for _range in width_ranges] 

564 

565 if (table_width < max_width and self.expand) or ( 

566 self.min_width is not None and table_width < (self.min_width - extra_width) 

567 ): 

568 _max_width = ( 

569 max_width 

570 if self.min_width is None 

571 else min(self.min_width - extra_width, max_width) 

572 ) 

573 pad_widths = ratio_distribute(_max_width - table_width, widths) 

574 widths = [_width + pad for _width, pad in zip(widths, pad_widths)] 

575 

576 return widths 

577 

578 @classmethod 

579 def _collapse_widths( 

580 cls, widths: list[int], wrapable: list[bool], max_width: int 

581 ) -> list[int]: 

582 """Reduce widths so that the total is under max_width. 

583 

584 Args: 

585 widths (list[int]): List of widths. 

586 wrapable (list[bool]): List of booleans that indicate if a column may shrink. 

587 max_width (int): Maximum width to reduce to. 

588 

589 Returns: 

590 list[int]: A new list of widths. 

591 """ 

592 total_width = sum(widths) 

593 excess_width = total_width - max_width 

594 if any(wrapable): 

595 while total_width and excess_width > 0: 

596 max_column = max( 

597 width for width, allow_wrap in zip(widths, wrapable) if allow_wrap 

598 ) 

599 second_max_column = max( 

600 width if allow_wrap and width != max_column else 0 

601 for width, allow_wrap in zip(widths, wrapable) 

602 ) 

603 column_difference = max_column - second_max_column 

604 ratios = [ 

605 (1 if (width == max_column and allow_wrap) else 0) 

606 for width, allow_wrap in zip(widths, wrapable) 

607 ] 

608 if not any(ratios) or not column_difference: 

609 break 

610 max_reduce = [min(excess_width, column_difference)] * len(widths) 

611 widths = ratio_reduce(excess_width, ratios, max_reduce, widths) 

612 

613 total_width = sum(widths) 

614 excess_width = total_width - max_width 

615 return widths 

616 

617 def _get_cells( 

618 self, console: "Console", column_index: int, column: Column 

619 ) -> Iterable[_Cell]: 

620 """Get all the cells with padding and optional header.""" 

621 

622 collapse_padding = self.collapse_padding 

623 pad_edge = self.pad_edge 

624 padding = self.padding 

625 any_padding = any(padding) 

626 

627 first_column = column_index == 0 

628 last_column = column_index == len(self.columns) - 1 

629 

630 _padding_cache: dict[tuple[bool, bool], tuple[int, int, int, int]] = {} 

631 

632 def get_padding(first_row: bool, last_row: bool) -> tuple[int, int, int, int]: 

633 cached = _padding_cache.get((first_row, last_row)) 

634 if cached: 

635 return cached 

636 top, right, bottom, left = padding 

637 

638 if collapse_padding: 

639 if not first_column: 

640 left = max(0, left - right) 

641 if not last_row: 

642 bottom = max(0, top - bottom) 

643 

644 if not pad_edge: 

645 if first_column: 

646 left = 0 

647 if last_column: 

648 right = 0 

649 if first_row: 

650 top = 0 

651 if last_row: 

652 bottom = 0 

653 _padding = (top, right, bottom, left) 

654 _padding_cache[(first_row, last_row)] = _padding 

655 return _padding 

656 

657 raw_cells: list[tuple[StyleType, "RenderableType"]] = [] 

658 _append = raw_cells.append 

659 get_style = console.get_style 

660 if self.show_header: 

661 header_style = get_style(self.header_style or "") + get_style( 

662 column.header_style 

663 ) 

664 _append((header_style, column.header)) 

665 cell_style = get_style(column.style or "") 

666 for cell in column.cells: 

667 _append((cell_style, cell)) 

668 if self.show_footer: 

669 footer_style = get_style(self.footer_style or "") + get_style( 

670 column.footer_style 

671 ) 

672 _append((footer_style, column.footer)) 

673 

674 if any_padding: 

675 _Padding = Padding 

676 for first, last, (style, renderable) in loop_first_last(raw_cells): 

677 yield _Cell( 

678 style, 

679 _Padding(renderable, get_padding(first, last)), 

680 getattr(renderable, "vertical", None) or column.vertical, 

681 ) 

682 else: 

683 for style, renderable in raw_cells: 

684 yield _Cell( 

685 style, 

686 renderable, 

687 getattr(renderable, "vertical", None) or column.vertical, 

688 ) 

689 

690 def _get_padding_width(self, column_index: int) -> int: 

691 """Get extra width from padding.""" 

692 _, pad_right, _, pad_left = self.padding 

693 

694 if self.collapse_padding: 

695 pad_left = 0 

696 pad_right = abs(pad_left - pad_right) 

697 

698 if not self.pad_edge: 

699 if column_index == 0: 

700 pad_left = 0 

701 if column_index == len(self.columns) - 1: 

702 pad_right = 0 

703 

704 return pad_left + pad_right 

705 

706 def _measure_column( 

707 self, 

708 console: "Console", 

709 options: "ConsoleOptions", 

710 column: Column, 

711 ) -> Measurement: 

712 """Get the minimum and maximum width of the column.""" 

713 

714 max_width = options.max_width 

715 if max_width < 1: 

716 return Measurement(0, 0) 

717 

718 padding_width = self._get_padding_width(column._index) 

719 if column.width is not None: 

720 # Fixed width column 

721 return Measurement( 

722 column.width + padding_width, column.width + padding_width 

723 ).with_maximum(max_width) 

724 # Flexible column, we need to measure contents 

725 min_widths: list[int] = [] 

726 max_widths: list[int] = [] 

727 append_min = min_widths.append 

728 append_max = max_widths.append 

729 get_render_width = Measurement.get 

730 for cell in self._get_cells(console, column._index, column): 

731 _min, _max = get_render_width(console, options, cell.renderable) 

732 append_min(_min) 

733 append_max(_max) 

734 

735 measurement = Measurement( 

736 max(min_widths) if min_widths else 1, 

737 max(max_widths) if max_widths else max_width, 

738 ).with_maximum(max_width) 

739 measurement = measurement.clamp( 

740 None if column.min_width is None else column.min_width + padding_width, 

741 None if column.max_width is None else column.max_width + padding_width, 

742 ) 

743 return measurement 

744 

745 def _render( 

746 self, console: "Console", options: "ConsoleOptions", widths: list[int] 

747 ) -> "RenderResult": 

748 table_style = console.get_style(self.style or "") 

749 

750 border_style = table_style + console.get_style(self.border_style or "") 

751 _column_cells = ( 

752 self._get_cells(console, column_index, column) 

753 for column_index, column in enumerate(self.columns) 

754 ) 

755 

756 row_cells: list[tuple[_Cell, ...]] = list(zip(*_column_cells)) 

757 _box = ( 

758 self.box.substitute( 

759 options, safe=pick_bool(self.safe_box, console.safe_box) 

760 ) 

761 if self.box 

762 else None 

763 ) 

764 _box = _box.get_plain_headed_box() if _box and not self.show_header else _box 

765 

766 new_line = Segment.line() 

767 

768 columns = self.columns 

769 show_header = self.show_header 

770 show_footer = self.show_footer 

771 show_edge = self.show_edge 

772 show_lines = self.show_lines 

773 leading = self.leading 

774 

775 _Segment = Segment 

776 if _box: 

777 box_segments = [ 

778 ( 

779 _Segment(_box.head_left, border_style), 

780 _Segment(_box.head_right, border_style), 

781 _Segment(_box.head_vertical, border_style), 

782 ), 

783 ( 

784 _Segment(_box.mid_left, border_style), 

785 _Segment(_box.mid_right, border_style), 

786 _Segment(_box.mid_vertical, border_style), 

787 ), 

788 ( 

789 _Segment(_box.foot_left, border_style), 

790 _Segment(_box.foot_right, border_style), 

791 _Segment(_box.foot_vertical, border_style), 

792 ), 

793 ] 

794 if show_edge: 

795 yield _Segment(_box.get_top(widths), border_style) 

796 yield new_line 

797 else: 

798 box_segments = [] 

799 

800 get_row_style = self.get_row_style 

801 get_style = console.get_style 

802 

803 for index, (first, last, row_cell) in enumerate(loop_first_last(row_cells)): 

804 header_row = first and show_header 

805 footer_row = last and show_footer 

806 row = ( 

807 self.rows[index - show_header] 

808 if (not header_row and not footer_row) 

809 else None 

810 ) 

811 max_height = 1 

812 cells: list[list[list[Segment]]] = [] 

813 if header_row or footer_row: 

814 row_style = Style.null() 

815 else: 

816 row_style = get_style( 

817 get_row_style(console, index - 1 if show_header else index) 

818 ) 

819 for width, cell, column in zip(widths, row_cell, columns): 

820 render_options = options.update( 

821 width=width, 

822 justify=column.justify, 

823 no_wrap=column.no_wrap, 

824 overflow=column.overflow, 

825 height=None, 

826 highlight=column.highlight, 

827 ) 

828 lines = console.render_lines( 

829 cell.renderable, 

830 render_options, 

831 style=get_style(cell.style) + row_style, 

832 ) 

833 max_height = max(max_height, len(lines)) 

834 cells.append(lines) 

835 

836 row_height = max(len(cell) for cell in cells) 

837 

838 def align_cell( 

839 cell: list[list[Segment]], 

840 vertical: "VerticalAlignMethod", 

841 width: int, 

842 style: Style, 

843 ) -> list[list[Segment]]: 

844 if header_row: 

845 vertical = "bottom" 

846 elif footer_row: 

847 vertical = "top" 

848 

849 if vertical == "top": 

850 return _Segment.align_top(cell, width, row_height, style) 

851 elif vertical == "middle": 

852 return _Segment.align_middle(cell, width, row_height, style) 

853 return _Segment.align_bottom(cell, width, row_height, style) 

854 

855 cells[:] = [ 

856 _Segment.set_shape( 

857 align_cell( 

858 cell, 

859 _cell.vertical, 

860 width, 

861 get_style(_cell.style) + row_style, 

862 ), 

863 width, 

864 max_height, 

865 ) 

866 for width, _cell, cell, column in zip(widths, row_cell, cells, columns) 

867 ] 

868 

869 if _box: 

870 if last and show_footer: 

871 yield _Segment( 

872 _box.get_row(widths, "foot", edge=show_edge), border_style 

873 ) 

874 yield new_line 

875 left, right, _divider = box_segments[0 if first else (2 if last else 1)] 

876 

877 # If the column divider is whitespace also style it with the row background 

878 divider = ( 

879 _divider 

880 if _divider.text.strip() 

881 else _Segment( 

882 _divider.text, row_style.background_style + _divider.style 

883 ) 

884 ) 

885 for line_no in range(max_height): 

886 if show_edge: 

887 yield left 

888 for last_cell, rendered_cell in loop_last(cells): 

889 yield from rendered_cell[line_no] 

890 if not last_cell: 

891 yield divider 

892 if show_edge: 

893 yield right 

894 yield new_line 

895 else: 

896 for line_no in range(max_height): 

897 for rendered_cell in cells: 

898 yield from rendered_cell[line_no] 

899 yield new_line 

900 if _box and first and show_header: 

901 yield _Segment( 

902 _box.get_row(widths, "head", edge=show_edge), border_style 

903 ) 

904 yield new_line 

905 end_section = row and row.end_section 

906 if _box and (show_lines or leading or end_section): 

907 if ( 

908 not last 

909 and not (show_footer and index >= len(row_cells) - 2) 

910 and not (show_header and header_row) 

911 ): 

912 if leading: 

913 yield _Segment( 

914 _box.get_row(widths, "mid", edge=show_edge) * leading, 

915 border_style, 

916 ) 

917 else: 

918 yield _Segment( 

919 _box.get_row(widths, "row", edge=show_edge), border_style 

920 ) 

921 yield new_line 

922 

923 if _box and show_edge: 

924 yield _Segment(_box.get_bottom(widths), border_style) 

925 yield new_line 

926 

927 

928if __name__ == "__main__": # pragma: no cover 

929 from rich.console import Console 

930 from rich.highlighter import ReprHighlighter 

931 

932 from ._timer import timer 

933 

934 with timer("Table render"): 

935 table = Table( 

936 title="Star Wars Movies", 

937 caption="Rich example table", 

938 caption_justify="right", 

939 ) 

940 

941 table.add_column( 

942 "Released", header_style="bright_cyan", style="cyan", no_wrap=True 

943 ) 

944 table.add_column("Title", style="magenta") 

945 table.add_column("Box Office", justify="right", style="green") 

946 

947 table.add_row( 

948 "Dec 20, 2019", 

949 "Star Wars: The Rise of Skywalker", 

950 "$952,110,690", 

951 ) 

952 table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347") 

953 table.add_row( 

954 "Dec 15, 2017", 

955 "Star Wars Ep. V111: The Last Jedi", 

956 "$1,332,539,889", 

957 style="on black", 

958 end_section=True, 

959 ) 

960 table.add_row( 

961 "Dec 16, 2016", 

962 "Rogue One: A Star Wars Story", 

963 "$1,332,439,889", 

964 ) 

965 

966 def header(text: str) -> None: 

967 console.print() 

968 console.rule(highlight(text)) 

969 console.print() 

970 

971 console = Console() 

972 highlight = ReprHighlighter() 

973 header("Example Table") 

974 console.print(table, justify="center") 

975 

976 table.expand = True 

977 header("expand=True") 

978 console.print(table) 

979 

980 table.width = 50 

981 header("width=50") 

982 

983 console.print(table, justify="center") 

984 

985 table.width = None 

986 table.expand = False 

987 table.row_styles = ["dim", "none"] 

988 header("row_styles=['dim', 'none']") 

989 

990 console.print(table, justify="center") 

991 

992 table.width = None 

993 table.expand = False 

994 table.row_styles = ["dim", "none"] 

995 table.leading = 1 

996 header("leading=1, row_styles=['dim', 'none']") 

997 console.print(table, justify="center") 

998 

999 table.width = None 

1000 table.expand = False 

1001 table.row_styles = ["dim", "none"] 

1002 table.show_lines = True 

1003 table.leading = 0 

1004 header("show_lines=True, row_styles=['dim', 'none']") 

1005 console.print(table, justify="center")