I was reading a Python textbook when I saw this piece of code:
def print_matches(matchtext):
print "Searching for", matchtext
while True:
line = (yield)
if matchtext in line:
print line
matcher = print_matches("python")
matcher.next()
matcher.send("Hello World")
matcher.send("python is cool") # prints "python is cool"
matcher.send("yow!")
matcher.close()
I always considered it a kind of return
-sibling, so now I am really interested how (yield)
works. Some people referred me to the Python 2 documentation and PEP 342.
But as I am not a native speaker it's really hard for me to understand anything written in there. Could anyone please tell me in as simple language as possible how (yield)
works?
I understand the syntax when you use "yield" to return object on demand. But I don't understand the implementation of "line = (yield)". Why "yield" is a value of a variable?