Callbacks and "callable" objects
Michael Hudson
mwh21 at cam.ac.uk
Thu Apr 22 12:54:03 EDT 1999
Randall Hopper <aa8vb at vislab.epa.gov> writes:
> A while back I asked how to pass parameterized callbacks to Tkinter.
> Now I need to explore how best to do partial resolution of callback
> arguments. For example, define values for arguments 1 and 2 at
> registration time, but leave argument 3 to be populated by Tkinter.
>
> Probably makes no sense. So let me use an example:
I don't think that you've described your problem too well here, but I
understand the problem faced in the example well enough.
What you want is a callable object with state indpendent of the
parameters it's passed by whatever's calling it. In your example
below, you want the callback to have a `color' state.
The most Pythonic way of doing this is to define a class like this:
class ColorCallback:
def __init__(self,color):
self.color=color
def callback(self,event):
print self.color
wgt1.configure( command = ColourCallback("blue").callback )
This can be a lot of typing for a measly little callback however,
leading to the dreaded `default argument hack':
def make_color_callback(color):
def _(event,color=color):
print color
return _
This is less typing (& quicker) but it is sneaky. Tim Peters once
said:
> Not at all, although I agree here too <wink>. It's like saying a
> fork is broken just because it's not that handy for jacking up a
> car. That is, Guido implemented the syntax to support default
> arguments, and it works great for that purpose! Using it to fake
> closures is a hack, and the "hey, this is cool!" / "hey, this really
> sucks!" mixed reaction thus follows, much as pain follows a car
> falling on your skull. Stick to stabbing peas, or even teensy
> pea-sized closures, and a fork serves very well.
which sums it up far better than I ever could.
(Pay a visit to
http://starship.python.net/crew/amk/quotations/python-quotes.html
somtime...)
HTH
Michael Hudson
Jesus College
Cambridge
CB5 8BL
More information about the Python-list
mailing list