liveBook · Manning

Option

As explained in Practices of the Python Pro

Option is a book-specific class that associates a menu description with a command and optional input-preparation behavior.

Option associates a menu description with a command and optional input-preparation behavior. It keeps the CLI menu focused on presentation while commands handle business logic. section 6.3.3

An Option coordinates a menu choice in four steps:

  • Stores the displayed name, command object, and optional preparation callback. section 6.3.3
  • Runs the preparation callback when user input is needed, such as bookmark data or an identifier. section 6.3.3
  • Passes prepared data to command.execute(), or executes the command without data. section 6.3.3
  • Prints the command’s returned message and represents itself with its menu name. section 6.3.3

Bookmark menu options

A menu can map A to Option('Add a bookmark', AddBookmarkCommand(), prep_call=get_new_bookmark_data), B to a date-ordered listing command, and T to the same command configured for title order. The menu prints each Option’s name, then calls choose() for the selected item. section 6.3.3

Listing 6.11. Connecting menu text to business logic commands
class Option:
    def __init__(self, name, command, prep_call=None):
        self.name = name                                     #1
        self.command = command                               #2
        self.prep_call = prep_call                           #3


    def choose(self):                                        #4
        data = self.prep_call() if self.prep_call else None  #5
        message = self.command.execute(data) if data
else self.command.execute()                                #6
        print(message)

    def __str__(self):                                       #7
        return self.name

Inspect the compact implementation showing stored configuration, optional preparation, command dispatch, output, and string conversion. section 6.3.3

How Practices of the Python Pro covers it

How deep it goes
Defines attributes and execution flow, then demonstrates configuration and input callbacks without descending into command internals.
Examples
Uses bookmark creation, date and title listing, deletion, quitting, and callbacks that gather bookmark data or deletion identifiers.
What it assumes
Assumes command objects provide execute(), while demonstrating menu construction, callbacks, and input validation directly.
What you can do after
Build it from scratch to configure menu entries that collect optional input and invoke commands through a Python CLI.
How it connects
Ties menu options to commands, the presentation layer, user input, and loose coupling between application layers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.