How to avoid StopIteration Error in python

JohnConneely picture JohnConneely · Jun 26, 2013 · Viewed 63.4k times · Source

I have a line that is pulling in variables from multiple lists and I want it to avoid the StopIteration error that comes up so that it can move onto the next line. At the moment I am using the break function, this avoids the StopIteration, but only gives me the first item in the list and it leaves a blank line after it, if i was to print it out.

Here are two of my iterations that have the same problem.

def compose_line5(self, synset_offset, pointer_list):
    self.line5 = ''''''
    for item in pointer_list:
        self.line5 += '''http://www.example.org/lexicon#'''+synset_offset+''' http://www.monnetproject.eu/lemon#has_ptr '''+pointer_list.next()+'''\n'''            
        break
    return self.line5

def compose_line6(self, pointer_list, synset_list): 
    self.line6 = ''''''
    for item in synset_list:
        self.line6 += '''http://www.example.org/lexicon#'''+pointer_list.next()+''' http://www.monnetproject.eu/lemon#pos '''+synset_list.next()+'''\n'''                      
        break
    return self.line6

This is the error I get without the break:

Traceback (most recent call last):
  File "wordnet.py", line 225, in <module>
    wordnet.line_for_loop(my_file)
  File "wordnet.py", line 62, in line_for_loop
    self.compose_line5(self.synset_offset, self.pointer_list)
  File "wordnet.py", line 186, in compose_line5
    self.line5 += '''http://www.example.org/lexicon#'''+self.synset_offset+''' http://www.monnetproject.eu/lemon#has_ptr '''+self.pointer_list.next()+'''\n'''
StopIteration

Is there a quick fix for this or do I have to catch exceptions for every method I use the iter() in?

Answer

Thomas Vander Stichele picture Thomas Vander Stichele · Jun 26, 2013

In compose_line5, instead of pointer_list.next(), use item - you are already iterating over pointer_list.

For compose_line6, it seems you want to iterate over two lists at the same time. Use the top answer from Is there a better way to iterate over two lists, getting one element from each list for each iteration? (I'm assuming both lists are the same length)

Yes, the iterator protocol will raise StopIteration (not an error, just an exception signalling the end of the iteration) if you call .next() on it manually. The pythonic way to use it is to use it as a normal iterator (for example, looping over it) and not call .next() on it.

Your code has a few issues beyond that that you may want to look at - look at http://www.python.org/dev/peps/pep-0008/

For example, no need to use '''''' when '' suffices. Instead of doing +=, you may want to create a list then join in the end. Not sure why you store things in self if you're just returning them from the function.