@@ -284,6 +284,7 @@ def get_items(self) -> list[CompletionItems]:
284284from .completion import (
285285 ChoicesProviderUnbound ,
286286 CompleterUnbound ,
287+ CompletionItem ,
287288)
288289from .rich_utils import Cmd2RichArgparseConsole
289290from .styles import Cmd2Style
@@ -901,6 +902,34 @@ def _ArgumentParser_set_ap_completer_type(self: argparse.ArgumentParser, ap_comp
901902setattr (argparse .ArgumentParser , 'set_ap_completer_type' , _ArgumentParser_set_ap_completer_type )
902903
903904
905+ ############################################################################################################
906+ # Patch ArgumentParser._check_value to support CompletionItems as choices
907+ ############################################################################################################
908+ def _ArgumentParser_check_value (_self : argparse .ArgumentParser , action : argparse .Action , value : Any ) -> None : # noqa: N802
909+ """Check_value that supports CompletionItems as choices (Custom override of ArgumentParser._check_value).
910+
911+ When displaying choices, use CompletionItem.value instead of the CompletionItem instance.
912+
913+ :param self: ArgumentParser instance
914+ :param action: the action being populated
915+ :param value: value from command line already run through conversion function by argparse
916+ """
917+ # Import gettext like argparse does
918+ from gettext import (
919+ gettext as _ ,
920+ )
921+
922+ if action .choices is not None and value not in action .choices :
923+ # If any choice is a CompletionItem, then display its value property.
924+ choices = [c .value if isinstance (c , CompletionItem ) else c for c in action .choices ]
925+ args = {'value' : value , 'choices' : ', ' .join (map (repr , choices ))}
926+ msg = _ ('invalid choice: %(value)r (choose from %(choices)s)' )
927+ raise ArgumentError (action , msg % args )
928+
929+
930+ setattr (argparse .ArgumentParser , '_check_value' , _ArgumentParser_check_value )
931+
932+
904933############################################################################################################
905934# Patch argparse._SubParsersAction to add remove_parser function
906935############################################################################################################
0 commit comments