-1

How to understand the function repeater2 and repeater3?

def repeater1(value):
    new = (yield value)

def repeater2(value):
    while True:
        new = (yield value)

def repeater3(value):
    while True:
        new = (yield value)
        if new is not None:value = new

r1,r2,r3 = repeater1(1),repeater2(2),repeater3(3)
r1.next() #1
r2.next() #2
r3.next() #3

r1.send(4) #StopIteration 
r2.send(4) #2
r2.next() #2
r3.send(4) #4
r3.next() #4
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Alex
  • 67
  • 2

1 Answers1

-2

The variable new does not do anything in function repeater2 (or repeater1 for that matter). The function may be rewritten as:

def repeater2(value):
    while True:
        yield value

Also calling r2.send() is pointless because it does not do anything with the yield expression. Whatever you send to it, it will always return 2 because that was passed in during generator initialization.

r3 yields the initial value of 3 for the first time and then whatever value is used in the send call for subsequent calls (as long as it is not None). The variable new is actually being used here.

It may make sense to rename these functions as non_repeater, repeater and sendable_repeater.

sureshvv
  • 4,234
  • 1
  • 26
  • 32