I needed a way to dynamically create a class at runtime in python, similar to the following Java code:
clazz = Class.forName("Image")
obj = clazz.newInstance()

python has similar capabilities:

clazz = eval("Image")
obj = clazz()

But python takes it a step further. In Java, newInstance() requires a default constructor to be present, where in python I can have any constructor. For example,

class Image:
   def __init__(self, name, type):
      self.name = name
      self.type = type

clazz = eval("Image")
obj = clazz("foo", "JPG")

Another feature is that in python I can define a class dynamically, but I haven’t tried that yet.

UPDATE
Michael Dehaan corrected my eval faux pas with the following code for loading classes. I wanted to get it formatted in the blog instead of in the comments:

# if just searching one module
# module = __import__(modname)
# or ...
for x in list_of_modules_to_search:
   try:
        classobj = getattr(module, classname)
        return classobj
   except AttributeError, ae:
        pass

if classobj is not None:
   inst = classobj(...)
else:
   # boom

4 thoughts on “python runtime class creation

  1. eval is dangerous for the same reasons it’s dangerous in perl. You probably want something like…

    # if just searching one module
    # module = __import__(modname)
    # or …
    for x in list_of_modules_to_search:
    try:
    classobj = getattr(module, classname)
    return classobj
    except AttributeError, ae:
    pass

    if classobj is not None:
    inst = classobj(…)
    else:
    # boom

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s