Python Button Dictionary Case Statement

From OpenCircuits
Jump to navigation Jump to search

What/Why[edit]

There is a technique in Python to use a dictionary in place of a case statement ( which in any case Python does not have ). This is a cool technique that can both make code faster and easier to maintain. I have also found that it is particurlarly useful with Tkinter to build GUIs. This page will give a little introduction and link to some example code.

How[edit]

A Case Statement[edit]

A case or switch statement in other languages may look something like this:

    ( something like this, I just made it up )
    switch on case A
         case "one"
               call sub_1()
         case "2"
             call sub_1()
     end switch

So when executed if A == "one" then sub_1 is called .......

Python Dict Approach[edit]

Assume we have build a dictionary something like

   case_dict   = { "one": sub_1,  "2": sub_2,  }

Then we can call the subroutine ( the switch case like statement )

   case_dict[ A ]()

It is really simple, supports very large number of cases, and is very fast.

With Tkinter Buttons[edit]

When we build buttons we can specify a command for the button. The idea we use here is to have all buttons call one subroutine with the button as an argument. That function then uses a dictionary to use a case dictionary to call the function we actually want. Doing this seems to require a little trick with a lambda function that I will describe only by showing you the code. There are three different versions, the first is the most naive, the last the most compact, and for me functional. You can find and read this at github [Github Code]. Read it, try it out, if you want let me know how you feel about it. By the way this uses a version of a technique described in Python Example Code