4

In the following block of code:

def bottom():  
    # Returning the yield lets the value that goes up the call stack to come right back down.
    return (yield 42)

def middle():  
    return (yield from bottom())

def top():  
    return (yield from middle())

# Get the generator.
gen = top()  
value = next(gen)  
print(value)  # Prints '42'.  
try:  
    value = gen.send(value*2)
except StopIteration as exc:  
    value = exc.value
print(value)  # Prints '84'.
  1. What does return (yield 42) actually do ? Why not simply return 42 and why is (yield 42) in parenthesis ?
  2. What does he mean by this: "Returning the yield lets the value that goes up the call stack to come right back" ?
  3. Why is he using "yield from" in the "top" and "middle" functions ?
wim
  • 338,267
  • 99
  • 616
  • 750
Liviu
  • 1,023
  • 2
  • 12
  • 33
  • `yield` expressions evaluate to whatever value is sent into the generator, e.g. when calling `gen.send(value * 2)` the expression becomes `value * 2`. – gyre Apr 19 '17 at 18:53
  • A very thorough explanation of `yield` and generators: [http://stackoverflow.com/a/231855/5463636](http://stackoverflow.com/a/231855/5463636) – freginold Apr 19 '17 at 19:01
  • @freginold that actually doesn't address generators as coroutines, which is needed to understand this particular example – juanpa.arrivillaga Apr 19 '17 at 19:14
  • 2
    @freginold indeed, you need to look at [this](http://stackoverflow.com/a/31042491/5014455) answer buried deep in the list of answers to find something that addresses this. – juanpa.arrivillaga Apr 19 '17 at 19:18
  • @juanpa.arrivillaga that is very good information, thank you for pointing it out. – freginold Apr 19 '17 at 19:33
  • 1
    @freginold yeah, unfortunately this is probably what I would consider "advanced" Python, beyond merely "intermediate" (e.g. using generators just to create lazy iterators). It mixes concurrency, probably the most hard to grasp concept in computer science, with probably the most obscure part of Python. – juanpa.arrivillaga Apr 19 '17 at 19:36
  • @juanpa.arrivillaga are you referring to this chapter: "Cooperative Delegation to Sub-Coroutine with yield from" ? Is that generator concurency ? – Liviu Apr 19 '17 at 19:40
  • @Liviu I'm not referring to any chapter, I don't know what book you are reading... – juanpa.arrivillaga Apr 19 '17 at 19:42
  • 1
    But here is a good [presentation](http://www.dabeaz.com/coroutines/Coroutines.pdf) on the subject. – juanpa.arrivillaga Apr 19 '17 at 19:42

0 Answers0