6

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.

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And be sure that the value for default is likewise a function object (i.e, that calling default() is legal and does something sensible.)
3
def keyboard(key):
  values = {
    110: discoMode(),
    27: exit()
  }

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

What you meant to write was:

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

Which will assign 110 to the function discoMode (not call the function!), likewise for exit. Remember functions are first class objects: they can be assigned, stored, and called from other variables.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.