|
11 | 11 | WARNING: This example requires the tableformatter module: https://github.com/python-tableformatter/tableformatter |
12 | 12 | - pip install tableformatter |
13 | 13 | """ |
14 | | -import argparse |
15 | 14 | from typing import Tuple |
16 | 15 |
|
17 | 16 | import cmd2 |
@@ -142,6 +141,21 @@ def high_density_objs(row_obj: CityInfo) -> dict: |
142 | 141 | return opts |
143 | 142 |
|
144 | 143 |
|
| 144 | +def make_table_parser() -> cmd2.argparse_completer.ACArgumentParser: |
| 145 | + """Create a unique instance of an argparse Argument parser for processing table arguments. |
| 146 | +
|
| 147 | + NOTE: The two cmd2 argparse decorators require that each parser be unique, even if they are essentially a deep copy |
| 148 | + of each other. For cases like that, you can create a function to return a unique instance of a parser, which is |
| 149 | + what is being done here. |
| 150 | + """ |
| 151 | + table_parser = cmd2.argparse_completer.ACArgumentParser() |
| 152 | + table_item_group = table_parser.add_mutually_exclusive_group() |
| 153 | + table_item_group.add_argument('-c', '--color', action='store_true', help='Enable color') |
| 154 | + table_item_group.add_argument('-f', '--fancy', action='store_true', help='Fancy Grid') |
| 155 | + table_item_group.add_argument('-s', '--sparse', action='store_true', help='Sparse Grid') |
| 156 | + return table_parser |
| 157 | + |
| 158 | + |
145 | 159 | class TableDisplay(cmd2.Cmd): |
146 | 160 | """Example cmd2 application showing how you can display tabular data.""" |
147 | 161 |
|
@@ -169,18 +183,12 @@ def ptable(self, rows, columns, grid_args, row_stylist): |
169 | 183 | formatted_table = tf.generate_table(rows=rows, columns=columns, grid_style=grid, row_tagger=row_stylist) |
170 | 184 | self.ppaged(formatted_table, chop=True) |
171 | 185 |
|
172 | | - table_parser = argparse.ArgumentParser() |
173 | | - table_item_group = table_parser.add_mutually_exclusive_group() |
174 | | - table_item_group.add_argument('-c', '--color', action='store_true', help='Enable color') |
175 | | - table_item_group.add_argument('-f', '--fancy', action='store_true', help='Fancy Grid') |
176 | | - table_item_group.add_argument('-s', '--sparse', action='store_true', help='Sparse Grid') |
177 | | - |
178 | | - @cmd2.with_argparser(table_parser) |
| 186 | + @cmd2.with_argparser(make_table_parser()) |
179 | 187 | def do_table(self, args): |
180 | 188 | """Display data in iterable form on the Earth's most populated cities in a table.""" |
181 | 189 | self.ptable(EXAMPLE_ITERABLE_DATA, COLUMNS, args, high_density_tuples) |
182 | 190 |
|
183 | | - @cmd2.with_argparser(table_parser) |
| 191 | + @cmd2.with_argparser(make_table_parser()) |
184 | 192 | def do_object_table(self, args): |
185 | 193 | """Display data in object form on the Earth's most populated cities in a table.""" |
186 | 194 | self.ptable(EXAMPLE_OBJECT_DATA, OBJ_COLS, args, high_density_objs) |
|
0 commit comments