I have a generator generator and also a convenience method to it - generate_all.
def generator(some_list):
for i in some_list:
yield do_something(i)
def generate_all():
some_list = get_the_list()
return generator(some_list) # <-- Is this supposed to be return or yield?
Should generate_all return or yield? I want the users of both methods to use it the same, i.e.
for x in generate_all()
should be equal to
some_list = get_the_list()
for x in generate(some_list)
You're probably looking for Generator Delegation (PEP380)
For simple iterators,
yield from iterableis essentially just a shortened form offor item in iterable: yield item
def generator(iterable):
for i in iterable:
yield do_something(i)
def generate_all():
yield from generator(get_the_list())
It's pretty concise and also has a number of other advantages, such as being able to chain arbitrary/different iterables!
return generator(list) does what you want. But note that
yield from generator(list)
would be equivalent, but with the opportunity to yield more values after generator is exhausted. For example:
def generator_all_and_then_some():
list = get_the_list()
yield from generator(list)
yield "one last thing"
The following two statements will appear to be functionally equivalent in this particular case:
return generator(list)
and
yield from generator(list)
The later is approximately the same as
for i in generator(list):
yield i
The return statement returns the generator you are looking for. A yield from or yield statement turns your whole function into something that returns a generator, which passes through the one you are looking for.
From a user point of view, there is no difference. Internally, however, the return is arguably more efficient since it does not wrap generator(list) in a superfluous pass-thru generator. If you plan on doing any processing on the elements of the wrapped generator, use some form of yield of course.
You would return it.
yielding* would cause generate_all() to evaluate to a generator itself, and calling next on that outer generator would return the inner generator returned by the first function, which isn't what you'd want.
* Not including yield from