Python yield

Official introduction to 'yield':

https://docs.python.org/2.7/reference/simple_stmts.html?highlight=yield#grammar-token-yield_stmt


It is said 'yield' statement can optimize code efficiency.

Here is the detailed post to help understand its advantage.

http://blog.csdn.net/preterhuman_peak/article/details/40615201

 

The code below is adapted from an example in Core Python Programming.

def counter(start_at=0):    count = start_at    while count < 6:        val = (yield count)        if val is not None:            count = val        else:            count += 1  # for i in counter(1):#   print i  c = counter(1)  print c.next()print c.next()print c.next()print c.next()print c.next()

 


Based on my observation during debugging, the line 'val =(yieldcount)' is crucial.

The execution sequence is as follows:

  1. c = counter(1)

    This doesn't execute the 'counter' function. You will go to the first 'printc.next()', if you try to step into during debugging.

  2. c.next()

    in line print c.next()

    Step into, you will go to the 'counter' function now.

  3. yield count

    Starting from the 1st line of the function, you will jump out of it to printc.next()while 'yield count' in 'val=(yield count)' is executed.

  4. print c.next()

  5. val = (yield count)

    After printing, you go back inside 'counter' function again and start execute from below 'yield'. Here it is the value assignment for 'val'.

  6. Note before Step #5, val is not defined. Afterwards, val is None, which mean (yield count) doesn't return anything. It's just like a markup telling you that 'count' is the thing to output when you call next().

  7. count += 1

  8. while count < 6

  9. yield count

  10. print c.next()