Style Guide for wxPython code
This is a little style guide for using wxPython. It's not the be-all and end-all of how wxPython code should be written, but what I've tried to capture is a way to write wxPython code that is clear and Pythonic. It was vetted on the wxPython-users mailing list, with very little disagreement.
Pythonic is partly defined by:
http://www.python.org/doc/humor/#the-zen-of-python
This is about how to use wxPython-specific classes and structure. For code formatting advice, particularly if you want to include it in the wxPython lib, see: http://wxpython.org/codeguidelines.php
1. Use import wx NEVER use from wx import * or the ancient from wxPython.wx import *.
Don't use import * for other libs either.
BECAUSE: Namespaces are one honking great idea.
For modules that are buried deep in a package, you can use:from wx.lib.SomeLib import SomeModule
As no one wants to type:AnObject = wx.lib.SomeLib.SomeModule.SomeClass()
2. Keyword arguments in constructors.
- If you find yourself putting in a bunch of unneeded defaults
like wx.DefaultSize, wx.DefaultPosition, wx.ID_ANY, etc. in constructors, use keyword arguments:
MainFrame = wx.Frame(None, title="A Title", size=(500, 400))
BECAUSE: Explicit is better than implicit.
2b. Use *args and **kwargs when subclassing wx.Windows:
class MyPanel(wx.Panel): """This Panel does some custom thing""" def __init__(self, *args, **kwargs): """Create the DemoPanel.""" wx.Panel.__init__(self, *args, **kwargs)
- This allows your custom Window to take all the same arguments as a standard Window, without your having to anticipate which ones might be useful in advance.
3. Don't use IDs. There is very rarely a good reason to use them.
- BECAUSE: Simple is better than complex.
- Most Widget constructors will fill in a default ID for you, so you don't have to specify one at all. Other arguments can be specified as key word arguments (see above):
MyFrame = wx.Frame(None, title="A Title", size=(400,400))
AButton = wx.Button(self, label="Push Me")
If the id is a required argument, use wx.ID_ANY. Because wx.ID_ANY == -1, you may see -1 used for an id in code, but use wx.ID_ANY to make your code clearer. And who knows, maybe that magic value will change one day. wx.ID_ANY is more explicit, as it is self-documenting and descriptive. Using the numeric value of named constants in general is extremely poor practice in any programming language. (Chris Mellon)
BECAUSE: Explicit is better than implicit.
EXCEPTION: (there's always an exception!) Use standard IDs for standard menus, buttons, etc. It is useful to use the standard IDs because they may turn on standard functionality, such as menu item remapping for wxMac, automatic Dialog completion or cancellation, using stock button labels and images, etc. A list of these standard IDs can be found in the "Constants -- Stock items" section of the wxWidgets Reference manual. Example:
item = FileMenu.Append(wx.ID_EXIT, "&Quit") NOTE: On OSX Cocoa both the about and the quit menu belong to the bold 'app menu', and that's why you don't find them anymore in the file menu.- using the standard Ids allows wx to place these items in their correct location. By using your own ids you just block this ability to play by the rules.
4. Use the Bind() method to bind events:
- A pushbutton example:
AButton = wx.Button(self, label="Push Me")
AButton.Bind(wx.EVT_BUTTON, self.OnButtonPush)
You can use Bind() for menus too, even though they don't have a Bind() method, in this way:
FileMenu = wx.Menu()
item = FileMenu.Append(wx.ID_EXIT, "&Quit")
self.Bind(wx.EVT_MENU, self.OnQuit, item)
(where self is a wx.Frame)
5. Use Sizers!
- If you use Sizers rather than absolute positioning, you get code that:
- Works better across platforms: different platforms have different size widgets.
- Easily adapts to different languages: different languages have different length labels, etc.
- Works better even on one platform is the user uses a different default font, different theme.
- Is more maintainable: If you need to change, remove or add a widget, the rest of your dialog or panel can re-arrange itself.
6. wx.App() now has the same built in functionality as wx.PySimpleApp(),
- so there is no need for the latter.
Note: The above is not true on MacOS X. When using wx.App, tracebacks are shown in a dialog which instantly disappears as your app dies (unless run with pythonw -i). With wx.PySimpleApp, tracebacks go to stdout.
7. Use separate, custom classes rather than nesting lots of wx.Panels in one class.
If you find yourself doing this in an __init__:
self.MainPanel = wx.Panel(self, ...
self.SubPanel1 = wx.Panel(self.MainPanel, ..)
self.SubPanel2 = wx.Panel(self.SubPanel1, ...)
MyButton = wx.Button(self.SubPanel2, ....)
Then you are creating an ugly, hard to maintain, mess!
Instead, create custom classes for the stuff that all is working together in a panel:class MainPanel(wx.Panel):
- ...
class SubPanel1(wx.Panel):
- ...
8. Use native Python stuff rather than wx stuff where possible:
- BECAUSE: Simple is better than complex.
For example, use size=(500, 400) rather than size=wx.Size(500, 400)
9. Use docstrings, consistently.
10. Use the StdDialogButtonSizer with buttons using standard wx.IDs when subclassing dialogs to place the buttons correctly for the user's platform.
Example
1 #!/usr/bin/env python2.4
2
3 # I like to put the python version on the #! line,
4 # so that I can have multiple versions installed.
5
6 """
7
8 This is a small wxPython app developed to demonstrate how to write
9 Pythonic wxPython code.
10
11 """
12
13 import wx
14
15 class DemoPanel(wx.Panel):
16 """This Panel hold two simple buttons, but doesn't really do anything."""
17 def __init__(self, parent, *args, **kwargs):
18 """Create the DemoPanel."""
19 wx.Panel.__init__(self, parent, *args, **kwargs)
20
21 self.parent = parent # Sometimes one can use inline Comments
22
23 NothingBtn = wx.Button(self, label="Do Nothing with a long label")
24 NothingBtn.Bind(wx.EVT_BUTTON, self.DoNothing )
25
26 MsgBtn = wx.Button(self, label="Send Message")
27 MsgBtn.Bind(wx.EVT_BUTTON, self.OnMsgBtn )
28
29 Sizer = wx.BoxSizer(wx.VERTICAL)
30 Sizer.Add(NothingBtn, 0, wx.ALIGN_CENTER|wx.ALL, 5)
31 Sizer.Add(MsgBtn, 0, wx.ALIGN_CENTER|wx.ALL, 5)
32
33 self.SetSizerAndFit(Sizer)
34
35 def DoNothing(self, event=None):
36 """Do nothing."""
37 pass
38
39 def OnMsgBtn(self, event=None):
40 """Bring up a wx.MessageDialog with a useless message."""
41 dlg = wx.MessageDialog(self,
42 message='A completely useless message',
43 caption='A Message Box',
44 style=wx.OK|wx.ICON_INFORMATION
45 )
46 dlg.ShowModal()
47 dlg.Destroy()
48
49 class DemoFrame(wx.Frame):
50 """Main Frame holding the Panel."""
51 def __init__(self, *args, **kwargs):
52 """Create the DemoFrame."""
53 wx.Frame.__init__(self, *args, **kwargs)
54
55 # Build the menu bar
56 MenuBar = wx.MenuBar()
57
58 FileMenu = wx.Menu()
59
60 item = FileMenu.Append(wx.ID_EXIT, text="&Quit")
61 self.Bind(wx.EVT_MENU, self.OnQuit, item)
62
63 MenuBar.Append(FileMenu, "&File")
64 self.SetMenuBar(MenuBar)
65
66 # Add the Widget Panel
67 self.Panel = DemoPanel(self)
68
69 self.Fit()
70
71 def OnQuit(self, event=None):
72 """Exit application."""
73 self.Close()
74
75 if __name__ == '__main__':
76 app = wx.App()
77 frame = DemoFrame(None, title="Micro App")
78 frame.Show()
79 app.MainLoop()
Comments
Put your comments here.
Please also feel free to add to this page, though if you want to change something, please discuss on the wxPython-users group first (unless you're RobinDunn).
For good python coding style in general:
Also note that wxPython uses getter and setter methods (e.g. GetLabel(), SetLabel(str)) because it is a wrapper for another language. For native python modules you should use @property instead. Look at this stack over-flow question: properties and the Python docs: property. Of course, if you are writing a custom or extended wxPython class, use the wx style for consistency.
-- AnthonyGlaser 2013-05-11 16:15:53
History
First Written 1/11/2006 by Chris Barker, with a lot of help from the wxPython-users mailing list.
Franz Steinhaeusler, 16. Jan. 2006:
Added docstrings for init methods.
14/1/2010 - Added StdDialogButtonSizer