0

First of all, apologies for the title, I couldn't think of a better one. What I want to do is to be able to reduce the amount of if statements in my code. Here is my code:

if var is "forwardThrustButton":
    global forwardThrustButton
    forwardThrustButton = res
elif var is "backThrustButton":
    global backThrustButton
    backThrustButton = res
elif var is "leftRotateButton":
    global leftRotateButton
    leftRotateButton = res
elif var is "rightRotateButton":
    global rightRotateButton
    rightRotateButton = res
elif var is "basicShootButton":
    global basicShootButton
    basicShootButton = res
elif var is "specialShootButton":
    global specialShootButton
    specialShootButton = res
elif var is "bombShootButton":
    global bombShootButton
    bombShootButton = res

As you can see I have a lot of if statements here, using a string that I have put into a function, and checking to see what that string is. This code works. What I want to do is to be able to pass the name of a variable into the function and just say var = res. Thanks in advance.

  • 6
    Don't use dynamic variables, use a dictionary. – juanpa.arrivillaga May 26 '17 at 08:19
  • Could you explain *why* you need a separate variable depending on another variable? This approach leads to the problem that you never know what variables exist at a certain point in time. As @juanpa.arrivillaga already said: use a dictionary. Have a look here: https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables – Christian König May 26 '17 at 08:28
  • Comparing strings with `is` is a bad idea: https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce – ivan_pozdeev May 26 '17 at 19:26

3 Answers3

1

If you just have a dictionary of all those button values, then you could easily just say

buttons["leftRotateButton"] = res

that would clean up your code all around too

buttons[var] = res
Mauricio
  • 419
  • 4
  • 14
1

You can try:

globals()[var] = res

or

locals()[var] = res

depending on the scope context. But this is very ugly, and it's better to use a dictionary.

poe123
  • 1,188
  • 8
  • 11
0

First of all, use == instead of is, is is an identity testing, you're basically checking if var is "forwardThrustButton", the very same str instance. And the result of this check depends on string interning implementation of a specific Python version. You can check these posts to get more information on the subject.
Apart from that, you can keep a dict with all possible button names as keys and buttons as values as mentioned before, or use exec("global " + var + "; " + var + " = res"), though latter is quite ugly (but gets the job done).

Lemx
  • 166
  • 2
  • 6