a 'case' statement?

Andrew Bennetts andrew-pythonlist at puzzling.org
Fri Feb 14 20:57:47 EST 2003


On Sat, Feb 15, 2003 at 12:46:04AM +0000, Bengt Richter wrote:
> On Fri, 14 Feb 2003 16:25:13 +1100, Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote:
> >
> >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.
> >
[..snip..]
> >
> 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.

Which is why I said "can suit certian problems very nicely".  It doesn't
suit everything, for exactly the reasons you describe.

But for cases where rather than wanting to change something local scope, you
want to change some state in an object, putting "action_foo" methods on your
object can be effective.  A good example might be writing a class for a POP3
server, which could have command_USER, command_PASS, command_LIST,
command_RETR, etc methods automatically invoked by a lineReceived method.

I usually find I have more use for my version (i.e. changing instance vars)
than the dict version (i.e. changing local vars), but I do use both.

-Andrew.






More information about the Python-list mailing list