What 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.
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
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