Python3 - Yield keyword
- take a text file that you may have.
and you want to read each line from the file:
since we are storing the lines of the text file in list = []
, we are storing those lines in the memory of our program (stack/heap)
but what if the file was million’s of lines long?
then our program would crash.
What if we just get one line at a time?
pull a line, do what we need to do, erase it from memory (the stack), and then move onto the next one.
That’s where:
Python Generators come in...
you can change the code above to instead use the yield
keyword.
instead of printing out the whole array, it will print out
to get values out of this generator object, we say next(zen)
and we will get the next line.
- @ It’s like a for-loop that is frozen in time, and we can control the actions of that frozen for-loop dynamically.
Now that we know what Yield does…How can you use yield from
?
- example
you can pass an iterable or another generator to yield from
to get the same type of results or effect
like so:
This will print out:
This is a good paradigm to use when you are handling an iterable where you don’t know the end length and don’t want your program’s memory to expand rapidly if you get a very large sized iterable (think millions).
-
! You can even send information into subgenerators in order to do further data handling or exception Handling
-
This is sometimes called “coroutine behavior”
once yield
ends up on the value side of the assignment, it turns the generator into a coroutine and allows the generator to receive values (like done by delegator
)
but when yield
is on the left side; it sends the value out of the generator.
if you need a more verbose example:
You need to “prime” the generator in order for verbose_subgen
to get to it’s first yield statement.
if you don’t you get this error.