-
How do I pass an object to a Cmd2ArgumentParser() constructor so that it or one of its subparsers may refer to it, for example, via the use of a "choices_provider=" argument to a parser argument? I am using the @cmd2.with_argparser decorator. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
You should be passing a fully constructed Cmd2ArgumentParser to the |
Beta Was this translation helpful? Give feedback.
-
Hello @anselor -- thank you for your explanation, but I'm afraid I don't follow. Let me try to explain as concisely as possible what I am seeking to do and you can laugh or sigh as appropriate. I have an class InteractiveShell( cmd2.cmd ):
def __init__( self, *args, **kwargs ):
super().__init__( *args, **kwargs )
self._settings = Settings()
self._model = Model()
@cmd2.with_argparser( settings_argparser, ns_provider=ns_provider )
def do_settings( self, args: argparse.Namespace ):
do_settings( args )
def do_settings( args: argparse.Namespace ):
log.info( f'{args=}' ) Also, How and when should I construct Right now I have settings_argparser = cmd2.Cmd2ArgumentParser( add_help=False )
settings_subparsers = settings_argparser.add_subparsers( dest='action' )
list_parser = settings_subparsers.add_parser( 'list' )
list_parser.add_argument( 'what', choices={ 'packages', 'systems' } )
list_parser = settings_subparsers.add_parser( 'load' ) ...but what I really want to do is pass a property on an instance of Am I doing this completely wrongly? |
Beta Was this translation helpful? Give feedback.
Ah, so what we have here is an order of operations issue with how I originally implemented the argparse registration.
The
cmd2.with_argparser()
command decorators are executed during module load as the class definition is executed. The model instance doesn't exist until much later when you're instantiating the class. It is, therefore, impossible to pass anything on the cmd2 instance to the argparser or the decorator.Pull Request #1278 may interest you as it is adds the ability to provide a factory function that is called when the cmd2 instance is created and therefore allows for future access to instance-specific attributes.
In the near-term there is a work-around you can do. You can def…