4

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?

djvg
14.8k7 gold badges84 silver badges120 bronze badges
asked Jun 5, 2014 at 9:01
1
  • You can have a look at metaprogramming using the type() builtin function : it gives you a way to programmatically define a class. Commented Jun 5, 2014 at 9:10

1 Answer 1

3

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).

answered Jun 5, 2014 at 9:25
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.