Stop generator

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 gnnator from outside it, ie, for the generator to run while until the "user" says it does not want it anymore. My question is I do not know if the generetor's close () method is for this purpose or I'm misusing it.

    
asked by anonymous 12.02.2016 / 00:44

1 answer

1

One good way to handle this is to use StopIteration , it is launched by next() of iterator , method to signal that there are no more values, in this case the use is within the get_fruits() method. It is derived from an Exception instead of an StandardError as long as this is not considered an error in your 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)

Output:

  

Papaya
  Avocado
  Melon
  Banana

In this case I used its if fruit is 'Banana' condition to stop the generator interaction.

Source: yield break in Python

    
12.02.2016 / 01:33