Fix Python yield AttributeError: ‘generator’ object has no attribute ‘next’ – Python Tutorial

By | November 22, 2021

When we are using python yield statement, we may get AttributeError: ‘generator’ object has no attribute ‘next’. In this tutorial, we will introduce how to fix this problem.

Look at example code below:

def get_data():
    for i in range(10):
        batch_data = i
        yield batch_data

d = get_data()
print(d.next())

Run this code, you will find:

Fix Python yield AttributeError: 'generator' object has no attribute 'next' - Python Tutorial

How to fix this AttributeError?

In python 2.x, you can use next() method. However, in python 3.x, it is replaced by __next__().

In order to fix this error, we can do as follows:

d = get_data()
print(d.__next__())

Then, you can find this error is fixed.

Leave a Reply

Your email address will not be published. Required fields are marked *