Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python Argument Parsing Inheritance
import argparse
import sys
class Command(object):
def __init__(self):
self._argument_parser = argparse.ArgumentParser()
def main(self, args):
self._main(self._argument_parser.parse_args(args))
class CommandCommon(Command):
def __init__(self):
super(CommandCommon, self).__init__()
self._argument_parser.add_argument('-x')
class CommandAdd(CommandCommon):
def __init__(self):
super(CommandAdd, self).__init__()
self._argument_parser.add_argument('-y')
def _main(self, args_object):
print(args_object)
return 0
class CommandDelete(CommandCommon):
def _main(self, args_object):
print(args_object)
return 0
_COMMAND_DICT = {
'add': CommandAdd(),
'delete': CommandDelete()
}
def main():
return _COMMAND_DICT[sys.argv[1]].main(sys.argv[2:])
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment