473,386 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Avoiding if..elsif statements

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?

Aug 25 '06 #1
11 3365
"unexpected" <su***********@gmail.comwrote:
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>

Aug 25 '06 #2
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?
How about (untested):

def x():
print 'x'

def y():
print 'y'

funcdict={ 'valuex': x, 'valuey': y }

funcdict['valuex']()
Aug 25 '06 #3
unexpected 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?
Yup.

dispatch = dict(
something = somethingClass.func,
somethingElse = somethingElseClass.func,
anotherthing = anotherthingClass.func,
yetanotherthing = yetanotherthingClass.func
)

def default():
pass
# call it like this

dispatch.get(switch_value, default)()

Aug 25 '06 #4
unexpected 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?
Why not do it this way?

foo =
{'something':somethingClass.func,'somethingelse':s omethingelseClass.func)

if foo.has_key(value) :
foo[value]()
else :
raise OMG, "%s isn't known" % value

Aug 25 '06 #5
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" <su***********@gmail.comwrote:
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>
Aug 25 '06 #6
"unexpected" <su***********@gmail.comwrote:
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!

in Python, an explicit call is always written as

expression(argument list)

where expression yields a callable object. in your original case,
the expression was a bound method; in the modified example,
the expression is a dictionary lookup. the actual call part looks
the same way, in both cases.

</F>

Aug 25 '06 #7
unexpected wrote:
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?
Use something other than Perl.

:)
Carl Banks

Aug 26 '06 #8
Try it and see. Functions are first-class citizens in Python.

On Aug 25, 2006, at 6:36 PM, unexpected 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?

--
http://mail.python.org/mailman/listinfo/python-list
Aug 26 '06 #9

Fredrik Lundh wrote:
"unexpected" <su***********@gmail.comwrote:
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]

Aug 27 '06 #10
Tal Einat wrote:
This will work great if all of your functions recieve the same
argument(s).
I assumed "every single function would be passing the same variables"
meant exactly that, of course.

</F>

Aug 27 '06 #11

Fredrik Lundh wrote:
Tal Einat wrote:
This will work great if all of your functions recieve the same
argument(s).

I assumed "every single function would be passing the same variables"
meant exactly that, of course.

</F>
Right, as usual. I sort of missed that... ;)

- Tal

Aug 27 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Danny | last post by:
Using small stored procs or sp_executesql dramatically reduces the number of recompiles and increases the reuse of execution plans. This is evident from both the usecount in syscacheobjects,...
12
by: Peter Proost | last post by:
Hi group, has anyone got any suggestions fot the best way to handle this problem, I've got 3 tables for example table A, B, and C table A looks like name, value table B looks like name, value...
7
by: onetitfemme | last post by:
Hi, for some reason Firefox is apparently inserting a new line somehow after some IPA symbols which I have written in their hexadecimal notation. Also, I would like to have two spaces by...
23
by: steve.j.donovan | last post by:
Hi guys, We have the following macro: #define NEXT(type,p) (*((type*)(p))++) It provides a way to poke variable sized data into an array of pcode for a simple VM. e.g,
3
by: jrs362 | last post by:
For some reason, I have to rewrite a program to avoid using import statements. I know it's possible, but cannot seem to find it in my text book. Can someone please give me a sample outline of how...
2
by: srinivasang87 | last post by:
Hi, I have a query with three select statements joined using two UNION's. All three queries differ ONLY in the where condition. It goes something like this: select Emp_No, Emp_Name, ...
12
by: Bill Mill | last post by:
Hello all, I want to have a user able to eval code in a text box. However, if he accidentally types "while(1) { i=0; }" and hits "run", I also want him to be able to hit a stop button such that...
0
by: Tewr | last post by:
I'm trying to develop a reader-lock-free application by using versioning. Instead of using SQL server 2005 built-in transactions, I'm inserting timestamped rows, so that readers would never have to...
25
by: dpapathanasiou | last post by:
I have some old Common Lisp functions I'd like to rewrite in Python (I'm still new to Python), and one thing I miss is not having to declare local variables. For example, I have this Lisp...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.