Generators are more specific versions of iterators that you can create yourself!
When a generator function is called, it returns a generator object!
The body of a generator function is not evaluated until next is called on the returned generator object.
Generator functions look like normal functions, but use yield instead of return. Python will automatically see yield and determine a function a generator function if necessary.
Generators (continued)
When next is called on a generator object, the body of a function is executed until yield is reached.
From there, the yield statement will return a value, and then pauses that specific function at that moment (by saving the frame, and the line that it's on)
When next is called again, we continue where we left off, until yield is reached again.
StopIteration will be raised at the end of a generator function
Example
defcountdown_generator(n):assert n >= 0while n >= 0:
yield n
n -= 1
yield from
You can use yield from <iterable> if you want to yield every value from an iterable. These are equivalent:
lst = [1, 2, 3]
# Version 1yieldfrom lst
for item in lst:
yield item
Mental Health Resources
CAPS:
If you need to talk to a professional, please call CAPS at 510-642-9494.
After Hours Assistance
For any assistance after hours, details on what to do can be found at this link