0

What is the pythonic way to convert/modify regular function to make a single value generator?

Possible usage: pass a function where generator is expected.

I am thinking to do something like this:

# some function
def foo():
    return Bar()

def gen_foo()
    yield foo()
quantum_well
  • 869
  • 1
  • 9
  • 17

2 Answers2

3

When you said pass a function into a place where a generator is expected, I assume you are talking about it expects a sequence that can be iterated over (i.e. an iterator) using either a for loop or next(). In this case, the easiest way is actually not making a wrapper function around it but just to pass a sequence containing that function (assuming that your function does not return a sequence). Let's say you have

def foo():
    return 1

Then the easiest way to pass it to where a sequence is expected is, of course, a tuple or a list. Note this only works if the function expecting it is using a for loop internally.

(foo(), )
# or
[foo()]

But then, the function expecting the sequence may be iterating everything manually using next(), in which case you can just pass in

iter([foo()])

to get an iterator that produces that function and nothing else. This approach is basically the same as your gen_foo() and produces the same result. However, you might also want an iterator to return an infinite copy of your function, in which case you can use

import itertools
itertools.repeat(foo())

which will create an infinite amount of (the return value of) foo.

Mia
  • 2,466
  • 22
  • 38
1

Do you mean this?

def make_generator(function):
    yield function()
Anonymous
  • 738
  • 4
  • 14
  • 36