Thursday, August 6, 2015

Slots in Python

Slots seem to be poorly documented. What they do is simple, but whether they are used is tricky. This is a little mini-post on slots.

Basics of Metaclasses

This is a quick tutorial over the basics of what metaclasses do.

The Metaclass

Metaclasses, while seemingly a complex topic, really just do something very simple. They control what happens when you have code that turns into a class object. The normal place they are executed is right after the class statement. Let's see that in action by using print as our metaclass.

Note: this post uses Python 3 metaclass notation. Python 2 uses assignment to a special __metaclass__ attribute to set the metaclass. Also, Python 2 requires explicit, 2 argument super() calls.

In [13]:
class WillNotBeAClass(object, metaclass=print):
    x=1
WillNotBeAClass (<class 'object'>,) {'x': 1, '__module__': '__main__', '__qualname__': 'WillNotBeAClass'}

Here, we have replaced the metaclass (type) with print, just to investigate how it works. This is quite useless, of course, but does show that the metaclass gets called with three arguments when a class is created. The first is the name of the class to be created, the second is a tuple of base classes, and the third is a dictionary that has the namespace of the body of a class, with a few extra special values added.