a 'case' statement?

Bengt Richter bokr at oz.net
Fri Feb 14 19:46:04 EST 2003


On Fri, 14 Feb 2003 16:25:13 +1100, Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote:

>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...
>
The trouble with all the function-calling variants is that they
require function calls, and code inside the functions can't rebind
anything in the local scope where the case construct is, which
results in ugly mutable-parameter tricks.

Regards,
Bengt Richter




More information about the Python-list mailing list