a 'case' statement?

Andrew Bennetts andrew-pythonlist at puzzling.org
Fri Feb 14 00:25:13 EST 2003


On Thu, Feb 13, 2003 at 09:02:51PM -0800, Chad Netzer wrote:
> On Thu, 2003-02-13 at 20:47, Wouter van Marle wrote:
> > Hi!
> > 
> > I miss something like Pascal's case: statement! (probably my Pascal syntax
> > is not correct, it's too long ago, it was a very very handy one anyway!)
> > 
> > case keyword is:
> > 'life':
> >    killit()
> > 'dead':
> >    buryit()
> > else:
> >   donothing()
> > end
> 
> call_table = { 'life' : killit, 'dead' : buryit }
> f = call_table.get( keyword, donothing )
> f()

Or even:

    class Action:
        def choose(self, keyword):
            getattr(self, 'action_' + keyword, donothing)()
    
        def action_life(self):
            killit()
    
        def action_dead(self):
            buryit()
    
    Action().choose(keyword)

Which can suit certain problems very nicely.

> > In Python I have to do this with the not so nice if, elif, else statements.
> 
> You don't HAVE to...

Indeed.  You could even say there's many ways to do it...

-Andrew.






More information about the Python-list mailing list