Python generators: return output

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'.
  • What makes a return (exit 42)? Why not just return 42 and why (exit 42) in parentheses?
  • What does he mean by this: "Damage return gives a value that goes up to the call stack before go back"?
  • Why does he use the "exit" in the "top" and "middle" functions?
+4
source share

Source: https://habr.com/ru/post/1675201/


All Articles