Create New Classes With Python At Runtime

For a testing framework I want to create new classes in Python at runtime:

def mixIn(classname, parentclasses):
	if len(parentclasses) > 0:
		parents = map(lambda p:p.__name__, parentclasses)
		createclass = "class %s (%s):\n\tpass" % (classname, ",".join(parents))
	else:
		createclass = "class %s:\n\tpass" % classname
	exec createclass
	globals()[classname] = eval(classname)

This function creates a new class in the global namespace with the name classname inheriting from all classes in parentclasses, which is a list of strings.

Use the function like this:

class Foobar:
	def __init__(self, a):
		self.a = a
	def foo(self):
		return "foo" + str(self.a)

class Barfoo:
	def __init__(self, b, a):
		self.b = b
		self.a = a
	def bar(self):
		return "bar" + str(self.b) + str(self.a)

mixIn("Test", ["Foobar", "Barfoo"])
t = Test("23")
print t.foo() # this will print "foo23"
print t.bar() # this will throw an exception, because self.b is not defined

In most cases it’s not possible to generate a meaningful __init__ function automatically. The Python interpreter just takes the constructor of the first parent, but it’s possible to add another constructor afterwards.

def myinit(self, a, b):
	Foobar.__init__(self, a)
	Barfoo.__init__(self, b, a)
Test.__init__ = myinit
t = Test("23", "42")
print t.foo() # prints foo23
print t.bar() # prints bar4223
Advertisements

0 Responses to “Create New Classes With Python At Runtime”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

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





%d bloggers like this: