Move ArgumentParser into seperate file

Viewed 857

I have an argparser that is getting very long. I want to move it into a separate file to keep my main script clean. Right now I have:

main.py

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--test',
                    default=0.1,
                    type=float,
                    help='test')
# Many more arguments
args = parser.parse_args()
# My main code
print("Argument in my code:{}".format(args.test))
...

Is there a way to turn this into two files to keep my main file clean?

main.py

import parsing_file
# My main code
print("Argument in my code:{}".format(args.test))

parsing_file.py

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--test',
                    default=0.1,
                    type=float,
                    help='test')
# Many more arguments
args = parser.parse_args()
1 Answers

Thanks @Green Clock Guy and @chepner for suggestions on how to solve this. They suggested turning the parser into a function and returning it to the main function.

main.py

import parsing_file

parser = parsing_file.create_parser()
args = parser.parse_args()
# My main code
print("Argument in my code:{}".format(args.test))

parsing_file.py

import argparse

def create_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--test',
                        default=0.1,
                        type=float,
                        help='test')
    # Many more arguments
    return parser
Related