tags:

views:

67

answers:

1

I'm playing with subclassing OptionParser from the std library module optparser. (Python 2.5.2) When I attempt it I get the exception:

TypeError: super() argument 1 must be type, not classobj

Looking at OptionParser, it is not derived from object. So I added object as a parent class, (shown below) and super works properly.

from optparse import OptionParser, Option
class MyOptionParser(OptionParser, object):
    """Class to change 
    """
    def __init__(self,
             usage=None,
             option_list=None,
             option_class=Option,
             version=None,
             conflict_handler="error",
             description=None,
             formatter=None,
             add_help_option=True,
             prog=None,
             epilog=None,
            ):

      super(MyOptionParser, self).__init__(usage, option_list, option_class, version, conflict_handler, description, formatter, add_help_option, prog, epilog)

if __name__ == '__main__':
    """Run a quick test
    """
    parser = MyOptionParser()
    parser.add_option("-t", "--test", type="string", dest="test")
    (options, args) = parser.parse_args()
    print "The test option is: %s" % options.test

Is this the correct way to go about it?

+2  A: 

Yes I dont see why it would not work. You just need to add couple of spaces right before that super call - as it's written right now, it is not part of your custom init method. Also, a shortcut you might want to use is **kwargs - you can do kwargs key check in your method if thats what you desire to do:

class MyOptionParser(OptionParser, object):
    """Class to change 
    """
    def __init__(self, **kwargs):
        # You can limit kwargs keys here
        super(MyOptionParser, self).__init__(**kwargs)
kibitzer
Good tip - thanks!
ptcmark
If it helped, please mark as answered.
kibitzer