title: Is there a way to set metaclass after the class definition?
body: <p>In order to set metaclass of a class, we use the <code>__metaclass__</code> attribute. Metaclasses are used at the time the class is defined, so setting it explicitly after the class definition has no effect. </p>
  
  <p>This is what happens when I try to set metaclasses explicitly;</p>
  
  <pre><code>&gt;&gt;&gt; class MetaClass(type):
      def __new__(cls, name, bases, dct):
          dct["test_var"]=True
          return type.__new__(cls, name, bases, dct)
      def __init__(cls, name, bases, dct):
          super(MetaClass, cls).__init__(name, bases, dct)
  
  
  &gt;&gt;&gt; class A:
      __metaclass__=MetaClass
  
  
  &gt;&gt;&gt; A.test_var
  True
  &gt;&gt;&gt; class B:
      pass
  
  &gt;&gt;&gt; B.__metaclass__=MetaClass
  &gt;&gt;&gt; B.test_var
  
  Traceback (most recent call last):
    File "&lt;pyshell#20&gt;", line 1, in &lt;module&gt;
      B.test_var
  AttributeError: class B has no attribute 'test_var'
  </code></pre>
  
  <p>The best idea I can think of is to re-define whole class and add the <code>__metaclass__</code> attribute dynamically somehow. Or do you know a better way set metaclass after the class definition?</p>