The Secret Life of Python: Generator Secrets - Functions That Remember
dev.to·3h·
Discuss: DEV
Flag this post

Timothy was reviewing code when he encountered something that made him do a double-take. “Margaret, what’s this yield keyword? This function has yield instead of return, and when I call it, I get some weird generator object instead of a value. What’s going on?”

Margaret grinned. “Welcome to generators - Python’s memory-efficient superpower. That function isn’t just returning a value. It’s creating an iterator that remembers its state between calls. Let me show you why generators are one of Python’s most elegant features.”

The Puzzle: Functions That Don’t Return

Timothy showed Margaret the confusing code:

def strange_function():
"""This function has yield instead of return!"""
yield 1
yield 2
yield 3

# Call it
result = strange_function()
print(f"Result: {result}") ...

Similar Posts

Loading similar posts...