Avoiding if..elsif statements
Tal Einat
tal.no.no.spam at gmail.com
Sun Aug 27 03:56:01 EDT 2006
Fredrik Lundh wrote:
> "unexpected" <sumesh.chopra at gmail.com> wrote:
>
> > 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?
>
> just add the parameters to the call:
>
> dispatch[value](string, list) # note: do the call here!
>
This will work great if all of your functions recieve the same
argument(s). If not, there are still simple solutions.
I would suggest a solution like this, since it's simple and generic:
class Command (object):
def __init__(self, func, *args, **kw):
self.func = func
self.args = args
self.kw = kw
def __call__(self, *args, **kw):
args = self.args+args
kw.update(self.kw)
apply(self.func, args, kw)
An instance of the Command class can be called just like a function,
and it will call the orginial function with the arguments it was
instantiated with. (You can also pass additional arguments at the call
itself)
dispatch = {
"something": Command(somethingClass.func),
"somethingElse": Command(somethingElseClass.func, "moo",
[1,2,3]),
"anotherthing": Command(anotherthingClass.func, 'a', 'b', 'c'),
"yetanotherthing": Command(yetanotherthingClass.func,
verbose=True),
}
dispatch[value]()
- Tal Einat
reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))],
[[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3]
More information about the Python-list
mailing list