Designing a cancellable function

Leo Breebaart leo at lspace.org
Fri Dec 15 20:20:47 EST 2006


I have written a function foo() that iterates over and processes
a large number of files. The function should be available to the
user as library function, via a command-line interface, and
through a GUI.

So, I added a 'config' object as a parameter to foo() that can be
used by the caller to explicitly pass in user-defined settings.
Because the processing foo() does can take such a long time, the
next thing I did was add an 'update_function' callback parameter
that foo() will call regularly, so that the GUI can update a
progress bar, and the command-line version can print dots, etc.

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.

One obvious approach seems to me to turn the 'config' object into
something more dynamic, and have foo() regularly inspect it to
see if somebody in the main thread has set e.g. config.abort to
True.

Another approach would be to turn foo() into a proper (threaded)
class with distinct run() and abort() methods. But the caller
would still need to register the update callback somehow, and I
am wondering if this way the whole API for foo() won't become to
complex and overdesigned.

I was wondering if anybody has any insights or best practice
recommendations for me here. Do I keep the function interface? Do
I use a class? Any other solution I am overlooking?

Many thanks in advance for your advice.

-- 
Leo Breebaart  <leo at lspace.org>



More information about the Python-list mailing list