0

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?

maryAndreeva
  • 61
  • 1
  • 6
  • What do you mean *"how does it work"*? You mean how is it implemented? Or just how does one use it (in which case, there are plenty of examples out there already, e.g. http://stackoverflow.com/q/231767/3001761) – jonrsharpe May 28 '16 at 19:51
  • I'd recommend these presentations on [generators](http://www.dabeaz.com/finalgenerator/) and [coroutines](http://www.dabeaz.com/coroutines/) – Ben May 28 '16 at 20:02
  • @jonrsharpe 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? – maryAndreeva May 28 '16 at 20:04
  • So it's the assignment and `.send` you're unclear on? What is puzzling you? – jonrsharpe May 28 '16 at 20:07
  • @jonrsharpe only the assignment. I've never seen such use of this statement before. – maryAndreeva May 28 '16 at 20:14
  • 1
    Then see http://stackoverflow.com/q/19302530/3001761 – jonrsharpe May 28 '16 at 20:15
  • @jonrsharpe Thank you, that cleared it a lot! – maryAndreeva May 28 '16 at 20:23
  • @Ben Thanks for those links a lot! – maryAndreeva May 28 '16 at 20:23
  • You should change the title of your question to `How does "line = yield" work?` – gboffi May 28 '16 at 20:27
  • The answer to your question is `line = yield` _and_ `matcher.send('string')` together let you implement a _coroutine_, that is a generator with a twist, you can modify its status using its `.send()` method. For further details you have already the links in the excellent comments from Ben and johnrsharpe. – gboffi May 28 '16 at 20:34
  • @gboffi Thak you for your advise and clear explanation! – maryAndreeva May 28 '16 at 21:12
  • I know this is old, but this may help someone. This presentation by D. Beasley is the best explanation http://dabeaz.com/coroutines/Coroutines.pdf. . .The 1st part explains what `line = yield` does & how it does it. – Chris Kavanagh Jul 28 '17 at 03:51

0 Answers0