More decorator rumination
Jack Diederich
jack at performancedrivers.com
Wed Mar 30 18:14:40 EST 2005
On Wed, Mar 30, 2005 at 02:48:51PM -0800, Scott David Daniels wrote:
> Over on comp.python.education we were discussing a (generally seen as)
> misuse of decorators to build the definite integral of a function.
> On thinking over the definite integral decorator, I had almost
> decided that one necessary, but not sufficient, criterion for a
> good decorator is that it must not change a function's arg list.
> I was happy with this until just now.
>
> I've been fighting wxPython a lot recently, and suddenly a good
> working definition for a decorator came to me:
>
> * A decorator mediates between a function and its environment.
>
> In particular, I thought about something like:
>
> @mousexy
> def OnRightClick(self, x, y):
> ...
>
> For those non-wx'ers, all GUI events come wrapped in an "event",
> so all event-responding methods tend to look like:
>
> def OnRightClick(self, event):
> x = event.GetX()
> y = event.GetY()
>
> which looks like boilerplate to me. I'm wondering whether others
> think this is an interesting insight into what decorators are "for,"
> or they think I'm working on "the moral equivalent of a macro."
>
It might be plainer (and certainly more backwards compatible) to
wrap the function when setting the event handler.
EVT_BUTTON(self.frame, XRCID("ButtonName"), mousexy(self.OnRightClick))
As a matter of style & clairty, it just depends. If this is for
education I have no idea if putting the mutation in a decorator
might make it easier to explain to novices than explaining to them
that mousexy() creates a function that returns a function which is
bound to the event.
-jack
I haven't used wxPython, I just grabbed that example from
http://wiki.wxpython.org/index.cgi/XrcCheatSheet
More information about the Python-list
mailing list