0

I have a written a custom vector of user defined objects. I need to use something like

for x in vec:
    print(x.function())

However, I might have missed something and I am facing a

ERROR:  Attempted to access index "64" of a vector of objects, but the vector is only of size "64"

It did print out the first 63 just, could not stop before 64.

However this works fine

for x in range(vec.size()):
   print(vec[x].function())

Could anyone figure out what function(s) did I miss in my implementation of iterator or is it simple not allowed in python? If someone could detail out what functions are called in a expr like "for x in vec:" that would be helpful.

Chinmoy Kulkarni
  • 187
  • 1
  • 13
  • Sounds like a bug in your custom vector class, the generator used for iteration is trying to access outside the vector. – Barmar Nov 22 '17 at 17:46
  • Post the code for the custom vector. – Barmar Nov 22 '17 at 17:46
  • You need to implement `__iter__` which must return an iterator. Iterators must implement `__iter__` and `__next__`. Your container should probably only implement `__iter__` and you can either make that a generator function, in which case, it returns a generator which *is an iterator*, or you write a seperate iterator class that implements `__iter__` and `__next__`. The linked duplicate is a bit terse, but you can easily google "python iterables iterators iterator protocol" and find a lot of examples. – juanpa.arrivillaga Nov 22 '17 at 17:47
  • You have implemented `__getitem__`, which is a legacy way of implementing iterable sequences. Essentially, if you lack `__iter__`, python will try to use `__getitem__` using `obj[0]` `obj[1]` etc until you hit an `IndexError`. – juanpa.arrivillaga Nov 22 '17 at 17:50
  • As an aside, you probably don't want a `vec.size()` method. You should stick to the Python data model, and implement `__len__` and use `len(vec)` – juanpa.arrivillaga Nov 22 '17 at 17:52

0 Answers0