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
Simple example:
Use the exec statement to define your class and then instantiate it:
Alas,
exec
is your only choice, but at least do it right to avert disaster: pass an explicit dictionary (with anin
clause, of course)! E.g.:this way you KNOW the
exec
won't pollute general namespaces, and whatever classes are being defined are going to be available as attributes ofx
. Almost makesexec
bearable...!-)