When I call a function, I want to receive updates when the function reaches some milestones:
def do_something():
start_with_something()
# update
for x in iterate_something():
# update each iteration
do_something_expensive()
# update again
finish_with_something_else()
# final update
return the_nice_result
This would allow me, for example, update an UI with a progress bar. Or show some initial results to the user after the first update.
A way to do this would be using callbacks:
def do_something(initial_update, iteration_update, update_again, final_update):
some_initial_data =start_with_something()
initial_update(some_initial_data)
for x in iterate_something():
iteration_update(x)
...
Another way, in python, would be to (abuse?) generators:
def do_something():
some_initial_data= start_with_something()
yield some_initial_data
for x in iterate_something():
yield x
do_something_expensive()
yield ...
There are pros and cons to both situations, but I do not really fancy any of them. For example, the first one clutters the function signature and updates information passed-in values, and the second one abuses an iteration mechanism.
In the end I want to keep my do_something
function separated from any UI stuff.
I would like to know if there is an approach for this situation or a way to architecture this, specially in Python, which can avoid both of the cons.