conditional class inheritance definition in python

inheritance, python

Solution

You can specify a metaclass where you can test what modules are importable:

class Meta(type):
    def __new__(cls, name, bases, attrs):
        try:
            import gtk
            bases += (gtk.Window)
        except ImportError:
            # gtk module not available
            pass

        # Create the class with the new bases tuple
        return super(Meta, cls).__new__(cls, name, bases, attrs)


class ToolWindow(common.Singleton):
    __metaclass__ = Meta

   ...

This is just a raw sketch, obviously many improvements can be done, but it should help you get started.

You should be aware that you should change your `__init__()` method from `ToolWindow` because it may not have the `gtk` module available (maybe set a flag in the metaclass to later check if the module is available; or you can even redefine the `__init__()` method from within the metaclass based on whether the module is available or not -- there are several ways of tackling this).

Problem

I have an linux based python application, which make use of `pygtk` and `gtk`. It have both UI execution & command line mode execution option. In UI mode, to create main application window, class definition is ``` class ToolWindow(common.Singleton, gtk.Window): def __init__(self): gtk.Window.__init__(self,gtk.WINDOW_TOPLEVEL) ``` What I want to do is, if application is able to import `gtk` and `pygtk`, then only class `ToolWindow` should inherit both `common.Singleton` and `gtk.Window` classes, else it should only inherit `common.Singleton` class. What is the best way to do it?

Original source