7 ms·
The Python yield keyword explained
- johnsonqq 14y agoIt's a coroutine. Not exactly revolutionary.
- Sharlin 14y agoThat's not exactly helpful if you don't know what coroutines are and how they work.
- johnsonqq 14y agoIt's precisely all the help you need to go and look up your notes on coroutines from college. You did go to college didn't you? Or are you an anti-college hipster, suddenly finding the limitations of that approach.
- stch 14y agoIs it common to keep the notes you wrote in college?
- ineedtosleep 14y agoThis is probably the biggest jackass comment I've seen on HN in a while. Your college experience definitely shows.
- micampe 14y agothat is likely the reason why they felt the need to create a new account to post it.
- NullSet 14y agoSeriously?
- to3m 14y agoI studied computer science at a university, not just a college, and coroutines weren't covered during the course. So even if you've got a degree, there's no guarantee you'll have met a coroutine! (I do agree that a formal education is valuable, even if you already think (or know) you're good at programming. I learned a lot from my course. There's a lot to be said for being forced to learn a bunch of stuff, and when you're under 25 it's not like it's going to hurt.)
- phpnode 14y agostch - your account has been hell banned, for nearly a whole year.
- stch 14y agoWhat does that mean/how does it affect me? And howd that happen?
- phpnode 14y ago(replying to myself because I can't reply to stch directly): What does that mean/how does it affect me? It means that only people who have specifically turned "showdead" on can see your posts. No one can reply to you posts directly. Your upvotes do nothing and don't count. But crucially, to you, everything seems completely normal. And howd that happen? An administrator decided that your first ever comment didn't fit the tone of this site (which it didn't, but well, you were new), so they decided to instantly and silently ban your account forever. So you have been commenting, for a year, and basically no one has seen your posts. I feel really bad about that and I hate this objectionable practise.
- stch2 14y agoWow, that's pretty ridiculous. You'd figure after a few months they'd tell me, right? Is that also why I get "Unknown or expired link" all the time and every page always takes 15-20 seconds to load? I noticed when I logged out that issue went away. I always just assumed the forum was really poorly designed. :o)
- jlgreco 14y ago> Is that also why I get "Unknown or expired link" No, that is just something HN does.
- bthomas 14y agoI use yield and generators regularly. They just make sense, but I never knew what a coroutine is in an academic sense
- johnsonqq 14y agoThis is why you study CS at university before you start work as a programmer. Otherwise you end up being amazed by the basic CS concepts, or worse, you end up reinventing them badly.
- kachnuv_ocasek 14y agoThank God for abstraction.
- kmfrk 14y agoDoes studying CS at university make people as insufferably grumpy and unhelpful as you?
- johnsonqq 14y agoCome on, I've got a reasonable point here. People post on forums asking these questions which should have been answered during their educations. If civil engineers had a forum site and someone asked "how do I calculate the load a simple beam", people would say, what the fuck are you doing in your job if you don't know that? Who is employing you and why? Where did you go to college? Who was your tutor because next time I'm at a dinner at my college I'm going to ask him how the fuck did they pass you. Our current trend of saying college doesn't matter really starts to be a problem when professional programmers (yeah I'm assuming that the guy in the question is) are asking basic questions like this. This shows that we do need college education for programmers. It also irritates me - this guy could have taken the time to learn all these basics, but for whatever reason he thought it didn't matter, and now he's paying for it.
- monkeyfacebag 14y agoNeither a college education nor continued employment in the field is a requirement to ask a stackoverflow question. In fact, I'd venture to say that a version of stackoverflow where the default answer to everything was "you should have learned this in college" would not be very useful (or used) at all. If you find the discussion beneath you, I suggest that you not participate and find a better use of your time. Others may be getting value from it and I can't for the life of me understand why you think this is a bad thing.
- jtchang 14y agoWhat a troll. The post is descriptive and helpful. Go back to whatever hole you crawled out of.
- akashshah 14y agoOther amazing Python answers by the same guy: What is a metaclass in Python - http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/6581949#6581949 http://stackoverflow.com/questions/100003/what-is-a-metaclas... Understanding Python decorators - http://stackoverflow.com/questions/739654/understanding-python-decorators/1594484#1594484 http://stackoverflow.com/questions/739654/understanding-pyth...
- jiggy2011 14y agoWhat I find weird about the yield keyword is that it seems to effect the execution of code that comes before the statement, causing it not to execute until later. For example: def createGenerator(): print "aaa" mygen = createGenerator() outputs: aaa Whereas def createGenerator(): print "aaa" yield mygen = createGenerator() Outputs nothing.
- gejjaxxita 14y agoThe presence of the yield keyword in a function definition means the function will return a generator when it's called. Therefore "print "aaa"" is not executed on "mygen = createGenerator()" as expected. "print "aaa"" is infact executed when mygen.next() is called. To emphasise this point, it is the existence of the yield keyword which causes the function to return a generator when it is called - it will not execute any of the code. This is why the following results in an error: >>> def hello(j): ... if j>2: ... return "big number" ... elif j<2: ... yield "small number" A return keyword cannot exist within the body of a generator - it makes no sense. A more detailed explanation can be found here http://docs.python.org/2.5/ref/yieldexpr.html http://docs.python.org/2.5/ref/yieldexpr.html
- jiggy2011 14y agoI think I mostly understand the idea, the presence of the yield statement transforms the nature of the parent function itself and makes evaluation lazy. This seems a little weird syntactically though because it feels like the interpreter is somehow reading ahead in the program. It also means you don't necessarily know that this is a lazy function unless you read to the end. A more intuitive syntax might be something like: def lazy createGenerator(): print "aaa" yield "bbb"
- csense 14y agoThis syntax would against the Python principle DRY (Don't Repeat Yourself): The "lazy" keyword conveys no information that doesn't exist in the function body. Also, Python has precedent for this scanning behavior. One of the fundamental features of Python is that the scope of a variable is determined by the presence of an assignment statement in a function. For example: a = 1 def f(): print a # UnboundLocalError occurs here a = 2 f() If you know Javascript, think about how often you need to use the "var" keyword in that language, and how easy it is to accidentally pollute the global namespace by omitting it.
- ars 14y agoA helpful hint on the name: Yield should be read like "Yields" as in "returns" or "produces". Not Yield as in the common multithreading command to allow another thread to run. PS. Anyone know why they chose such a confusing name?
- Someone 14y agoBecause it allows another thread to run. Yes, they actually are coroutines, but that is an implementation detail. Just look at it as an optimization for the case where at most one of the two threads (the one producing the values and the one consuming it) runs at a time.
- kevsamuel 14y agoHi guys, I'm the autor of the answers. Thanks for the feedback. Because of comments like these, I decided to spend more time at training people for a living, and I'm loving it. So don't underestimate the power of web comments, it can literally change the way people live.