2

I have a python class and a main function next to it so I can execute it from command line. My init function deals my provided arguments:

import argparse

class Tester:

    def __init__(self):
        self.args_parser = argparse.ArgumentParser(description='Test')
        self.args = self.__parse_parameters()
...


if __name__ == "__main__":
    tester = Tester()

This way, when I execute the above file from command line, for example:

#python teser.py --test eating --lowcarb

I can provide the parameters and they will eventually get passed to __parse_parameters function. All good.

My question is, how can I pass these parameters to the class if I decide to use this class from python code?

1
  • 1
    Extract the argument parsing to a separate function outside the class. Commented Jan 15, 2023 at 11:57

2 Answers 2

3

Do you mean this?

import argparse

class Tester:

    def __init__(self, answer, foo):
        print(answer)
        self.args_parser = argparse.ArgumentParser(description='Test')
        self.args = self.__parse_parameters()

if __name__ == "__main__":
    tester = Tester(answer=42, foo='bar')

Another option (depending on what you mean) is to move the ArgumentParser outside the class:

import argparse

class Tester:

    def __init__(self, args):
        self.args = args

if __name__ == "__main__":
    args_parser = argparse.ArgumentParser(description='Test')
    tester = Tester(args_parser.parse_args())

This way you can pass any args:

tester2 = Tester(('arg0', 'arg1'))
Sign up to request clarification or add additional context in comments.

Comments

2

Look at this example from the official tutorial:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print(f"the square of {args.square} equals {answer}")
elif args.verbosity == 1:
    print(f"{args.square}^2 == {answer}")
else:
    print(answer)

You can use add_argument to specifically indicate an argument, and then pass it to the class using args.<argument-name>.

Personally I would parse the arguments in a function in main, and pass the parameters to the class, so it will look something like:

if __name__ == '__main__':
    args = parse_args()
    tester = Tester(args.arg1, args.arg2, ...)

1 Comment

Agreed. This is far superior to any notion that parsing the command line parameters during init might be a good idea. It gives a better structure overall and in particular when there's a need to handle missing flags/values on the command line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.