In Python, you can use yield
in a function as a Generator.
For example
def foo():
for i in range(10):
yield i
Written as
for k in foo():
print(k)
If you write, the value from 0 to 9 is displayed.
For example
def hoge():
for i in range(10):
yield i
return i+1
If you do this, you will only get the result of ** yield. ** **
This is a Python specification, and the reason is that return in Generator is treated as StopIteration
.
Therefore, it is safe to think that it is basically difficult to use yield and return together.
Rather, the yield acts as a return within the Generator, so basically
It is better to narrow down to either yield or return.
If for some reason you want to use it with return, use yield from
to get the value set for return.
You will be able to do it.
For example
def buzz():
i = 0
for j in range(10):
i += j
yield j
return i
If you write a function like this and want to return, prepare a new function separately and do as follows If you write it, you can get up to the value of return.
def getter():
x = yield from buzz()
yield x
However, note that yield from
is a technique that can only be described within a function.
--Generator can be generated using yield --Combination of yield and return is strict --You can get up to the value of return by using yield from. --yield from can only be used inside a function --In the end, it's better to focus on yield or return.
Recommended Posts