Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Using a dictionary as switch not working

I'm a 'python neophyte' and trying to grasp the inner workings of the dictionary datatype. Last night I was attempting to use one as a control structure (i.e. switch statement) for keyboard input on an openGL program.

The problem was that for some reason the dictionary kept evaluating ALL cases (two in this instance) instead of just the one from the key pressed.

Here is an example piece of code:

def keyboard(key):
  values = {
    110: discoMode(),
    27: exit()
  }
  values.get(key, default)()

I spent an hour or more last night trying to find the answer to why every 'case' is evaluated, I've got a few ideas, but wasn't able to clearly find the answer to the "why" question.

So, would someone be kind enough to explain to me why when I hit the 'n' key (the ascii representation is 110) that this piece of code evaluates the entry under 27 (the ESC key) too?

Apologize if this topic has been beaten to death but I looked and was unable to find the clear answer easily (maybe I missed it).

Thank you.

like image 677
Austen Cameron Avatar asked Feb 10 '11 17:02

Austen Cameron


1 Answers

You shouldn't call the functions. Just store the function objects itself in the dictionary, not their return values:

def keyboard(key):
    values = {
      110: discoMode,
      27: exit
    }
    values.get(key, default)()

f() is a call to the function f and evaluates to the return value of this call. f is the function object itself.

like image 135
Sven Marnach Avatar answered Sep 21 '22 12:09

Sven Marnach