On Thu, Dec 31, 2009 at 8:54 AM, Wells <thewellsoli...@gmail.com> wrote:
> Sorry, this is totally basic, but my Google-fu is failing: > > I have a variable foo. I want to instantiate a class based on its > value- how can I do this? It sort of depends on where these classes are. If they're in the current namespace/module, something like: class A: pass class B: pass class C: pass my_variable = "B" instance = globals()[my_variable]() Basically, globals() returns a dictionary of the current module's globals, which you can access as you please. Personally, I find this ugly and slightly dangerous(as who knows what else is in your globals that may get accessed), and would prefer an explicit mapping of available-classes, e.g.: valid_classes = {"A": A, "B": B, "C": C} instance = valid_classes[my_variable]() --S
-- http://mail.python.org/mailman/listinfo/python-list