Getting error while calling generator in Python

Viewed 43

I created a simple generator:

def long_time():

    for i in range(10):

        yield i * 5  

a = long_time()

print(next(a))

print(next(a))

Here, I get the outputs 0 and 5, which is OK. But when I try to build the variable a as below:

def long_time():

    for i in range(10):
        yield i * 5
  
a = long_time

print(next(a()))

print(next(a()))

Both of the print outputs are 0. What is the difference, should I always call the generator with ()?

2 Answers

When you write

a = long_time 

you're just giving a different name to the function long_time.

So writing

print(next(a()))

is the same as writing

print(next(long_time()))

That is, in a single line, you get a generator object by calling long_time(), then pass it to next, getting the generator's first value 0. But since you don't have a reference to that generator, after that line you can't access the object anymore. On your next print... line, you're getting a fresh generator since it involves a new call to long_time().

This is fixed when a isn't a reference to the long_time function, but its return value (the generator) instead:

a = long_time()

When you call long_time, you get back a fresh generator object. In your second example, a is just another name for the generator function, so each time you call a(), you get a new generator (just as if you had called long_time) that starts at 0.

Related