Possible Duplicate:
How to programmatically set a global (module) variable?
I have a class called Variable defined as so:
class Variable():
def __init__(self, name):
self.name = name
self._value = None
def value(self):
return self._value
def __repr__(self):
return self.name
I want to create 26 capital single letter instances of Variable like this:
A = Variable('A')
B = Variable('B')
...
Z = Variable('Z')
So far I’ve tried various solutions, and the best I’ve come up with is:
from string import uppercase
for char in uppercase:
exec "%s = %s" % (char, Variable(str(char))) in None
However, this doesn’t run and gives me this error:
Traceback (most recent call last):
File "C:\Users\Administrator\Dev\python\truthtable\truthtable.py", line 7, in <module>
exec "%s = %s" % (char, Variable(str(char))) in None
File "<string>", line 1, in <module>
NameError: name 'A' is not defined
What am I doing wrong?
Whether this is a good idea remains questionable 🙂
This only works for
globals()(i.e. module level assignments), as the language definition explicitly states that modifying the dictionary returned bylocals()may not actually change the value of any local variables.You can also do something similar with the
__dict__of a class or instance.