Note that there are some explanatory texts on larger screens.

plurals
  1. POSqlAlchemy metaclass confusion
    text
    copied!<p>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:</p> <p>The default "metaclass" of SqlAlchemy:</p> <pre><code>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) </code></pre> <p><code>declarative_base</code> is implemented like this:</p> <pre><code>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) </code></pre> <p>It's used like this:</p> <pre><code>Base = declarative_base() class SomeModel(Base): pass </code></pre> <p>Now I have derived my own metaclass like this:</p> <pre><code>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 </code></pre> <p>And use it like this:</p> <pre><code>Base = declarative_base(metaclass=MyDeclarativeMeta) </code></pre> <p>Ok, now to my problem:</p> <ul> <li><code>print result</code> in my own class always prints <code>None</code>.</li> <li>The code seems to work anyway!?</li> <li>Why is the metaclass using <code>__init__</code> and not <code>__new__</code></li> <li><code>declarative_base</code> returns an instance of this class. Shouldn't it return a class having an attribute <code>__metaclass__</code> having <code>MyDeclarativeMeta</code> as value?</li> </ul> <p>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?</p>
 

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