Programmatically creating variables in Python [duplicate]

from string import uppercase
_g = globals()
for char in uppercase:
    _g[char] = Variable(char)

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 by locals() may not actually change the value of any local variables.

You can also do something similar with the __dict__ of a class or instance.

Leave a Comment