Jump to content
  • Advertisement
Sign in to follow this  
crivens

Python - quickest way to create class instance from string?

This topic is 3797 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!