
Python Generators Part 2: How They Actually Work (The Magic Revealed)
Understanding the pause button: frames, state, and bidirectional communication In Part 1, you learned: ✅ Generators produce values one at a time (lazy) ✅ The yield keyword pauses the function ✅ Generators use constant memory (112 bytes) ✅ Use for loops or next() to get values If you haven't reviewed Part 1 yet, please refer to it here . Now let's answer the big question: How does Python remember where it paused? The Big Question: Where is the State Saved? When a generator pauses at yield , it needs to remember: 📍 Where it was in the code (which line?) 🧮 All local variables (their current values) 📊 The call stack (in case there were nested function calls) Where does Python store all this? Answer: In a special object called a Generator Frame . What Happens When You Call a Generator Function Let's trace through this step-by-step: def counter ( start , end ): current = start while current < end : value = current ** 2 yield value current += 1 # Step 1: Call the function gen = counter ( 0 ,
Continue reading on Dev.to Python
Opens in a new tab



