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)
When you use a yield keyword inside a generator function, it returns a generator object instead of values. In fact, it stores all the returned values inside this generator object in a local state.
Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
A return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true ). If a value is returned, it will be set as the value property of the object returned by the generator.
The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.
You're probably looking for Generator Delegation (PEP380)
For simple iterators,
yield from iterable
is 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With