4

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

Daedalus Mythos
  • 565
  • 2
  • 8
  • 24
  • 2
    Depends on the size of the script, and whether it will (eventually) be imported by other scripts. Small parsers can be defined and run in the `if __name__` block. Larger ones are best defined in a function, but the `parse_args` will still be performed (directly or indirectly) by that script block. – hpaulj Sep 30 '14 at 17:30

1 Answers1

4

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
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685