Execution context and output of generator?

#Help_post

Can someone explain the output and execution context of this program . I have tried to play with generator and got stuck here .

code start from here

def power(values):
print(f’ {values} first power print’)
for value in values:
print(‘powering %s’ % value)
yield value

def adder(values):
print(f’{values} adder print’)
for value in values:
print(‘adding %s’ % value)
if value % 2 == 0:
yield value+3
else:
yield value+2

results = adder(power([1,4,7,9,12,19]))
next(results)
next(results)

code end here.

Output

<generator object power at 0x7f7c2e2ffc10> adder print
[1, 4, 7, 9, 12, 19] first power print
powering 1
adding 1
powering 4
adding 4

end output

You’ve got 2 generator functions. The characteristic of a generator is
that it runs only when you try to iterate over its results (for example,
by calling next() on it).

So the generator below:

def power(values):
     print(f' {values} first power print')
     for value in values:
             print('powering %s' % value)
             yield value

will run until its yield statement when you ask for its next value. So
the first time you ask for a value, only then does it start to
execute. So it does the first print, then the print inside the loop,
then yields its first value.

The generator below is similar: when you ask for its first value, only
then
does it run. It does its first print, then the print inside the
loop, then yields a value.

def adder(values):
     print(f'{values}  adder print')
     for value in values:
             print('adding %s' % value)
             if value % 2 == 0:
                     yield value+3
             else:
                     yield value+2

Now, consider how you are calling it:

results = adder(power([1,4,7,9,12,19]))

The values over which adder() iterates are the values from the
power() generator. SO initially neither runs. Then you ask for the
first value from adder():

next(results)

It does the first adder() print function. Then adder() starts to
iterate over its values, which is the generator from your call to
power(). Now the power() function commences running, does its
first 2 prints, then yields a value. The adder() resumes, does its
second print and then yields a value. And that is the return value from
next(results).

Then you do this again:

next(results)

but the functions are both inside their loops, so one to the prints
inside the loop.

Cheers,
Cameron Simpson cs@cskk.id.au

Thanks for you nice Response . :smile: