Search code examples
pythongeneratorbreak

run code after yield statement in python generator when using break


I have a simple generator:

def counter(n): 
   counter = 0
   while counter <= n:
      counter += 1
      yield counter
   print(f"Nice! You counted to {counter}")

def test_counter(): 
   for count in counter(6): 
      print(f"count={count}")
      if count > 3: 
         break

In this example there is a break once count reaches 3. However the only problem with the code is that the break terminates the generator execution at the yield statement. It doesn't run the print statement after the yield statement. Is there a way to execute code within the generator that is after the yield statement when a break occurs?

Example run:

# What happens: 
>>> test_counter()
count=1
count=2
count=3
count=4

# What I'd like to see: 
>>> test_counter()
count=1
count=2
count=3
count=4
Nice! You counted to 4

Solution

  • You have to put the print in a finally-block:

    def counter(n): 
        try:
            counter = 0
            while counter <= n:
                counter += 1
                yield counter
        finally:
            print(f"Nice! You counted to {counter}")
    
    def test_counter(): 
        for count in counter(6): 
            print(f"count={count}")
            if count > 3: 
                break