Another surprisingly complex topic, also waiting for me to explore.
It seems, "yield from" is much more than simple chaining of generators. It is a bidirectional channel that lets you pass values to and from generators, as well as propagate error messages across functions automatically.
The important topic to research is: coroutines.
Good place to start:
Thanks a lot but I asked for the 🐍 'yield from...' instruction & not for the 🐍 'yield' instruction⁉️🤔
Tibor Santa Thx, I think, I'll be also interesting for you;
PEP 380 -- Syntax for Delegating to a Subgenerator
It's just like Mirielle🐶 [Inactive] said. Yield transforms a given function into a generator. Considering the code provided above, the first time you ask the function for output it will give you "1". The function gets frozen in that first yield statement. Thus, the second time you ask use the function, it will "unfreeze" and proceed until the next yield is reached. And so on.
I hope I managed to help in something!
yield from seems to be a yield statement for iterables, where each item in an iterable will be separately be yielded.
yield from [1, 2, 3]
for temp in [1, 2, 3]:
But that statement might have more meanings, because it would be weird that Python created a statement for a thing which can be easily done with 2 lines of code.
Yield statement changes a function into a generator function.
Generator functuin behaves little different than an original function.
Generator function returns a generator object, that works a little like a list, you can:
check whether an item is in generator object by in operator.
iterate through a generator object with for loop.
transform it into another iterable.
When used in for loop:
for i in gen_func():
First: gen_func() gets normally called and for loop waits gen_func to yield its first value.
Second: gen_func yields first value, call of gen_func gets paused.
Third: the yielded value gets assigned to variable i and for loop runs its codeblock once and i gets printed.
Fourth: the gen_func call continues from where it was paused and for loop waits for new value to be yielded.
Fifth: Same cycle will continue until function call terminates, for loop breaks or other thing (such as an error) causes termination for the loop.
I personally haven't used that tool yet, somehow it didn't occur to me.
A generator usually yields from the inside, right?
So when you use subgenerators in a generator, instead of writing a loop and yielding every next of that subgenerator, you basically just pull everything out and pass it right on to the outside.
And it seems you can also put stuff in with send.
As I said, so far I haven't at any point thought: 'If there was just a way to...'