Search code examples
pythonargvoptparsekeyword-argument

How to pass a parameter list to another function in Python?


Using optparse, I want to separate the list of option list parameters from the place where I call add_option(). How do I package the stuff up in File A (and then unpack in file B) so that this will work? The parser_options.append() lines will not work as written...

File A:

import file_b
parser_options = []
parser_options.append(('-b', '--bootcount', type='string', dest='bootcount', default='', help='Number of times to repeat booting and testing, if applicable'))
parser_options.append(('-d', '--duration', type='string', dest='duration', default='', help='Number of hours to run the test.  Decimals OK'))

my_object = file_b.B(parser_options)

File B recieves parser_options as input:

import optparse
class B:
    def __init__(self, parser_options):
        self.parser = optparse.OptionParser('MyTest Options')
        if parser_options:
            for option in parser_options: 
                self.parser.add_option(option)

* EDIT: Fixed to use ojbects


Solution

  • Rather than try to shoehorn your options into some data structure, wouldn't it be simpler to define a function in file A that adds options to a parser you give it?

    File A:

    def addOptions(parser):
        parser.add_option('-b', '--bootcount', type='string', dest='bootcount', default='', help='Number of times to repeat booting and testing, if applicable')
        parser.add_option('-d', '--duration', type='string', dest='duration', default='', help='Number of hours to run the test.  Decimals OK')
    

    File B:

    import optparse
    def build_parser(parser_options):
        parser = optparse.OptionParser('MyTest Options')
        if parser_options:
            parser_options(parser)
    

    elsewhere:

    import file_a
    import file_b
    file_b.build_parser(file_a.addOptions)