Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return or yield from a function that calls a generator?

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) 
like image 262
hyankov Avatar asked Jan 05 '20 01:01

hyankov


People also ask

Does yield return a generator?

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.

What does a generator return what does a generator return?

Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

Does generator function has a return statement?

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.

What happens when a generator encounters a yield statement?

The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.


1 Answers

You're probably looking for Generator Delegation (PEP380)

For simple iterators, yield from iterable is essentially just a shortened form of for 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!

like image 165
ti7 Avatar answered Sep 22 '22 10:09

ti7