Python tip: create a class dynamically.

Been looking through a Django snippet lately and had to make sense of it all. A line by line analysis eventually lead to me an interesting discovery: you can create classes programmatically. Well, also, I learned a lot more, but this particularly seems worth mentioning.

The built-in function type that tells you what an object’s type is? Call that function with a 3-parameter signature (class name, a tuple of base classes, and a dictionary of properties and methods); see what happens:

>>> def echo(self, x):
...    print(x)
...
>>> def speak(self):
...    print("Hi!")
...
>>> methods = {"echo": echo, "speak": speak}

>>> FancyThings = type("FancyThings", (), methods)

>>> vars(FancyThings)
mappingproxy({'echo': <function echo at 0x104fb6f70>, 'speak': <function speak at 0x104fc7040>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'FancyThings' objects>, '__weakref__': <attribute '__weakref__' of 'FancyThings' objects>, '__doc__': None})

>>> foo = FancyThings()

>>> foo.speak()
Hi!

Further reading:

0

Comment via email.