Avoiding if..elsif statements

unexpected sumesh.chopra at gmail.com
Fri Aug 25 19:09:06 EDT 2006


the missing () was the trick!

However, I'm passing in a few variables, so I can't just take it
out-though every single function would be passing the same variables.

so something.func() is actually
something.func(string, list)

How would I modify it to include them? Sorry I didn't include them the
first time, I was trying to simplify it to make it easier...oops!

Fredrik Lundh wrote:
> "unexpected" <sumesh.chopra at gmail.com> wrote:
>
> > I have a program where based on a specific value from a dictionary, I
> > call a different function. Currently, I've implemented a bunch of
> > if..elsif statements to do this, but it's gotten to be over 30 right
> > now and has gotten rather tedious. Is there a more efficient way to do
> > this?
> >
> > Code:
> >
> > value = self.dictionary.get(keyword)[0]
> >
> > if value == "something":
> >     somethingClass.func()
> > elsif value == "somethingElse":
> >     somethingElseClass.func()
> > elsif value == "anotherthing":
> >     anotherthingClass.func()
> > elsif value == "yetanotherthing":
> >     yetanotherthingClass.func()
> >
> > Is it possible to store these function calls in a dictionary so that I
> > could just call the dictionary value?
>
> but of course (did you try it?).  here's an outline:
>
>     dispatch = {
>         "something": somethingClass.func, # note: no () here
>         "somethingElse": somethingElseClass.func,
>         "anotherthing": anotherthingClass.func,
>         "yetanotherthing": yetanotherthingClass.func,
>     }
>
>     ...
>
>     dispatch[value]() # note: do the call here!
>
> or, a bit more robust:
>
>     try:
>         func = dispatch[value]
>     except KeyError:
>         print "- no handler for", value
>     else:
>         func()
> 
> tweak as necessary.
> 
> </F>




More information about the Python-list mailing list