views:

241

answers:

2

I have a class that handles command line arguments in my program using python's optparse module. It is also inherited by several classes to create subsets of parameters. To encapsulate the option parsing mechanism I want to reveal only a function add_option to inheriting classes. What this function does is then call optparse.make_option.

Is it a good practice to simply have my add_option method say that it accepts the same arguments as optparse.make_option in the documentation, and forward the arguments as *args and **kwargs?

Should I do some parameter checking beforehand? In a way I want to avoid this to decouple that piece of code as much from a specific version of optparse.

A: 

Are you sure that subclassing is what you want to do? Your overriding behavior could just be implemented in a function.

kaizer.se
+1  A: 

It seems that you want your subclasses to have awareness of the command line stuff, which is often not a good idea.

You want to encapsulate the whole config input portion of your program so that you can drive it with a command line, config file, other python program, whatever.

So, I would remove any call to add_option from your subclasses.

If you want to discover what your config requirements look like at runtime, I would simply add that data to your subclasses; let each one have a member or method that can be used to figure out what kind of inputs it needs.

Then, you can have an input organizer class walk over them, pull this data out, and use it to drive a command line, config file, or what have you.

But honestly, I've never needed to do this at run time. I usually pull all that config stuff out to it's own separate thing which answers the question "What does the user need to tell the tool?", and then the subclasses go looking in the config data structure for what they need.

Sean Cavanagh
A very good answer. I understand now that for encapsulating the command line parser it would be better to have it fully configurable. But I actually decided to go with S.Lott's suggestion and simply give up the encapsulation altogether.
Avihu Turzion