title: Extending widget bases dynamically
body: <p>I need to change bases of some of my widget class, depending on passed arguments.</p>
  
  <p>The simplest example is:</p>
  
  <pre><code>class A:
      def a(self):
          print (1)
  
  class B:
      def __init__(self):
          self.extend_instance(A)
          self.a()
  
      def extend_instance(obj, cls):
          base_cls = obj.__class__
          base_cls_name = obj.__class__.__name__
          obj.__class__ = type(base_cls_name, (base_cls, cls),{})
  
  B()
  
  </code></pre>
  
  <p>Maybe not an optimal way, because it changes bases every time when a new <code>B</code> instance created (if I undestand it right). But it seems to work.</p>
  
  <p>This is a very simplified example (without arguments, depending on which class B instances with different bases should be created.)</p>
  
  <p>Now I'm trying to implement this with kivy widgets</p>
  
  <pre><code>from kivy.app import App
  from kivy.lang import Builder
  from kivy.uix.label import Label
  
  
  class CoolLabel(Label):
      def a(self):
          print (1)
  
  
  class MyLabel:
      def __init__(self, **kwargs):
  
          #self.__basses__ = CoolLabel
  
          self.extend_instance(CoolLabel)
  
          self.a()
  
  
      def extend_instance(obj, cls):
          base_cls = obj.__class__
          base_cls_name = obj.__class__.__name__
          obj.__class__ = type(base_cls_name, (base_cls, cls),{})
  
  
  class MyApp(App):
      def build(self):
          self.root = MyLabel(text= '123456')
  
  
  MyApp().run()
  </code></pre>
  
  <p>And I get this error:</p>
  
  <pre><code>   File "main.py", line 24, in extend_instance
       obj.__class__ = type(base_cls_name, (base_cls, cls),{})
   TypeError: __class__ assignment: 'MyLabel' object layout differs from 'MyLabel'
  </code></pre>
  
  <p>what is the reason? can this be related to kivy Widget Metaclass?
  and are there any ways to workaround this?</p>
  
  <p>Update:</p>
  
  <p>Let me simplify my problem.
  The main question is - why this doesn't work?</p>
  
  <pre><code>from kivy.uix.widget import Widget
  
  class MyWidget:
      def __init__(self, **kwargs):
          self.__class__ = type('MyWidget', (Widget,),{})
  
  MyWidget()
  </code></pre>
  
  <p>Here's the error I have:</p>
  
  <pre><code>   File "main.py", line 7, in &lt;module&gt;
       MyWidget()
     File "main.py", line 5, in __init__
       self.__class__ = type('MyWidget', (Widget,),{})
   TypeError: __class__ assignment: 'MyWidget' object layout differs from 'MyWidget'
  </code></pre>