Tables and Menus

The TableItem and Table support text-based tables and menus in cooked_input.

Note

Using the Table class is for more advanced users, Beginners can just use the get_menu() and get_table_input() convenience functions.

TableStyle:

class cooked_input.TableStyle(show_cols=True, show_border=True, hrules=0, vrules=1, rows_per_page=20)

TableStyle is used to define the visual style of a Cooked_Input table. Table objects take an instance of TableStyle as the style parameter.

Parameters:
  • show_cols (Bool) – if True (default) shows a the column names at the top of the table
  • show_border (Bool) – if True (default) shows a border around the table
  • hrules – whether to draw horizontal lines between rows. See below for allowed RULE values.
  • vrules – whether to draw vertical lines between rows. See below for allowed RULE values.
  • rows_per_page (int) – The maximum number of rows to display in the table. Used for paginated tables (None for no maximum).

hrules and vrules can use the following RULE values for the rows and columns respectively:

value action
RULE_FRAME RULE_HEADER RULE_ALL RULE_NONE Draw ruled lines around the outside (frame) of the table. Draw ruled lines around the header of the table. Draw ruled line around the table, header and between columns/rows. Do not draw any rules lines around columns/rows.

TableItem:

class cooked_input.TableItem(col_values, tag=None, action='default', item_data=None, hidden=False, enabled=True)

TableItem is used to represent individual rows in a table. This is also often used for menu items.

Parameters:
  • col_values (List) – A list of values for the row’s columns.
  • tag – a value used to choose the item. If None, a default tag will be assigned by the Table.
  • action (Callable) – an action function called when the item is selected.
  • item_data (Dict) – a dictionary containing addtional contextual data for the table row. This is not displayed as part of the table item but can be used for processing actions. For example, item_data can store the database ID associated for the item. item_data is also used for item filters.
  • hidden (bool) – The table row is hidden if True, or visible if False (default). Hidden table items are still selectable, unless the enabled attribute is False.
  • enabled (bool) – The table row is selectable if True **(default), and not selectable if **False.

TableItem actions:

The table item action specifies what to do when a table item is selected. The action can be one of the default actions listed in the following table or a custom action can be provided:

value action
TABLE_RETURN_TAG return the selected row’s tag.
TABLE_RETURN_FIRST_VAL return the first data column value of the selected row.
TABLE_RETURN_ROW return the list of column values for the selected row.
TABLE_RETURN_TABLE_ITEM return the TableItem instance for the selected row.
TABLE_ITEM_DEFAULT use default method to handle the table item (e.g. use the parent table’s default_action handler function)
TABLE_ITEM_EXIT selecting the table row should exit (used to exit a menu)
TABLE_ITEM__RETURN selecting the table row should return (used to return from a submenu)

In addition to the values in the table above, the action can be any callable that takes the following parameters:

  • row (TableItem) – The TableItem instance selected (i.e. this table item)
  • action_dict (Dict) – The parent table’s action_dict.

Table:

class cooked_input.Table(rows, col_names=None, title=None, prompt=None, default_choice=None, default_str=None, default_action=None, style=None, **options)

The Table class is used to display a table of data. Each row of data has the same number of columns (specified by the col_name parameter) as is represented by a TableItem instance. Tables are often used for menus.

Parameters:
  • rows (List) – The rows of the table. Each row is a TableItem instance.
  • col_names (List) – An optional list of the column names (strings) for the table. If no list is given the number of columns is determined by the length of the data list for the first row (TableItem).
  • title (str) – An optional title for the table.
  • prompt (str) – The prompt for choosing a table value.
  • default_choice (str) – An optional default tag value to use for the table selection.
  • default_str (str) – An optional string to display for the default table selection.
  • default_action (Callable) – The default action function to call a table item is selected. See below for details.
  • style (TableStyle) – a TableStyle defining the look of the table.
  • options (Dict) – see below for a list of valid options

Options:

