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
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