Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to position argparse in code

I'm currently implementing command line arguments in my python script and want to be as pythonic as possible. Thus I'm using argparse and am currently reading trough the documentations tutorial.

What's not clear to me, as I have def main(): def a_function(): and now have to add the argparse related stuff somewhere, where does it go? Is there a PEP guideline?

I've assumed it goes outside the main(), as the arguments are used in the function and the main, but then again it's nowhere mentioned.

Sorry I'm still learning and want to learn it correctly.

tl;dr. I'm a noob and don't know where to plac argparse code

like image 562
Daedalus Mythos Avatar asked Oct 24 '25 03:10

Daedalus Mythos


1 Answers

There is no PEP guideline, and likely no common pattern. I prefer using a class for my application, and put my option parsing code in a method. I pass in the arguments, which allows the caller to either send in sys.argv, or pass in whatever it wants (eg: you can pass in a custom list of arguments when testing)

class App(object):
    def __init__(self, args):
        ...
        self.args = self._parse_arguments(args)
        ...

    def _parse_arguments(args):
        parser = argparse.ArgumentParser()
        ...
        result = parser.parse_args(args)
        return result
like image 175
Bryan Oakley Avatar answered Oct 26 '25 08:10

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!