1

I am creating a file object and try to access the next() on it. But the interpreter throws error mentioning that the function does not exist.

open("scala.txt").next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

But many discussions that I come across, mention that next() is available. But when I use this object in a for loop, it works fine. Can I get some help on why the above piece of code throws error.

PS: I encounter similar context when I create my own generator & try to invoke next(). When I place the generator object in a for loop, it works nicely.

>>> x = (e for e in range(1,10))
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute 'next'

Thanks!

user3103957
  • 636
  • 4
  • 16
  • Use `next(foo)` instead. The syntax changed in python 3. https://stackoverflow.com/questions/1073396/is-generator-next-visible-in-python-3 – Loocid Jul 08 '20 at 03:24

1 Answers1

2

next() is a built-in function, not a bound method. Example:

next(open("scala.txt"))

x = (e for e in range(1, 10))
next(x)

Behind-the-scenes, calling next() on an object tends to call the bound (but hidden) method __next__(), which does exactly what you think it does.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53