Skip to content

Commit 55fcbda

Browse files
committed
Use match/case for per-column table styling
1 parent 1992ccc commit 55fcbda

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

examples/rich_tables.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -90,30 +90,31 @@ def do_countries(self, _: cmd2.Statement) -> None:
9090
table.caption = "Data from https://worldpopulationreview.com/ and Wikipedia"
9191

9292
for header in COUNTRY_HEADERS:
93-
justify = "left"
94-
if any(term in header for term in ['Population', 'Density', 'GDP']):
95-
justify = "right"
96-
if 'Area' in header:
97-
justify = "center"
98-
table.add_column(header, justify=justify)
93+
match header:
94+
case s if "2025 Population" in s:
95+
justify = "right"
96+
header_style = Color.BRIGHT_BLUE
97+
style = Color.BLUE
98+
case s if "Density" in s:
99+
justify = "right"
100+
header_style = Color.BRIGHT_RED
101+
style = Color.RED
102+
case s if "per capita" in s:
103+
justify = "right"
104+
header_style = Color.BRIGHT_GREEN
105+
style = Color.GREEN
106+
case _:
107+
justify = "left"
108+
style = None
109+
header_style = None
110+
111+
table.add_column(header, justify=justify, header_style=header_style, style=style)
99112

100113
for row in COUNTRY_DATA:
101114
# Convert integers or floats to strings, since rich tables can not render int/float
102115
str_row = [f"{item:,}" if isinstance(item, int) else str(item) for item in row]
103116
table.add_row(*str_row)
104117

105-
# Make Population column blue
106-
table.columns[2].header_style = Color.BRIGHT_BLUE
107-
table.columns[2].style = Color.BLUE
108-
109-
# Make Density column red
110-
table.columns[4].header_style = Color.BRIGHT_RED
111-
table.columns[4].style = Color.RED
112-
113-
# Make GDB per capita column green
114-
table.columns[6].header_style = Color.BRIGHT_GREEN
115-
table.columns[6].style = Color.GREEN
116-
117118
self.poutput(table)
118119

119120

0 commit comments

Comments
 (0)