From: Plom Heller Date: Mon, 27 Jul 2026 20:01:40 +0000 (+0200) Subject: Improve argparse usage structuring, TABLE choices usage help. X-Git-Url: https://plomlompom.com/repos/%22https:/validator.w3.org/task?a=commitdiff_plain;h=1a3c28dbaa59756b13db6da06b905dfa442ac8c4;p=bricksplom Improve argparse usage structuring, TABLE choices usage help. --- diff --git a/bricksplom.py b/bricksplom.py index 21264f2..36be587 100755 --- a/bricksplom.py +++ b/bricksplom.py @@ -1,7 +1,11 @@ #!/usr/bin/env python3 'Data structures for managing/sorting bricks of a certain kind.' from abc import ABC, abstractmethod -from argparse import ArgumentError, ArgumentParser +from argparse import ( + ArgumentError, + ArgumentParser, + Namespace as ArgumentNamespace, + ) from dataclasses import dataclass from os import environ from pathlib import Path @@ -812,30 +816,40 @@ class BricksDb: def main( ) -> None: 'Load tables from BRICKSPLOM_DIR and put out in reproducible listings.' - def add_abbrev_choices_arg( - parser: ArgumentParser, - argname: str, - choices: set[str] - ) -> None: - def complete( - arg: str - ) -> str: - candidates = tuple(c for c in choices if c.startswith(arg)) - if len(candidates) > 1: - raise ArgumentError( - action, - f'{arg} – ambiguous, could match: {", ".join(candidates)}') - return (candidates + (arg, ))[0] - action = parser.add_argument(argname, choices=choices, type=complete) - - parser = ArgumentParser() - add_abbrev_choices_arg(parser, 'table', set(BricksDb.lookupable)) - parser.add_argument('item_id', nargs='?', metavar='ITEM_ID') - parser.add_argument('-r', '--raw', action='store_true') - parser.add_argument('-m', '--match-by', action='store') - parser.add_argument('-s', '--sort-by', action='store', default=TOK_SORT_ID) - parser.add_argument('-l', '--ldraw', action='store', default='') - args = parser.parse_args() + def parse_args( + ) -> ArgumentNamespace: + def add_abbreviable_table_arg( + ) -> None: + def complete( + arg: str + ) -> str: + candidates = tuple(c for c in choices if c.startswith(arg)) + if len(candidates) > 1: + raise ArgumentError( + action, + f'{arg} – ambiguous, matches: {", ".join(candidates)}') + return (candidates + (arg, ))[0] + choices = BricksDb.lookupable + msg = 'one of: ' + ', '.join(sorted(list(choices))) + msg += '; NB: abbreviable to first unambiguous character sequence' + action = parser.add_argument( + 'table', + choices=choices, type=complete, metavar='TABLE', help=msg) + parser = ArgumentParser() + add_abbreviable_table_arg() + parser.add_argument('item_id', + nargs='?', metavar='ITEM_ID') + parser.add_argument('-r', '--raw', + action='store_true') + parser.add_argument('-m', '--match-by', + action='store') + parser.add_argument('-s', '--sort-by', + action='store', default=TOK_SORT_ID) + parser.add_argument('-l', '--ldraw', + action='store', default='') + return parser.parse_args() + + args = parse_args() db = BricksDb(environ.get(NAME_ENV_DIRNAME, '.'), environ.get(NAME_ENV_LDRAW, ''), args.ldraw)