-3

enter image description here

When I use a imported package, I use an object that it gives to me. I found it has a next method so I just try use next() build-in function to generate next item of it,but something is wrong. And i wonder what is the built-in method of an Object, I never see it before. And i am using python 2.7.12 Thank you!

David
  • 11,245
  • 3
  • 41
  • 46
kyle
  • 1
  • 1
  • You need to have an Iterator object for next to make sense. – Henno Brandsma Dec 01 '16 at 17:41
  • You haven't provided enough information to be sure, but I'm guessing the built-in `next()` function isn't recognizing that the `Reader` object `p` is an iterator (probably because it doesn't have an `__iter__()` method), so it doesn't call its `next()` method. – martineau Dec 01 '16 at 17:44
  • What is this `Reader` object coming from? It looks like a buggy C implementation that defined a `next` method directly without setting `tp_iternext`. – user2357112 Dec 01 '16 at 17:54
  • Are you using Pcapy? – user2357112 Dec 01 '16 at 17:58
  • Thank you, I am indeed using pcapy. And in my opinion, the built-in function next don't need an iterator. If an obeject have a next() method it can be passed to built-in function next. The object needn't to have __iter__().I have test it. I have a object just have next method. I t can be passed to built-in function next. – kyle Dec 01 '16 at 19:07
  • Please do not paste pictures of code into your question. Copy-paste the actual code & error message. – Robᵩ Dec 01 '16 at 19:57

2 Answers2

0

The next() builtin function is behaving perfectly fine. While Reader() does appear to have a next() method, it is missing another important method. The next() builtin function requires an iterator object, which is why a TypeError is raised.

If a class is to be used in the manner of an iterator, it needs a minimum of two methods:

  • __iter__() Which is used to call next().
  • next()(Changed to __next__ in Python 3) Which returns the next item from the iterator.

The Python 2.7 documentations definition for next() can help confirm this:

Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

The most likely scenario, is that the Reader class does not implement the__iter__() method, which means the next() method cannot be called.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

It looks like you're using a Pcapy Reader object. While this object has a method named next, it is not an iterator and does not support iteration.

Ordinarily, this wouldn't matter, and the next built-in function would see the next method and call it, but Reader is written in C. A type written in C must provide a tp_iternext function in the C struct representing the type, not just a next method, to be recognized as an iterator, and this type sets tp_iternext to 0.

user2357112
  • 260,549
  • 28
  • 431
  • 505