Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 371
LeanMan Avatar asked Oct 20 '25 03:10

LeanMan


1 Answers

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
like image 156
Daniel Avatar answered Oct 22 '25 04:10

Daniel