required: requires an entry if True, exits the table on blank entry if False.

tag_str: string to use for the tag column name. Defaults to an empty string (“”).

add_exit: automatically adds a TableItem to exit the table menu (TABLE_ITEM_EXIT) or
return to the parent table/menu (TABLE_ADD_RETURN), or not to add a TableItem at all (False). Used to exit menus or return from sub-menus.
action_dict: a dictionary of values to pass to action functions. Used to provide context to
the action. Helpful to provide items such as data base sessions, user credentials, etc.

case_sensitive: whether choosing table items should be case sensitive (True) or not (False - default)

commands: a dictionary of commands for the table. For each entry, the key is the command and the
value the action to take for the command. See GetInput and GetInputCommand for further details
item_filter: a function used to determine which table items to display. Displays all items if None.
See below for more details.
refresh: refresh table items each time the table is shown (True - default), or just when created
(False). Useful for dynamic tables
header: a format string to print before the table, can use any value from action_dict as well as
pagination information
footer: a format string to print after the table, can use any values from action_dict as well as
pagination information

Table default actions:

Each table has a default action to take when an item is selected. The action can be a callable or a value from the table below. The Table’s default action is called if the If the selected row (TableItem) has its action set to TABLE_DEFAULT_ACTION, otherwise the action for the selected TableItem is called. Standard values for the Table default action are:

value action
TABLE_RETURN_TAG return the selected row’s tag.
TABLE_RETURN_FIRST_VAL return the first data column value of the selected row.
TABLE_RETURN_ROW return the list of column values for the selected row.
TABLE_RETURN_TABLE_ITEM return the TableItem instance for the selected row.

In addition to the values in the table above, the action can be any callable that takes the following parameters:

  • row (TableItem) – The TableItem instance selected (i.e. this table item)
  • action_dict (Dict) – The parent table’s action_dict.

For example:

def reverse_tag_action(row, action_dict):
    if action_dict['reverse'] is True:
        return row.tag[::-1]
    else
        return row.tag

item filters:

The item filter option provides a function that determines which table items are hidden and/or enabled in the table. It is a callable that takes the following input parameters:

  • item (TableItem) – the TableItem instance
  • action_dict (Dict) – the action_dict for the Table

The item_filter function returns a tuple of two Booleans (hidden, enabled) for the item (TableItem).

For example, a menu can have choices that are visible and enabled only for user’s who are part of the administrator group:

def user_role_filter(row, action_dict):
    if row.item_data is None:
        return  (False, True)   # visible and enabled

    for role in action_dict['user_roles'].roles:
        if role in row.item_data['roles']:
            return  (False, True)   # visible and enabled

    return (True, False)    # hidden and disabled

action_dict = {'user_roles': ['admin', 'users']}
admin_only = {'roles': {'admin'} }

rows = [
    TableItem('Add a new user', action=user_add_action, item_data=admin_only)
    TableItem('list users', action=user_list_action) ]
menu = Table(menu_items=rows, action_dict=action_dict, item_filter=user_role_filter)
Table.show_table()

Show the table without asking for input.

Returns:None
Table.get_table_choice(**options)

Prompts the user to choose a value from the table. This is the main method used to choose a value from a table.

Parameters:options – See below for details.
Returns:the result of performing the action (specified by the table or row) on the row. Returns None if no row is selected.

Options:

  • prompt (str) – the prompt for choosing a table value.
  • required (bool) – requires an entry if True, exits the table on blank entry if False.
  • default (str) – the default value to use.
  • default_str (str) – An optional string to display for the default table selection.
  • commands (Dict) – a dictionary of commands for the table. For each entry, the key is the
    command and the value the action to take for the command. See GetInput and GetInputCommand for further details
