Skip to content Skip to sidebar Skip to footer

How Can I List All Registered Arguments From An ArgumentParser Instance?

Couldn't find any existing method for it so I wonder if there is a hack?

Solution 1:

There is a hack; you can list all registered actions using the undocumented attribute parser._actions:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('--bar')
_StoreAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('spam')
_StoreAction(option_strings=[], dest='spam', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('eggs')
_StoreAction(option_strings=[], dest='eggs', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser._actions
[_HelpAction(option_strings=['-h', '--help'], dest='help', nargs=0, const=None, default='==SUPPRESS==', type=None, choices=None, help='show this help message and exit', metavar=None), _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None), _StoreAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None), _StoreAction(option_strings=[], dest='spam', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None), _StoreAction(option_strings=[], dest='eggs', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)]

Using the attribute is at your own risk; these internals are subject to change in future versions.


Post a Comment for "How Can I List All Registered Arguments From An ArgumentParser Instance?"