samedi 1 juin 2019

How to express a generator function in terms of a template function in python

I have a function my_algorithm of the following form:

  • iteratively generate some items
  • call an abstract inner_fn on 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 can define

def my_algorithm(*agrs, inner_fn, **kwargs):
    for item in my_algorithm_iter(*args, **kwargs):
        inner_fn(item)

I was wondering, if it is possible to do the reverse, express my_algorithm_iter by means of my_algorithm.

Aucun commentaire:

Enregistrer un commentaire