What's the best way to create a Python object when you have a class implementation stored in a string?
What is the best way to dynamically instantiate a Python object when all you have is a Python class stored as a string?
In the background I am working in Google Application Engine and want to load classes dynamically from the 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
source to share
Alas exec
- your only choice, but at least do it right to prevent disaster: skip the explicit vocabulary (with a sentence in
, of course)! For example:.
>>> class X(object): pass
...
>>> x=X()
>>> exec 'a=23' in vars(x)
>>> x.a
23
So you know that exec
will not pollute the common namespace, and any classes that will be determined, will be available as attributes x
. Almost exec
bearable ...! -)
source to share
Use the exec statement to define your class and then instantiate it:
exec solvertext1 s = solver() answer = s.solve(problem)
source to share