tags:

views:

126

answers:

3

What is the best way to dynamically create a Python object instance when all you have is the Python class saved as a string?

For background, I am working in the Google Application Engine environment and I want to be able to load classes dynamically from a string version of the class.

problem = “1,2,3,4,5”

solvertext1 = “””class solver:
  def solve(self, problemstring):
   return len(problemstring) “””

solvertext2 = “””class solver:
  def solve(self, problemstring):
   return problemstring[0] “””

solver = #The solution code here (solvertext1)
answer = solver.solve(problem) #answer should equal 9

solver = #The solution code here (solvertext2) 
answer = solver.solve(problem) # answer should equal 1
A: 

Use the exec statement to define your class and then instantiate it:

exec solvertext1
s = solver()
answer = s.solve(problem)
Paolo Tedesco
+9  A: 

Alas, exec is your only choice, but at least do it right to avert disaster: pass an explicit dictionary (with an in clause, of course)! E.g.:

>>> class X(object): pass
... 
>>> x=X()
>>> exec 'a=23' in vars(x)
>>> x.a
23

this way you KNOW the exec won't pollute general namespaces, and whatever classes are being defined are going to be available as attributes of x. Almost makes exec bearable...!-)

Alex Martelli
A: 

Simple example:

>>> solvertext1 = "def  f(problem):\n\treturn len(problem)\n"

>>> ex_string = solvertext1 + "\nanswer = f(%s)"%('\"Hello World\"')

>>> exec ex_string

>>> answer
11
TheMachineCharmer