Generator
Explore how Python generator functions simplify asynchronous programming by yielding values lazily, improving memory and compute efficiency. Understand generator lifecycle states and the use of methods such as next and close to control execution flow.
We'll cover the following...
Generator
Functions containing a yield statement are compiled as generators. Using a yield expression in a function’s body causes that function to be a generator. These functions return an object which supports the iteration protocol methods. The generator object created, automatically receives a __next()__ method. Going back to the example from the previous section we
can invoke __next__ directly on the generator object instead of using next():
def keep_learning_asynchronous():
yield "Educative"
if __name__ == "__main__":
gen = keep_learning_asynchronous()
str = gen.__next__()
print(str)
You can execute the above code in the code widget below:
Also note, the snippet iter(gen) is gen returns True. Thereby, confirming that a generator function returns a generator object which is an iterator.
Recap
Remember the following about generators:
Generator functions allow us to procrastinate computing expensive values. We only compute the next value when required. This makes generators ...