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
-
1Are 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– Tim Pietzcker2013年05月27日 07:59:05 +00:00Commented May 27, 2013 at 7: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– user24240052013年05月27日 23:54:09 +00:00Commented May 27, 2013 at 23:54
2 Answers 2
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)
Sign up to request clarification or add additional context in comments.
1 Comment
user2424005
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.
spam = "Hello, world!"
variable_name = 'spam'
print globals()[variable_name] # ==> Hello, world!
globals()[variable_name] = "some new value"
print spam # ==> some new value
answered May 27, 2013 at 7:24
icktoofay
130k23 gold badges261 silver badges239 bronze badges
2 Comments
Tim Pietzcker
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?
icktoofay
@TimPietzcker: You're right, of course. I wasn't really sure what I should have done otherwise, though, so I just did this.
lang-py