A little disappointed so far

Andrew Bennetts andrew-pythonlist at puzzling.org
Mon May 19 04:04:04 CEST 2003


On Mon, May 19, 2003 at 02:36:53AM +0100, Graham Nicholls wrote:
> Jay O'Connor wrote:
> 
> > 
> > Actually, from a Smalltalk pure OO background I find that case
> > statements are superflous in OO languages and had been programming
> > Python for about 8 months before I even wondered if the language had
> > them :)
> >
> How do you handle, say 
> if arg == 'd':
>         switch on debug
> if arg == 'v':
>         switch on verbose

Well, I might just spell it that way... it's nice and clear :)

But for this case, I don't use if statements.  Seeing as I'm typically using
Twisted, I use its twisted.python.usage module, which lets me say:

    class Options(usage.Options):
        optFlags = [['debug', 'd', 'switch on debugging'],
                    ['verbose', 'v', 'switch on verbose reporting'],]
    
    config = Options()
    config.parseOptions()

Then, code elsewhere can look at that object and do:
    
    if config['verbose']:
        print 'Starting the flobbudgitron!'

As bonus, you automatically get support for --verbose and --debug as long
options, and also you get a nicely formatted --help message for free.

I understand that the optparse module in Python 2.3 is similarly flexible.
The point here is if you have data-driven code like this, you don't need so
many little if statements for 50 seperate cases.  It's all handled by one
general case that you can re-use.

-Andrew.






More information about the Python-list mailing list