عمر جاويش عمر جاويش - 1 month ago 4
Python Question

Why have multiple parsers?

I am reading through argparse docs: https://docs.python.org/3.4/library/argparse.html

I read through the "parents" doc for ArgumentParser and it mentioned that this is used when several parsers share common args. I am wondering, when would I need to have "several parsers" in the first place?

Answer

The documentation is already fairly straightforward:

Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to parents= argument to ArgumentParser can be used

One use-case that comes to mind is when you have a lot of scripts that do different things to a database that requires a username and password to be accessed. One of the scripts alters a table, another one changes a few permissions... but all those scripts are going to need the username and password to access the database, right?

You could have a "base" argument parser that expects (or parses) the username and password, and then have more specialized parsers with more arguments. For instance:

import argparse

def make_basic_parser():
    parser = argparse.ArgumentParser(description='Basic parser (only username/password).',
                                     add_help=False)
    parser.add_argument('--username', type=str, help='Username to access database')
    parser.add_argument('--password', type=str, help='Password to access database')
    return parser


def alter_table_parser():
    parent = make_basic_parser()
    parser = argparse.ArgumentParser(description='Alter a table', parents=[parent])
    parser.add_argument('--table', type=str, help='Table to alter')
    return parser


if __name__ == "__main__":
    parser = alter_table_parser()
    args = parser.parse_args()
    print("Received arguments: %s" % (args))

Running this will result in:

$ python ./stack_055_A.py --username foo --password bar --table baz
Received arguments: Namespace(password='bar', table='baz', username='foo')

So you can reuse the basic\parser every time you need a username and a password.