Search code examples
pythoncommand-lineargs

Is it possible to embed an argsparse parser in a function?


I define an argsparse object like this:

parser = argparse.ArgumentParser(description='{desc}', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\
                 .format(desc=description)

Then I add arguments like this:

parser.add_argument("--config", "-c", help='config',
                    default='dbConf').format(dbConf=dbConfig) 

Since I use these two lines in many scripts, I want to embed them into a function. However, to my understanding the parser.add_argument() listens to the command line.

Is it possible to embed these lines into a function?


Solution

  • Is it possible to embed these lines into a function?

    Yes. add_argument doesn't interact with the command line at all, though even if it did that would make little difference.

    The one bit of argparse which interacts with the CLI input is the parse_args method, and what it does by default is access the global sys.argv attribute and process it. I wrote by default because you can also provide a list of strings as first parameter and it'll process that instead (if you click the link you'll see the official documentation does that to demonstrate various things in the examples).

    So yes, you can very much have a function which creates an ArgumentParser and starts configuring it, then returns it for more configuration and ultimately, well, parsing the arguments.