Dynamically Changing the Base Class

Carl Banks pavlovevidence at gmail.com
Mon Jul 7 23:04:49 CEST 2008

On Jul 7, 9:31 am, "Adam C." <adam... at gmail.com> wrote:
> We have a situation where we want a Swig-generated Python class to
> have a different base (not object). It doesn't appear that we can
> coerce Swig into generating the class we want at present (but we are
> still enquiring).
> Is it possible to dynamically change the base class to something else?
> Initial experiments appear to show it is not:
> -------------------------------- snip -------------------------------->>> class Foo(object):
>         pass
> >>> class Foozle(object):
>         pass
> >>> Foozle.__bases__ = (Foo,)
> Traceback (most recent call last):
>   File "<pyshell#6>", line 1, in <module>
>     Foozle.__bases__ = (Foo,)
> TypeError: __bases__ assignment: 'Foo' deallocator differs from
> 'object'
> -------------------------------- snip --------------------------------
> Is there a solution I am missing?
> Thanks in advance.

You get the same effect as subclassing by using multiple inheritance.
Suppose your SWIG class called Foo to have a base class of Base.  You
could instead call the SWIG class _Foo, and define Foo as a Python
class like this:

class Foo(_Foo,Base): pass

If you do that, the resulting class will behave exactly as if _Foo
were a subclass of base (apart from some introspection methods and
edge cases).  You can see that this is so if you look at the MRO:

Foo, _Foo, Base, object

Which is the same MRO that would occur if _Foo derived from Base

The drawback (which is also a drawback to the hypothetical base
reassignment) is that Foo's __init__ method won't call Base's.  The
only way you can make SWIG __init__ call it's superclass's __init__ is
apparently a patch.

Carl Banks

More information about the Python-list mailing list