Re: Designing a cancellable function



Gabriel Genellina wrote:

I now would also like to add the possibility to allow the user to
*cancel* the execution of foo() during the processing, and I am
wondering what the best / most Pythonic way to design this is.

I can't say if this is the "best/more Pythonic way", but a simple way would be to use the return value from your callback. Consider it an "abort" function: if it returns True, cancel execution; as long as it returns False, keep going.

It's even easier if the callback function simply raise an exception, which can be caught from the outside:


class AbortOperationError(RuntimeError):
pass


def callback(N):
updateProgressBar(N)
processGUIEvents()
if exit_button_pressed:
raise AbortOperationError()


try:
longFunction(callback)
except AbortOperationError()
pass


def longFunction(callback):
for i in xrange(1000000000):
# do something
callback(i / 1000000000.0)


--
Giovanni Bajo
.