Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Using <code>traceit</code> to step through the program line-by-line:</p> <pre><code>import sys import linecache class SetTrace(object): ''' with SetTrace(monitor): ... ''' def __init__(self, func): self.func = func def __enter__(self): sys.settrace(self.func) return self def passit(self, frame, event, arg): return self.passit def __exit__(self, ext_type, exc_value, traceback): sys.settrace(self.passit) def traceit(frame, event, arg): ''' http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html ''' if event == "line": lineno = frame.f_lineno filename = frame.f_globals["__file__"] if (filename.endswith(".pyc") or filename.endswith(".pyo")): filename = filename[:-1] name = frame.f_globals["__name__"] line = linecache.getline(filename, lineno) print("%s # %s:%s" % (line.rstrip(), name, lineno, )) return traceit def b(): for i in range(5): yield i x = (yield) print(x) def a(): g = b() next(g) for i in range(4): g.send(5) print(next(g)) with SetTrace(traceit): a() </code></pre> <p>we obtain</p> <pre><code>g = b() # __main__:44 next(g) # __main__:45 # runs b until you get to a yield for i in range(5): # __main__:38 yield i # __main__:39 # stop before the yield; resume a ^ for i in range(4): # __main__:46 g.send(5) # __main__:47 # resume b; (yield i) expression evals to 5 then thrown away x = (yield) # __main__:40 # stop before yield; resume a ^ print(next(g)) # __main__:48 # next(g) called; resume b; print not called yet print(x) # __main__:41 # next(g) causes (yield) to evaluate to None None for i in range(5): # __main__:38 yield i # __main__:39 # yield 1; resume a; `print(next(g))` prints 1 1 for i in range(4): # __main__:46 g.send(5) # __main__:47 # resume b; (yield i) expression evals to 5 then thrown away </code></pre> <p>The comments on the right-hand side (above) explain why Python prints <code>None</code> then <code>1</code>. If you get that far, I think it is clear why you get <code>None</code>, <code>2</code>, etc. -- it's the same story all over again with different values for <code>i</code>.</p> <p>The other scenario, where <code>x = (yield)</code> and <code>yield i</code> are reverse can be analyzed similarly.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload