Search code examples
pythongeneratorstopiteration

Don't know why I am getting StopIteration error


I am writing a program that takes in input from a file and each line may contain "ATG" or "GTG" and I am pretty sure I have done everything right as far as what I am trying to do. IT is my first time using a generator in python and after researching this problem I still don't Know why I am getting stop iteration. For this, my generator must yield a tuple with the start locations for either ATG or GTG found in each string.

import sys

import p3mod


gen = p3mod.find_start_positions()
gen.send(None)   # prime the generator

with open(sys.argv[1]) as f:
    for line in f:
        (seqid,seq) = line.strip().lower().split()
        slocs = gen.send(seq)
        print(seqid,slocs,"\n")

gen.close()  ## added to be more official

This is the generator

def find_start_positions (DNAstr = ""):

    DNAstr = DNAstr.upper()

    retVal = ()
    x = 0
    loc = -1

    locations = []

    while (x + 3) < len(DNAstr):

        if (DNAst[x:x+3] is "ATG" or DNAstr[x:x+3] is "GTG" ):
            loc = x

        if loc is not -1:
            locations.append(loc)

        loc = -1

    yield (tuple(locations))

This is the error:

Traceback (most recent call last):
  File "p3rmb.py", line 12, in <module>
    slocs = gen.send(seq)
StopIteration

Solution

  • You made a generator that returns all the data at once. You should yield the data in each iteration. This code might not be perfect, but it might solve part of your problem:

    def find_start_positions (DNAstr = ""):
        DNAstr = DNAstr.upper()
    
        x = 0
        loc = -1
    
        while x + 3 < len(DNAstr):
            if DNAst[x:x+3] == "ATG" or DNAstr[x:x+3] == "GTG" :
                loc = x
    
            if loc is not -1:
                yield loc
    
            loc = -1
    

    The StopIteration isn't an error. It's the way a generator signalizes that it exhausted all of it's data. You just need to "try except" it or use your generator in a forloop that already does that for you. Despite they aren't THAT complicated, it may take some time to get used to these "weird" errors. ;)