0

I am relatively new to Python and I am trying to solve the following problem at the moment. I am writing a script which parses command line arguments with argparse. Besides some other things I have a verbosity flag, which I want to make available for some objects. Currently I am passing it to the constructor and I am wondering if there is a more elegant way for doing this.

class MyClass(object):

    def __init__(self, verbosity=False):
        self.verbosity = verbosity

    def do_something(self):
        if self.verbosity:
            print("Doing something ...")

.

import argparse
import myclass

def main():
    parser = argparse.ArgumentParser(description='Testing.')
    parser.add_argument('-v', '--verbosity', action='store_true',
                    help="Produce verbose output")
    args = parser.parse_args()
    object = myclass.MyClass(verbosity=args.verbosity)
    object.do_something()

if __name__ == "__main__":
    main()

Any help would really be appreciated.

janno
  • 1
  • 1
  • 2
    Not entirely sure what you mean by "elegant" but if you're using several command line arguments you could pass the `args` object to your constructor and have the constructor set flags/call methods based on the arguments instead of passing each argument separately. – Jonah Haney Jan 20 '18 at 20:37

1 Answers1

0

I would say what you're doing is the cleanest approach, at least in this simple case. You could pass the args namespace that argparse gives you to the MyClass initializer, but then you'll need to construct a similar object if you want to run tests on your class, or to use it as a library from another script.

If you want the same command line options to be available from multiple classes or scripts, you could create a config.py that looks something like this:

import argparse

__all__ = ['options']

parser = argparse.ArgumentParser(description='Testing.')
parser.add_argument('-v', '--verbosity', action='store_true',
                        help="Produce verbose output")
args = parser.parse_args()
options = vars(args)

Then from your script you can do from config import options and get the parsed argument from options['verbosity']. You could also change the value of options - for something like:

if self.too_much_output():
    options['verbosity'] = False

and have that change be available to any code that's using options.

(The idea to use vars(args) comes from this answer to another argparse-related question.)

Nathan Vērzemnieks
  • 5,495
  • 1
  • 11
  • 23
  • Thank you! I was looking for something like the `config.py` solution, but unfortunately I have not only one script where I'd like to use it. Therefore I'd stay with my current solution for now. – janno Jan 21 '18 at 18:40
  • @janno - I don't understand your objection: you could use this from any number of scripts, or from just one. If you put it in your PYTHONPATH you could use it from anywhere! – Nathan Vērzemnieks Jan 21 '18 at 18:45
  • To be clear, when I say could "change the value of options", that would only take effect for a single process. – Nathan Vērzemnieks Jan 21 '18 at 19:04
  • Well, it's a bunch of scripts with different command line arguments. Sorry for missing this detail in my first comment. – janno Jan 22 '18 at 09:43