| 1 |
|
| 2 |
"""Demonstrates using CompletionItem instances as elements in an argparse choices list. |
| 3 |
|
| 4 |
Technical Note: |
| 5 |
Using 'choices' is best for fixed datasets that do not change during the |
| 6 |
application's lifecycle. For dynamic data (e.g., results from a database or |
| 7 |
file system), use a 'choices_provider' instead. |
| 8 |
|
| 9 |
Key strengths of this approach: |
| 10 |
1. Command handlers receive fully-typed domain objects directly in the |
| 11 |
argparse.Namespace, eliminating manual lookups from string keys. |
| 12 |
2. Choices carry tab-completion UI enhancements (display_meta, table_data) |
| 13 |
that are not supported by standard argparse string choices. |
| 14 |
3. Provides a single source of truth for completion UI, input validation, |
| 15 |
and object mapping. |
| 16 |
|
| 17 |
This demo showcases two distinct approaches: |
| 18 |
1. Simple: Using CompletionItems with basic types (ints) to add UI metadata |
| 19 |
(display_meta) while letting argparse handle standard type conversion. |
| 20 |
2. Advanced: Using a custom 'text' alias and a type converter to map a friendly |
| 21 |
string (e.g., 'alice') directly to a complex object (Account). |
| 22 |
""" |
| 23 |
|
| 24 |
import argparse |
| 25 |
import sys |
| 26 |
from typing import ( |
| 27 |
ClassVar, |
| 28 |
cast, |
| 29 |
) |
| 30 |
|
| 31 |
from cmd2 import ( |
| 32 |
Cmd, |
| 33 |
Cmd2ArgumentParser, |
| 34 |
CompletionItem, |
| 35 |
with_argparser, |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
id_choices = [ |
| 44 |
CompletionItem(101, display_meta="Alice's Account"), |
| 45 |
CompletionItem(202, display_meta="Bob's Account"), |
| 46 |
] |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
class Account: |
| 53 |
"""A complex object that we want to select by a friendly name.""" |
| 54 |
|
| 55 |
def __init__(self, account_id: int, owner: str) -> None: |
| 56 |
self.account_id = account_id |
| 57 |
self.owner = owner |
| 58 |
|
| 59 |
def __eq__(self, other: object) -> bool: |
| 60 |
if isinstance(other, Account): |
| 61 |
return self.account_id == other.account_id |
| 62 |
return False |
| 63 |
|
| 64 |
def __hash__(self) -> int: |
| 65 |
return hash(self.account_id) |
| 66 |
|
| 67 |
def __repr__(self) -> str: |
| 68 |
return f"Account(id={self.account_id}, owner='{self.owner}')" |
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
accounts = [ |
| 74 |
Account(101, "Alice"), |
| 75 |
Account(202, "Bob"), |
| 76 |
] |
| 77 |
account_choices = [ |
| 78 |
CompletionItem( |
| 79 |
acc, |
| 80 |
text=acc.owner.lower(), |
| 81 |
display_meta=f"ID: {acc.account_id}", |
| 82 |
) |
| 83 |
for acc in accounts |
| 84 |
] |
| 85 |
|
| 86 |
|
| 87 |
def account_lookup(name: str) -> Account: |
| 88 |
"""Type converter that looks up an Account by its friendly name.""" |
| 89 |
for item in account_choices: |
| 90 |
if item.text == name: |
| 91 |
return cast(Account, item.value) |
| 92 |
raise argparse.ArgumentTypeError(f"invalid account: {name}") |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
class ChoicesDemo(Cmd): |
| 99 |
"""Demo cmd2 application.""" |
| 100 |
|
| 101 |
DEFAULT_CATEGORY: ClassVar[str] = "Demo Commands" |
| 102 |
|
| 103 |
def __init__(self) -> None: |
| 104 |
super().__init__() |
| 105 |
self.intro = ( |
| 106 |
"Welcome to the CompletionItem Choices Demo!\n" |
| 107 |
"Try 'simple' followed by [TAB] to see basic metadata.\n" |
| 108 |
"Try 'advanced' followed by [TAB] to see custom string mapping." |
| 109 |
) |
| 110 |
|
| 111 |
|
| 112 |
simple_parser = Cmd2ArgumentParser() |
| 113 |
simple_parser.add_argument( |
| 114 |
"account_id", |
| 115 |
type=int, |
| 116 |
choices=id_choices, |
| 117 |
help="Select an account ID (tab-complete to see metadata)", |
| 118 |
) |
| 119 |
|
| 120 |
@with_argparser(simple_parser) |
| 121 |
def do_simple(self, args: argparse.Namespace) -> None: |
| 122 |
"""Show an account ID selection (Simple Case).""" |
| 123 |
|
| 124 |
self.poutput(f"Selected Account ID: {args.account_id} (Type: {type(args.account_id).__name__})") |
| 125 |
|
| 126 |
|
| 127 |
advanced_parser = Cmd2ArgumentParser() |
| 128 |
advanced_parser.add_argument( |
| 129 |
"account", |
| 130 |
type=account_lookup, |
| 131 |
choices=account_choices, |
| 132 |
help="Select an account by owner name (tab-complete to see friendly names)", |
| 133 |
) |
| 134 |
|
| 135 |
@with_argparser(advanced_parser) |
| 136 |
def do_advanced(self, args: argparse.Namespace) -> None: |
| 137 |
"""Show a custom string selection (Advanced Case).""" |
| 138 |
|
| 139 |
self.poutput(f"Selected Account: {args.account!r} (Type: {type(args.account).__name__})") |
| 140 |
|
| 141 |
|
| 142 |
if __name__ == "__main__": |
| 143 |
app = ChoicesDemo() |
| 144 |
sys.exit(app.cmdloop()) |