Generator problem in Python

I tried to understand generators in Python and implemented this:

def yfun():
    print("into y fun ... ")
    for x in range(1,6):
        print("tryin to yield : {}".format(x))
        yield x

yieldVar = yfun()

for val in yieldVar:
   print("value generated -> ", val)

      

The output looks like this:

into y fun ...
tryin to yield : 1
value generated ->  1
tryin to yield : 2
value generated ->  2
tryin to yield : 3
value generated ->  3
tryin to yield : 4
value generated ->  4
tryin to yield : 5
value generated ->  5

      

Could you please explain why the function is being called over and over again? Shouldn't the variable have a value and iterate over the generator variable?

+3


source to share


2 answers


The function is not called over and over, and you can see that the fact that it "into y fun ..."

is only printed once.

What happens is, the generator that you call by calling the containing function is yield

promoted (i.e. consumed) with a for loop.



yieldVar = yfun()  # call yfun and get a generator

      

As long as the generator keeps on giving values, the loop starts and prints the items you gave.

+4


source


When a generator function is called, a generator object is returned. No value as a normal function. It is an object that can be used for lazy evaluation. Each generator object has a method named __next__()

. This allows Python to repeatedly call a value from a generator object rather than a function - yieldVar

multiple times by calling __next__()

.



+1


source







All Articles