python - What Happens when a Generator Runs out of Values to Yield? -
to illustrate question, suppose have simple generator:
def firstn(n): num = 0 while num < n: yield num num += 1 in firstn(10): print
this print digits 0 through 9. if have:
def firstn(n): num = 0 while num < 5 < n: yield num num += 1 in firstn(10): print
(the change in while
statement.) prints digits 0 through 4. once num >= 5
, generator no longer yields values.
what i'm curious goes on under hood: used pythontutor step through code, , impression i'm under once while
statement no longer true
, function implicitly returns none
, for
loop somehow detects, , breaks. used next
built-in inspect more closely:
>>> def firstn(n): ... num = 0 ... while num < 5 < n: ... yield num ... num += 1 ... >>> >>> mygen = firstn(100) >>> next(mygen) 0 >>> next(mygen) 1 >>> next(mygen) 2 >>> next(mygen) 3 >>> next(mygen) 4 >>> next(mygen) traceback (most recent call last): file "<stdin>", line 1, in <module> stopiteration
which supports theory. big question: how stopiteration
work, , mean calling generator large value can equivalent calling smallest terminating value? in our example, for in firstn(5)
, for in firstn(9999999999999)
should equivalent, right?
this isn't mysterious. when generator runs out of values yield, raises stopiteration
exception. need understand how for-loop works in python. essentially, equivalent following code:
iterator = iter(collection) while true: try: x = next(iterator) # except stopiteration e: break
the above equivalent to:
for x in collection: #
Comments
Post a Comment