[Baypiggies] code down sizing

Marilyn Davis marilyn at deliberate.com
Sat Sep 2 01:01:12 CEST 2006

----- On Friday, September 1, 2006 shaleh at speakeasy.net wrote:

> Brain Murphy wrote:
>>   or something along those lines but I can not figure it out. Can any one
> help me with this?
> What you want is a lookup device. Consider:
> def do_a():
> import a
> # other code
> def do_b():
> import b
> # other code
> def do_c():
> import c
> # other code
> choices = {'a': do_a,
> 'b': do_b,
> 'c': do_c,}
> choice = raw_input("Enter choice: ")
> action = choices[choice]
> action()
> (Rapidly entered but close to accurate ...)

Sean's idea about a lookup device is a good one to learn.  However, for your special case, where the module names exactly match the chosen letters, you might like this trick:

    exec("import " + choice.lower())
except ImportError:
    print "No recipes were found that start with " + choice

You might find, in the long run, that storing your recipies as python code is not the most flexible possibility.  You might prefer to keep them in a file that you read and write.  That will allow you to add new recipes more easily.  And it will leave you in position to write code so that your parents can type "enchilada cassarole" when they really want the "green chili enchilada cassarole"

Good luck!

Marilyn Davis

More information about the Baypiggies mailing list