Stop Generator

Asked

Viewed 29 times

1

What would be the best way to stop a Generator? Example:

>>> def get_fruits():
        fruits = ['Mamão', 'Abacate', 'Melão', 'Banana', 'Maçã', 'Uva']

        for fruit in fruits:
            yield fruit


>>> my_bag = []
>>> salesman_fruits = get_fruits()
>>> 
>>> for fruit in salesman_fruits:
        my_bag.append(fruit)
        if fruit is 'Banana':
            salesman_fruits.close() # Chega não quero mais frutas

This was the way I found to stop the gnerator from outside of it, that is, so that the Generator runs while until the "user" says he does not want more. My doubt is that I don’t know if the generetor close() method is for that purpose or I’m making mistaken use of it.

  • What do you want to happen to the generator after you finish using it? You can simply stop your loop with break when you don’t want more fruit. No need to stop the generator. Maybe you need to give a better example.

  • @Pablo, I decided to stop this way because the internal loop of Generator would continue even if I gave a break in the why that runs the Generator. Let’s assume that the interactor body has an infinite loop: http://paste.ubuntu.com/15023506/ This would cause an infinite loop, since the break is for the loop for

  • You’re right! But from what I read here, it seems that . close() is the correct way to generate the Stopiteration that Dener quoted. See: https://docs.python.org/2/whatsnew/2.5.html

1 answer

1


A good way to deal with this is to use the Stopiteration, he is cast by next() of iterator, method to signal that there are no more values, in this case the use is within the method get_fruits(). It is derived from a Exception instead of a Standarderror provided that this is not considered an error in its normal application.

See this adaptation of StopIteration:

def get_fruits():
    fruits = ['Mamão', 'Abacate', 'Melão', 'Banana', 'Maçã', 'Uva'] 

    for fruit in fruits:
        yield fruit
        if fruit is 'Banana':
            raise StopIteration    

my_bag = []
salesman_fruits = get_fruits()

for fruit in salesman_fruits:
    my_bag.append(fruit)
    #if fruit is 'Banana':
        #salesman_fruits.close() # Chega não quero mais frutas

for fruit in my_bag: 
    print(fruit)

Exit:

Papaya
Avocado
Melon
Banana

In this case I used your condition if fruit is 'Banana' to stop Generator interaction.

Source: Yield break in Python

Browser other questions tagged

You are not signed in. Login or sign up in order to post.