0

I have a global variable one, two, three ... and I have a variable "num" (it is a string) that can be "one" or "two" or "three" ...I want to do the next thing :

if num == "one":
   one = True
elif num=="two":
   two = True
elif num=="three":
   three = True
...

in perl I can do it with 1 line : something like eval "$num = True" instead of the long if else above. How can I do it in python ?

yehudahs
  • 2,488
  • 8
  • 34
  • 54
  • 4
    [Using eval is bad practice](http://stackoverflow.com/a/1832957/1211429). – Joseph Victor Zammit Feb 24 '14 at 22:26
  • What are you actually trying to do here? I wouldn't be surprised if there's a simpler solution that avoids this whole wonky True/False thing. – Silas Ray Feb 24 '14 at 22:30
  • You are almost certainly doing something the wrong way. What are you trying to accomplish? – Al Sweigart Feb 24 '14 at 22:33
  • `Namespaces are one honking great idea -- let's do more of those!` – John La Rooy Feb 24 '14 at 22:39
  • I an sure that there is a better way to write this - but I am using code that others wrote so changing the way the variables are written is a mess. I am trying to do exactly what I wrote - have a variable string that has the exact name of an existing variable and I am trying to turn this existing variable to True if I have the string. – yehudahs Feb 25 '14 at 04:58

3 Answers3

8

You can use globals() to access global names as a dictionary:

globals()[num] = True

but you normally want to keep your data out of your variable names. Use a dictionary instead of globals here instead:

numbers = {'one': False, 'two': False, 'three': False}

numbers[num] = True

or perhaps an object:

class Numbers:
    one = two = three = False

numbers = Numbers()

setattr(numbers, num, True)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Eval is rather dangerous, so just like globals() I'm offering a slightly more eligant solution.

If you would want to build a dictionary with your keys being the "one", "two", etc... and the values being False. Then all you need to do is:

if num in switch_dict:
    switch_dict[num] = True

Then to get meaningful data back all you need to do is

print switch_dict[num]

or for control flow

if switch_dict[num]:
    <do stuff>
Jeff Langemeier
  • 1,018
  • 1
  • 10
  • 21
0

Although most likely, there are better ways to accomplish whatever it is for you're trying do, here's how:

one, two, three = False, False, False
print "before:", one, two, three  # before: False False False
num = "two"
eval("globals().update({%r: True})" % num)
print " after:", one, two, three  #  after: False True False
Community
  • 1
  • 1
martineau
  • 119,623
  • 25
  • 170
  • 301
  • I know that there are better solution but I am looking for the solution that will not make me have to change others code. this is exactly what I was looking for ! thx. – yehudahs Feb 25 '14 at 05:55