2

I am using Python 3.5 but this book is teaching 2.7 (beats me why in 2016)

Learning Predictive Analytics with Python by Ashish Kumar Feb 15, 2016

    >>> data=open(filename,'r')
    >>> cols=data.next().strip().split(',')
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        cols=data.next().strip().split(',')
    AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
    >>> 

I have read this AttributeError: '_io.TextIOWrapper' object has no attribute 'next' python and I still don't know how to get it to work in Python 3.5 GUI shell.

So far, I understand for Python 3.5 I have to use .__next__; for Python 2.7 .next.

Community
  • 1
  • 1
goughgough
  • 91
  • 9

1 Answers1

7

Use the next() function on iterators:

cols = next(data).strip().split(',')

This is compatible across Python versions.

You could indeed swap .next() for .__next__(), but it is better to use the standard function here, just as you'd use len(obj) instead of calling obj.__len__(). Double-underscore methods are hooks used by Python, your code should use the standard APIs that may or may not call those hooks. This is especially true here, where the hook name changed.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • In addition, the api calls are guaranteed to work even if the underlying methods (like `__next__()`) are changed. – Burhan Khalid Apr 05 '16 at 08:25
  • Thanks a million. It works . Martin. Don't you ever sleep ? :) – goughgough Apr 05 '16 at 08:27
  • @MartijnPieters Just a question; when does one needs to use these *hook methods* ? – Iron Fist Apr 05 '16 at 09:29
  • 1
    @IronFist: when you are trying to use *just* the hook effect; so when you are implementing `__ne__` you can call `self.__eq__` to avoid having Python test the inverse too if your own `__eq__` returns `NotImplemented`. Or when you want to avoid infinite recursion in `__getattribute__` you'd use `super().__getattribute__`, etc. So you call the hook method directly when you must, otherwise use the standard path. – Martijn Pieters Apr 05 '16 at 09:40