Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First things first. <code>__init__</code> is <strong>required</strong> to return <code>None</code>. The <a href="http://docs.python.org/reference/datamodel.html#object.__init__" rel="noreferrer">Python docs</a> say "no value may be returned", but in Python "dropping off the end" of a function without hitting a return statement is equivalent to <code>return None</code>. So explicitly returning <code>None</code> (either as a literal or by returning the value of an expression resulting in <code>None</code>) does no harm either.</p> <p>So the <code>__init__</code> method of <code>DeclarativeMeta</code> that 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:</p> <pre><code>def __init__(cls, classname, bases, dict_): if '_decl_class_registry' in cls.__dict__: # return whatever type's (our superclass) __init__ returns # __init__ must return None, so this returns None, which is okay return type.__init__(cls, classname, bases, dict_) else: # call _as_declarative without caring about the return value _as_declarative(cls, classname, cls.__dict__) # then return whatever type's __init__ returns return type.__init__(cls, classname, bases, dict_) </code></pre> <p>This could more succinctly and cleanly be written as:</p> <pre><code>def __init__(cls, classname, bases, dict_): if '_decl_class_registry' not in cls.__dict__: _as_declarative(cls, classname, cls.__dict__) type.__init__(cls, classname, bases, dict_) </code></pre> <p>I have no idea why the SqlAlchemy developers felt the need to return whatever <code>type.__init__</code> returns (which is constrained to be <code>None</code>). Perhaps it's proofing against a future when <code>__init__</code> 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.</p> <p>So your <code>print result</code> printing <code>None</code> is just showing that everything is working as intended.</p> <hr> <p>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 <em>calling</em> 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.</p> <p>The <code>__metaclass__</code> 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 of <code>type</code>" through a back-channel, because there's no proper channel for communicating that information to the interpreter.<sup>1</sup></p> <p>This will probably be clearer with an example. Take the following class block:</p> <pre><code>class MyClass(Look, Ma, Multiple, Inheritance): __metaclass__ = MyMeta CLASS_CONST = 'some value' def __init__(self, x): self.x = x def some_method(self): return self.x - 76 </code></pre> <p>This is roughly syntactic sugar for doing the following<sup>2</sup>:</p> <pre><code>dict_ = {} dict_['__metaclass__'] = MyMeta dict_['CLASS_CONST'] = 'some value' def __init__(self, x): self.x = x dict_['__init__'] = __init__ def some_method(self): return self.x - 76 dict_['some_method'] = some_method metaclass = dict_.get('__metaclass__', type) bases = (Look, Ma, Multiple, Inheritance) classname = 'MyClass' MyClass = metaclass(classname, bases, dict_) </code></pre> <p>So a "class having an attribute <code>__metaclass__</code> having [the metaclass] as value" <strong>IS</strong> 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 <code>__metaclass__</code> attribute, then it doesn't necessarily have <code>__metaclass__</code> as an attribute.<sup>3</sup></p> <p>That invocation of <code>metaclass</code> at the end is exactly like any other class invocation. It will call <code>metaclass.__new__(classname, bases, dict_)</code> to get create the class object, then call <code>__init__</code> on the resulting object to initialise it.</p> <p>The default metaclass, <code>type</code>, only does anything interesting in <code>__new__</code>. 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 <code>__new__</code> because it allows them to execute both before and after <code>type.__new__</code>. The net result is that everyone thinks that <code>__new__</code> is what you implement in metaclasses.</p> <p>But you can in fact have an <code>__init__</code> method; it will be invoked <em>on the new class object</em> 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 <code>__new__</code>.</p> <hr> <p><sup>1</sup> In Python3 this is addressed by adding <code>metaclass</code> as a "keyword argument" in the base-class list, rather than as a an attribute of the class.</p> <p><sup>2</sup> 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.</p> <p><sup>3</sup> Not that even a class with a metaclass (other than <code>type</code>) created the usual way necessarily <em>has</em> to have <code>__metaclass__</code> as an attribute; the correct way to check the class of a class is the same way as checking the class of anything else; use <code>cls.__class__</code>, or apply <code>type(cls)</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. COThanks for these detailed explanations which already clarify a lot. But a few pices have still not fallen in place: So if i have "class A(B,C,D)" the type of A does not depend on B,C or D having a __metaclass__ attribute, but on beeing B,C or D being of a differnt type than "type". Correct? And by giving A a __metaclass__ attribute, I say explicit: A,B,D are of type "type", but want to have another type. Assuming A is of type MA and B of type MB. How is the type of A choosen? And where can I find the documentation about this topic?
      singulars
    2. CO@Achim When you set the metaclass of a class, you're saying that your class is an instance of the metaclass. Inheritance implies that this should also be true of any subclasses of your new class. This means that the metaclass of class `A` has to be a subclass of the metaclasses of each of the base classes (`B`, `C`, and `D`).
      singulars
    3. CO@Achim Since `type` is the class of all classes, things generally "just work" when there is only one metaclass involved. If `A` doesn't have `__metaclass__`, and one of `B`, `C`, `D` has one (or several of them have the same metaclass), then `A` will also have the same metaclass. When there are two metaclasses involved, things get difficult. I believe you'd have to make a new metaclass that multiply inherits from all the metaclasses involved, and use that. Python can't figure out the precedence of the different metaclasses automatically, so the programmer has to do it explicitly.
      singulars
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload