Generator Lifecycle
Generator State Transitions
Generators in Python go through distinct states during their lifecycle, which determines how they can be used and consumed.
stateDiagram-v2
[*] --> Created: Generator Function Called
Created --> Running: next() or __next__() Method
Running --> Suspended: yield Statement
Suspended --> Running: Resumed
Running --> Completed: StopIteration
Completed --> [*]
Initialization and Creation
When a generator function is called, it doesn't immediately execute. Instead, it returns a generator object:
def countdown_generator(n):
while n > 0:
yield n
n -= 1
## Generator is created but not started
gen = countdown_generator(5)
Iteration Methods
Using next() Method
gen = countdown_generator(3)
print(next(gen)) ## 3
print(next(gen)) ## 2
print(next(gen)) ## 1
Using for Loop
for value in countdown_generator(3):
print(value)
Generator States Comparison
State |
Description |
Behavior |
Created |
Generator object exists |
Not yet started |
Running |
Currently executing |
Producing values |
Suspended |
Paused at yield |
Waiting to be resumed |
Completed |
All values generated |
Raises StopIteration |
Handling Completion
When a generator exhausts its values, it raises a StopIteration
exception:
gen = countdown_generator(2)
print(next(gen)) ## 2
print(next(gen)) ## 1
try:
print(next(gen)) ## Raises StopIteration
except StopIteration:
print("Generator exhausted")
Advanced Lifecycle Management
send() Method
Allows sending values back into the generator:
def interactive_generator():
while True:
x = yield
print(f"Received: {x}")
gen = interactive_generator()
next(gen) ## Prime the generator
gen.send(10) ## Sends value into generator
Generator Close and Cleanup
def resource_generator():
try:
yield "Resource"
finally:
print("Cleaning up resources")
gen = resource_generator()
next(gen)
gen.close() ## Explicitly closes generator
At LabEx, we emphasize that understanding generator lifecycle helps in:
- Efficient memory management
- Implementing complex iteration patterns
- Creating memory-efficient data processing pipelines
Best Practices
- Use generators for large or infinite sequences
- Be aware of single-use nature
- Handle potential exceptions
- Close resources when generators are no longer needed