tags:

views:

130

answers:

2

So i have a set of classes and a string with one of the class names. How do I instantiate a class based on that string?

class foo:
  def __init__(self, left, right):
     self.left = left
     self.right = right

str = "foo"
x = Init(str, A, B)

I want x to be an instantiation of class foo.

+4  A: 
classdict = {'foo': foo}

x = classdict['foo'](A, B)
Ignacio Vazquez-Abrams
How can I do it using reflection?
klynch
You *could* use `getattr()`, but that could expose you to security problems. Using a class decorator will let you enumerate classes automatically, but those only exist in newer versions of Python.
Ignacio Vazquez-Abrams
+3  A: 

If you know the namespace involved, you can use it directly -- for example, if all classes are in module zap, the dictionary vars(zap) is that namespace; if they're all in the current module, globals() is probably the handiest way to get that dictionary.

If the classes are not all in the same namespace, then building an "artificial" namespace (a dedicated dict with class names as keys and class objects as values), as @Ignacio suggests, is probably the simplest approach.

Alex Martelli