Step-by-Step Execution
Step 1: Define my_generator()
def my_generator():
value = yield
print(f"Received: {value}")
This is a generator function because it contains the yield statement.
Unlike a normal function, calling it does not execute the function immediately.
Instead, it returns a generator object that can be used to iterate lazily.
Step 2: Create a Generator Object
gen = my_generator()
This does not execute the function yet.
It simply creates a generator object.
Step 3: Start the Generator
next(gen)
The next(gen) advances execution to the first yield statement.
Inside my_generator(), execution starts at the beginning:
value = yield
yield pauses execution and waits for a value to be sent.
Since yield is on the right-hand side of value =, it waits for a value from gen.send(...).
At this point, execution is paused, and my_generator() is waiting for input.
Step 4: Send a Value into the Generator
gen.send(10)
gen.send(10) resumes execution at the yield statement.
The yield expression returns 10, which gets assigned to value.
value = 10 # Received from gen.send(10)
Execution continues past the yield statement, so the next line runs:
print(f"Received: {value}") # Output: "Received: 10"
Since there is no more yield statement, the function ends, and the generator is exhausted.
Final Output
Received: 10
0 Comments:
Post a Comment