Posts Tagged 'mixins'

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))
		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 # this will print "foo23"
print # 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 # prints foo23
print # prints bar4223