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 Almeida
@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 loopfor
– Matheus Saraiva
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
– Pablo Almeida