9

I've been trying to find a way to reliably set and get values of variables with the names in strings. Anything I can find remotely close to this doesn't seem to always work. The variables can be in any module and those modules are imported.

What is the safe/correct way to get and set the values of variables?

ps - I'm as newb as they come to python

user2424005
  • 93
  • 1
  • 4
  • 1
    Are those modules you wrote yourself? You're most definitely doing something wrong here. Accessing variables this way is very unpythonic. Please show some examples of what you're trying to do. – Tim Pietzcker May 27 '13 at 07:59
  • The only code example I could give would be using eval and exec so i think that is moving away from trying to learn how and where these variables are and access them more directly without relying on on demand compiled from strings code. To give a little background, it's basically a media backend system and this particular need is for those that have a vague clue but too lazy to code themselves. It's kind of a bridge of modifying and created a uniform end "tv" experience but with a subsystem that can work from basically non-programmer data files to semi-script what is going on. – user2424005 May 27 '13 at 23:54

2 Answers2

8

While it would work, it is generally not advised to use variable names bearing a meaning to the program itself.

Instead, better use a dict:

mydict = {'spam': "Hello, world!"}
mydict['eggs'] = "Good-bye!"
variable_name = 'spam'
print mydict[variable_name]  # ==> Hello, world!
mydict[variable_name] = "some new value"
print mydict['spam']  # ==> "some new value"
print mydict['eggs']  # ==> "Good-bye!"

(code taken from the other answer and modified)

EKons
  • 887
  • 2
  • 20
  • 27
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • I've been leaning towards this solution myself, was just wondering what methods I haven't run into. There's a lot to python and finding where all the information is, especially on this transition from older 2, newer 2 and now into the 3 is a lot of information to sort out what is current and available. – user2424005 May 27 '13 at 23:58
4
spam = "Hello, world!"
variable_name = 'spam'
print globals()[variable_name]  # ==> Hello, world!
globals()[variable_name] = "some new value"
print spam  # ==> some new value
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • 9
    I'm tempted to downvote this, even though it's technically correct. Why teach a self-declared Python newbie the worst possible way of achieving his goal? – Tim Pietzcker May 27 '13 at 07:56
  • 1
    @TimPietzcker: You're right, of course. I wasn't really sure what I should have done otherwise, though, so I just did this. – icktoofay May 27 '13 at 22:26