How does Lazy Evaluation work in Python?
programming.dev
How does Lazy Evaluation work in Python?
In last week’s post [https://fosstodon.org/@bterwijn/117128950012202427] we showed that a Python for-loop works through the Iterator Protocol. This same protocol also enables values to be produced lazily. In this new Lazy Evalution Example [https://memory-graph.com/#codeurl=https%3A%2F%2Fraw.githubusercontent.com%2Fbterwijn%2Fmemory_graph_examples%2Frefs%2Fheads%2Fmain%2Flazy.py×tep=0.2&play=] we show one sink reading values from five different sources: - source1: eagerly returns all values by list - source2: lazily by generator function using yield - source3: eagerly by list comprehension - source4: lazily by generator expression - source5: lazily by iterator protocol The same for-loop consumes all five sources. The eager sources produce all values before the sink starts consuming them. In the lazy sources producer and consumer take turns: - produce → consume → produce → consume → … Each value is produced only when the for-loop requests it. Generator functions and generator expressions are concise, readable ways to create lazy iterables. The final source makes their underlying mechanism explicit: - iter() obtains an iterator. - next() requests the next value. - StopIteration signals that no values remain. This clearly shows that generators achieve lazy iteration by implementing Python’s Iterator Protocol.
0 comments
No comments yet.