Explanation
The first step in understanding what is going on in this wacky code is to take a look at what
has to say about using return with yield:
return expr in a generator causes StopIteration(expr) to be raised upon exit from the generator.
In this case, StopIteration is raised at the beginning of my_func() due to the return statement
inside the function being called. Your code catches the StopIteration exception inside the list()
function at the end of the code.
Because an exception is raised, ["Python"] is not returned, so the list() function returns an empty
list.
If you’d like to get ["Python"] out of your code, you would need to modify the call to use the next()
function wrapped in an exception handler:
1 def my_func(value):
2 if value == 5:
3 return ["Python"]
4 else:
5 yield from range(value)
6
7 try:
8 next(my_func(5))
9 except StopIteration as exception:
10 print(f"StopIteration caught! {exception.value = }")
This code removes the call to list(), which will automatically catch the StopIteration exception
and uses the next() function instead. The next() function does not catch StopIteration, so you
wrap that call with Python’s try / except construct to catch that exception yourself.
To get the value of the exception, you can access the exception object’s value attribute.
0 Comments:
Post a Comment