Python : parsing the command line options using optparse

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Mar 1 12:47:03 CET 2014


On Sat, 01 Mar 2014 16:43:11 +0530, Ganesh Pal wrote:

> Iam done with the command line parsing but got stuck while trying to
> implement switch kind of behavior with dictionaries.  So posting 2 more
> questions

You should start new threads for new questions. The subject line here has 
nothing to do with the questions you ask.

> Question 1 :
> 
> Iam using the options.name  directly  for manipulations is this fine or
> do I need to assign it to variable and then use it

It is perfectly fine to use options.name directly. There's no need to 
save it to a temporary variable just to use it, unless doing this makes 
your code easier to read.


> Question 2 :
> 
> I wanted to use dictionary to match the above if else behavior (we don't
> have switch in python I guess ) and  If else looks very untidy.
> 
> Is it possible to store the options.object_type as a key in the
> dictionary and   then based on the value entered in the command line
> invoke the appropriate function

Yes. You almost got it right here:

> object_type_dictonary = { 'LIN' : corrupt_inode(),
>                           'INODE' : corrupt_lin(),
>                           'DATA' : corrupt_data(),
>                         };

(By the way, this is Python, not C, and there is no need for redundant 
semi-colons at the end of each line.)

The mistake you made is that you *called* the functions inside the dict. 
Instead, just refer to the function object itself, without calling it:

object_type_dictonary = {
    # no parens after the functions
    'LIN' : corrupt_inode,
    'INODE' : corrupt_lin,
    'DATA' : corrupt_data,
    }


Then, after you look up the object type, then and only then call the 
function:

func = object_type_dictionary[object_type]
func()



-- 
Steven



More information about the Python-list mailing list