Python - quickest way to create class instance from string?

Started by
4 comments, last by Vorpy 15 years, 11 months ago
Say I have a python string containing a Python class definition. What is the easiest and quickest way to create an instance of that class, assuming you don't know that class is called but you do know it can derive from one of say four other abstract (so to speak) classes? Currently I'm just using compile and execing the string into a temporary module I create. I then search that module for a class that has one of the allowed base classes. I then eval the class' name to create an instance. Is there a quicker (performance wise) method for doing this? Thanks
Advertisement
What about just calling eval on the original string?
Once you've found the class just use the () operator on it to construct it. Python classes act as constructor functions for themselves. Something like this:

x = searchForClass()
myInstance = x()
Quote:Original post by Vorpy
Once you've found the class just use the () operator on it to construct it. Python classes act as constructor functions for themselves. Something like this:

x = searchForClass()
myInstance = x()



Vorpy: Is 'x' a string here, or the class object?

Kylotan: I'm not sure how eval would work differently from my code below.


# Compile the scriptlet.code = compile(scriptlet, '<string>', 'exec')# Create the new 'temp' module.temp = imp.new_module("temp")sys.modules["temp"] = tempexec code in temp.__dict__# Inspect the module.classes = inspect.getmembers(temp, callable)for name,value in classes:	if value.__module__ == "temp":		# Create the instance.		obj = eval("temp." + name)()		breakreturn obj


Thanks again.
I guess I didn't entirely understand your first question, that's all.
In my example, "x" is the class object. In your code, I think it would be "value".

Instead of:

obj = eval("temp." + name)()

it would be:

obj = value()

Using eval is nearly always unnecessary.

This topic is closed to new replies.

Advertisement