Table.run()
Continue to get input from the table until a blank row (None) is returned, or a GetInputInterrupt
exception is raised. This is primarily used to use tables as menus. Choosing exit or return in a menu is the same as returning no row.
Returns:True if exited without an error, or False if a GetInputInterrupt exce[tion was raised
Table.get_num_rows()

Get the number of rows in the table.

Returns:the number of rows in the table
Return type:int
Table.get_row(tag)

Get the number of rows in the table.

Returns:the number of rows in the table
Return type:TableItem
Table.get_action(tag)

Return the action callback function for the first row matching the specified tag.

Parameters:tag – the tag to search for
Returns:the action for the first row containing the tag. Raises a ValueError exception if the tag is not found
Return type:Callable
Table.do_action(row)

Call the action function for the specified row

Parameters:row (TableItem) – the table row to call the action on
Returns:returns the return value for the action. Returns the original row if no action is defined for the row.

The action function is called with the following parameters:

  • row – The TableItem instance selected (i.e. this table item)
Table.show_rows(start_row)

Set the starting row for to display in the table. Last row shown is the start_row plus the number of rows per page (or the last row if start_row is within rows_per_page of the end of the table).

Parameters:start_row (int) – the first row of the table to show
Returns:None
Table.page_up()

Display the previous page of the table (if available)

Returns:None
Table.page_down()

Display the next page of the table (if available)

Returns:None
Table.goto_home()

Display the first page of the table

Returns:None
Table.goto_end()

Display the last page of the table

Returns:None
Table.scroll_up_one_row()

Display the one row earlier in the table (if available)

Returns:None
Table.scroll_down_one_row()

Display the one row later in the table (if available)

Returns:None
Table.refresh_screen()

Display the current page of the table (including any header or footer)

Returns:None
Table.refresh_items(rows=None, add_exit=False, item_filter=None)

Refresh which rows of the table are enabled and shown. Used to update rows in the table. Adds tags if necessary. formatter is used so values can be substituted in format strings from action_dict using vformat. This is useful in case some TableItems have dynamic data. Can also be used by action to change table items. For instance a search action might filter for row entries using an item filter.

Parameters:
  • rows (List) – a list of rows to show. If None, will use all rows.
  • add_exit (bool) – if TABLE_ADD_EXIT add an entry to exit, if TABLE_ADD_RETURN add an entry to return. Don’t add an entry if False (default).
  • item_filter (Callable) – an optional function used to filter rows. See Table for details regarding item filters.
Returns:

None

Table Action Functions:

The following pre-defined action functions can be used for the action for Table and TableItem:

return_table_item_action

cooked_input.return_table_item_action(row, action_dict)

Action function for Tables. This function returns the TableItem instance. Used by the TABLE_RETURN_TABLE_ITEM action.

Parameters:
  • row (List) – the data associated with the selected row
  • action_dict (Dict) – the dictionary of values associated with the action - ignored in this function
Returns:

A list containing all of the data for the selected row of the table.

Return type:

List

return_row_action

cooked_input.return_row_action(row, action_dict)

Default action function for Tables. This function returns the whole row of data including the tag. Used by the TABLE_RETURN_ROW action.

Parameters:
  • row (List) – the data associated with the selected row
  • action_dict (Dict) – the dictionary of values associated with the action - ignored in this function
Returns:

A list containing all of the data values for the selected row of the table.

Return type:

List

return_tag_action

cooked_input.return_tag_action(row, action_dict)

Default action function for tables. This function returns the tag for the row of data. Used by the TABLE_RETURN_TAG action.

Parameters:
  • row (List) – the data associated with the selected row
  • action_dict (Dict) – the dictionary of values associated with the action - ignored in this function
Returns:

The tag for the selected row of the table.

return_first_col_action

cooked_input.return_first_col_action(row, action_dict)
Default action function for tables. This function returns the first data column value for the row of
data. Used by the TABLE_RETURN_FIRST_VAL action.
Parameters:
  • row (List) – the data associated with the selected row
  • action_dict (Dict) – the dictionary of values associated with the action - ignored in this function
Returns:

The first value from the list of data values for the selected row of the table.