0

I'm trying to make python take a string from a list at random and then use that string to determine what variable of the same name to add 1 to. I can't use a dictionary because of how I'm using the variables in other modules.

This is what I have for an example:

import random

item1 = 0
item2 = 0
item3 = 0

items = ("Item1","Item2","Item3")
item = random.choice(items)

#I want it to find the variable of the same name and then add 1 to said variable
#depending on what item is chosen to be "item".
ManxFox
  • 1
  • 1
  • 5
  • Please don't do this but use a dictionary instead. – Selcuk May 12 '16 at 12:42
  • As I mentioned I can't use a dictionary because of code that is used in other modules that uses the variables I'm using – ManxFox May 12 '16 at 12:42
  • Also, please don't use global variables, unless absolutely necessary. Fix the other modules too, while you're at it. – Ilja Everilä May 12 '16 at 12:43
  • @ManxFox in that case, you should re-write so the other modules work using a dictionary, too. Or at least a some sort of container, like a class. – RoadieRich May 12 '16 at 12:44
  • I need the global variables for certain reasons that makes it so I can't use these variables as local variables. – ManxFox May 12 '16 at 12:44
  • 2
    What do you mean by, "I can't use a dictionary because of how I'm using the variables in other modules"? Variables in Python aren't shared between modules. – ChrisGPT was on strike May 12 '16 at 12:45
  • You shouldn't but you could totally do something like that: `vars()[item] += 1` – mahe May 12 '16 at 12:45
  • I cant. these variables are being wrote to a text file in such a format that makes it so I can save/load data from the same text file – ManxFox May 12 '16 at 12:45
  • 1
    You think you can't, but probably you could. How you serialize and unserialize data is controllable by you, I hope. – Ilja Everilä May 12 '16 at 12:46

3 Answers3

0

As the comments already mentioned, please don't do that, it's bad practice. You should change the code in your other modules to look for the dictionary, rather than those variables. But if you really have to, this code goes where your comments are:

exec(item.lower() + ' += 1')
Matthias Schreiber
  • 2,347
  • 1
  • 13
  • 20
0

If you can't use dictionary, one option is to use locals setattr:

import random

item1 = 0
item2 = 0
item3 = 0

items = ("Item1","Item2","Item3")
item = random.choice(items)

locals()[item.lower()] += 1
ryanmc
  • 1,821
  • 12
  • 14
0

What you could do instead is using a dictionary (associative container) : It works with a key->value system. Here, the name of your variable will be the key, and the number it holds will be the value.

Something like :

dict = {'Item1': 0, 'Item2': 0, 'Item3': 0}
item = random.choice(dict.keys())

Hope it helps.

PaulDennetiere
  • 179
  • 2
  • 10