I’m trying to inject some of my own code in the class construction process of SqlAlchemy. Trying to understand the code, I’m somewhat confused by the implementation of the metaclass. Here are the relevant snippets:
The default “metaclass” of SqlAlchemy:
class DeclarativeMeta(type):
def __init__(cls, classname, bases, dict_):
if '_decl_class_registry' in cls.__dict__:
return type.__init__(cls, classname, bases, dict_)
else:
_as_declarative(cls, classname, cls.__dict__)
return type.__init__(cls, classname, bases, dict_)
def __setattr__(cls, key, value):
_add_attribute(cls, key, value)
declarative_base is implemented like this:
def declarative_base(bind=None, metadata=None, mapper=None, cls=object,
name='Base', constructor=_declarative_constructor,
class_registry=None,
metaclass=DeclarativeMeta):
# some code which should not matter here
return metaclass(name, bases, class_dict)
It’s used like this:
Base = declarative_base()
class SomeModel(Base):
pass
Now I have derived my own metaclass like this:
class MyDeclarativeMeta(DeclarativeMeta):
def __init__(cls, classname, bases, dict_):
result = DeclarativeMeta.__init__(cls, classname, bases, dict_)
print result
# here I would add my custom code, which does not work
return result
And use it like this:
Base = declarative_base(metaclass=MyDeclarativeMeta)
Ok, now to my problem:
print resultin my own class always printsNone.- The code seems to work anyway!?
- Why is the metaclass using
__init__and not__new__ declarative_basereturns an instance of this class. Shouldn’t it return a class having an attribute__metaclass__havingMyDeclarativeMetaas value?
So I wonder why the code works at all. As the SqlAlchemy people obviously know what they are doing, I assume that I’m on the completly wrong track. Could somebody explain what’s going on here?
First things first.
__init__is required to returnNone. The Python docs say “no value may be returned”, but in Python “dropping off the end” of a function without hitting a return statement is equivalent toreturn None. So explicitly returningNone(either as a literal or by returning the value of an expression resulting inNone) does no harm either.So the
__init__method ofDeclarativeMetathat you quote looks a little odd to me, but it doesn’t do anything wrong. Here it is again with some comments added by me:This could more succinctly and cleanly be written as:
I have no idea why the SqlAlchemy developers felt the need to return whatever
type.__init__returns (which is constrained to beNone). Perhaps it’s proofing against a future when__init__might return something. Perhaps it’s just for consistency with other methods where the core implementation is by deferring to the superclass; usually you’d return whatever the superclass call returns unless you want to post-process it. However it certainly doesn’t actually do anything.So your
print resultprintingNoneis just showing that everything is working as intended.Next up, lets take a closer look at what metaclasses actually mean. A metaclass is just the class of a class. Like any class, you create instances of a metaclass (i.e. classes) by calling the metaclass. The class block syntax isn’t really what creates classes, it’s just very convenient syntactic sugar for defining a dictionary and then passing it to a metaclass invocation to create a class object.
The
__metaclass__attribute isn’t what does the magic, it’s really just a giant hack to communicate the information “I would like this class block to create an instance of this metaclass instead of an instance oftype” through a back-channel, because there’s no proper channel for communicating that information to the interpreter.1This will probably be clearer with an example. Take the following class block:
This is roughly syntactic sugar for doing the following2:
So a “class having an attribute
__metaclass__having [the metaclass] as value” IS an instance of the metaclass! They are exactly the same thing. The only difference is that if you create the class directly (by calling the metaclass) rather than with a class block and the__metaclass__attribute, then it doesn’t necessarily have__metaclass__as an attribute.3That invocation of
metaclassat the end is exactly like any other class invocation. It will callmetaclass.__new__(classname, bases, dict_)to get create the class object, then call__init__on the resulting object to initialise it.The default metaclass,
type, only does anything interesting in__new__. And most uses for metaclasses that I’ve seen in examples are really just a convoluted way of implementing class decorators; they want to do some processing when the class is created, and thereafter not care. So they use__new__because it allows them to execute both before and aftertype.__new__. The net result is that everyone thinks that__new__is what you implement in metaclasses.But you can in fact have an
__init__method; it will be invoked on the new class object after it has been created. If you need to add some attributes the the class, or record the class object in a registry somewhere, this is actually a slightly more convenient place to do it (and the logically correct place) than__new__.1 In Python3 this is addressed by adding
metaclassas a “keyword argument” in the base-class list, rather than as a an attribute of the class.2 In reality it’s slightly more complicated due to the need for metaclass compatibility between the class being constructed and all the bases, but this is the core idea.
3 Not that even a class with a metaclass (other than
type) created the usual way necessarily has to have__metaclass__as an attribute; the correct way to check the class of a class is the same way as checking the class of anything else; usecls.__class__, or applytype(cls).