Asynchronous programming
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Aug 11 05:45:41 EDT 2016
On Thursday 11 August 2016 16:21, Christian Gollwitzer wrote:
> In typical GUI code, there are usually not that many places qhere ou
> have sequential code. A simple exmaple might be a counter. Using asyncio
> and a properly integrated GUI toolkit, you could write it as (pseudo-code)
>
> async def counter():
> for i in range(10):
> button.settext("click me %d"%i)
> await button.click()
> button.disable()
> messageBox("You reached the end!")
>
> Writing that same thing in callback code to button.on_click() is
> obviously less fun and feels inverted.
I don't know how you would write it in callback fashion, but the above seems
inside out to me. It feels like COMEFROM instead of GOTO, if you understand the
analogy. Rather than
execute code in a linear fashion
until you reach a yield (GOTO), then transfer control *out*
it's
execute code in a linear fashion
control transferred *in* from somewhere else (COMEFROM)
This is how I would expect to write something like that in an event-driven way:
def mouseUp(self):
# assume self.counter is initially set to 0
self.settext("Click Me %d" % self.counter)
self.counter += 1
if self.counter == 10:
self.disable()
messageBox("You have reached the end!")
which feels natural to me. Processing of each click is independent of any other
click, and there's no non-linear transfer of control. The user clicks, the
mouseUp method is called, it runs, and it is done. Whatever persistent state
there is is part of the button itself.
I don't know whether you would call that a callback. I suppose it could be, in
the sense that you might say:
button.set_mouseup_function(mouseUp)
but I'm used to thinking of it as a property of the button.
--
Steve
More information about the Python-list
mailing list