Conditional definition of class inheritance in python

I have a linux based python based application that uses pygtk and gtk. It has both user interface execution and command line mode. In user interface mode, to create the main application window, class definition

class ToolWindow(common.Singleton, gtk.Window):

     def __init__(self):
         gtk.Window.__init__(self,gtk.WINDOW_TOPLEVEL)

What I want to do is if the application can import gtk and pygtk, then only the ToolWindow class should inherit both the common.Singleton and gtk.Window else classes, it should only inherit the regular one. Singleton class

What is the best way to do this?

+4
source share
1 answer

You can specify a metaclass where you can check which modules are imported:

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

   ...

, , , .

, __init__() ToolWindow, gtk (, , , , __init__() , - ).

+3

Source: https://habr.com/ru/post/1543371/


All Articles