In the second iteration of the while
loop, the server
generator only has 2 more items to yield, and the client()
function will trigger the StopIteration
exception when it tries to get 3 elements.
You'd need to handle the StopIteration
in the client()
function instead:
def client(course, take):
meal = []
for _ in range(take):
try:
some_meal = next(course)
meal.append(some_meal)
except StopIteration:
pass
return meal
Now that a client will handle the StopIteration
, you'll have to handle the while
loop differently; if a client()
doesn't return elements your server
must've been empty:
while True:
meal = client(course, 3)
if not meal:
break
print("First client: ", meal)
meal = client(course, 2)
print("Second client: ", meal)
if not meal:
break
You are missing a few tricks from the Python standard library here. You can reimplement your server
with iter()
:
def server():
return iter(MEALS)
and you could use itertools.islice()
to handle your client:
from itertools import islice
def client(course, take):
return list(islice(course, take))