Python: using dictionary as switch doesn't work

I am a "neophyte python" and trying to understand the inner workings of the dictionary type. Last night, I tried to use it as a control structure (i.e., a switch statement) for keyboard input in openGL.

The problem was that for some reason, the dictionary continued to evaluate ALL cases (two in this case), and not just the one that was clicked.

Here is an example code snippet:

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 the question why each "case" is evaluated, I have several ideas, but I could not clearly find the answer to the question "why."

So, would anyone be kind enough to explain to me why when I press the n key (the ascii view is 110), this part of the code also evaluates the record to 27 (ESC key)?

Sorry if this topic was beaten to death, but I looked and could not easily find the answer (maybe I missed it).

Thanks.

+6
python data-structures switch-statement
source share
3 answers
 def keyboard(key): values = { 110: discoMode(), 27: exit() } 

In this case, you create a dict containing the return value of "discoMode ()" assigned 110, and the return value of "exit ()" is 27.

What you wanted to write was:

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

which will assign 110 to the discoMode function (do not call the function!), similarly for exiting. Remember that functions are objects of the first class: they can be assigned, stored, and called from other variables.

+3
source share

You should not call functions. Just save the function objects themselves in the dictionary, not their return values:

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

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

+15
source share

Just remove the parentheses, so you are referring to the function instead of the result of the function call. Otherwise, you explicitly say: "call this function to get the value to associate with this key."

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

All Articles