Sign in to follow this  

Python - quickest way to create class instance from string?

This topic is 3489 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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()

Share this post


Link to post
Share on other sites
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"] = temp

exec 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)()

break

return obj



Thanks again.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 3489 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this