I have a function my_algorithm of the following form:
- iteratively generate some items
- call an abstract
inner_fnon each item
def my_algorithm(*args, inner_fn, **kwargs):
for ...: # many nested loops go here
inner_fn(next_item) # call monitor on each item
Hence my_algorithm represents an "outer algorithm" with its inner behavior parametrized into inner_fn.
An alternative way to abstract the inner behavior away would be to use a generator:
def my_algorithm_iter(*args, **kwargs):
for ...: # many nested loops go here
yield next_item
Both concepts provide different user interfaces, that is
my_algorithm(*a, my_inner_fn, **kw)
vs.
for item in my_algorithm_iter(*a, **kw):
my_inner_fn(item)
To offer both iterfaces without code duplication, one could define my_algorithm by means of my_algorithm_iter as follows:
def my_algorithm(*agrs, inner_fn, **kwargs):
for item in my_algorithm_iter(*args, **kwargs):
inner_fn(item)
I was wondering, if there is also a simple solution for the reverse, expressing my_algorithm_iter by means of my_algorithm.