Hacker News new | past | comments | ask | show | jobs | submit login
The Python yield keyword explained (stackoverflow.com)
89 points by iamelgringo on Aug 14, 2010 | hide | past | favorite | 14 comments



Thank you for linking this. It may not be hot news or a trendy topic but it was a very good read and a good refresher :)


I'm glad you liked it. i've recently discovered the awesomeness of generators, and I'm starting to use them a lot in my code. I don't see them a lot in other people's code that I read, so I figure I'd spread the word a bit.


Although I agree it was an interesting read and I do like this language feature, I think generators should be used with caution since they might detract from the code's readability (especially generator expressions). Some async libraries like dieselweb just use them too much for my taste.


Generators actually allow you to decouple code in more ways than normal functions and classes let you. See the "Why functional programming matters" paper, or the more practical presentation here:

http://www.dabeaz.com/generators/Generators.pdf


Wow, excellent resource, definitely a must-read. However, I still stand by my opinion that there are more intuitive ways to control flow in python other than generator tricks.


One of the most thorough explanations I've seen on any question.


It's always nice when you finally understand "magic".


I found looking at the code that the C# compiler generates for its yield keyword to also be helpful for understanding this keyword.

Source of an iterator example: http://gist.github.com/524972

What the compiler generates for the above example: http://gist.github.com/524974

The meat of it is in the MoveNext() function, where the original function is split up along the yield keywords into cases in a switch statement.


His decorator explanation is also excellent.


Can I get a link to the decorator explanation? A quick browse through his history didn't reveal much.



Yep, agreed, another gem.


I have it on my favorites, love it!, best explanation ever!


loved the bank example !




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: