[pygtk] Layout of complex app

David Ripton dripton at ripton.net
Thu Jan 29 02:09:21 WST 2009


On 2009.01.28 13:02:39 +0100, Thomas Guettler wrote:
> what layout (directories and classes) do you use for a
> pygtk project? I am programming since several years, but I am not
> used to event based programming like pygtk.
> 
> The pygtk tutorial suggest this:
> 
> {{{
> class HelloWorld:
>     def __init__(self):
>         self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
>         ...
>         self.show()
> 
>     def main(self):
>         gtk.main()
> 
> if __name__ == "__main__":
>     hello = HelloWorld()
>     hello.main()
> 
> }}}
> 
> If you start other dialogs from "HelloWorld", which depend on data
> stored in the main
> object, do you pass it around, or do you store it in a "global" variable
> at module level?

I pass it around.

I don't use globals in non-trivial code that also has classes, because
once you've gone to the bother to use classes then instance variables
are about as easy to use as globals, and cleaner.

So If I have widget A that depends on widgets B and C, I add B and C as
instance variables inside A.  When possible I set them exactly once in
A.__init__, to simplify lifespan issues and make the code easier to
read.

Note that the HelloWorld class above encapsulates a gtk.Window rather
than inheriting from gtk.Window.  I think this is usually right, because
you often want code in your class that's not part of the parent widget's
mission, so has-a makes more sense than is-a.  And it's easier with
Glade to have not-widget classes that encapsulate stock widget classes,
than to have custom-widget classes, because that way you don't have to
write custom loading code.  I only subclass gtk widgets when I actually
need a custom widget that does its own drawing, which usually means a
gtk.DrawingArea subclass.

As far as packages / directories go, my personal preference is to keep
it as simple as possible until it actually needs to be complex.  That
means that I start with one directory and put all the files there, use
sibling imports rather than package imports, run the code straight out
of the source tree rather than installing it, etc.  When the project
actually gets big enough that one directory gets unwieldy, then I move
files into subdirectories.  When it's ready to deliver to endusers, then
I make an installer and do proper packages.  IMO it's easier that way,
and modern version control systems don't punish moving files around like
CVS did.

-- 
David Ripton    dripton at ripton.net


More information about the pygtk mailing list