0

Here is some snippet code. I have tested the methods listed and they work correctly, yet when I run and test this method (countLOC) it only seems to initialize the first variable that has an instance method call (i = self.countBlankLines()). Anyone know the obvious reason I'm obviously missing?

def countLOC(self):  
    i = self.countBlankLines()  
    j = self.countDocStringLines()  
    k = self.countLines()  
    p = self.countCommentLines()  
    return k-i-j-p

This returns -3 because countBlankLines() returns 3 (correctly). however, it should return 37 as countDocStringLines() = 6 and countCommentLines() = 4 while countLines() = 50. Thanks.

7
  • What does print k, i, j, p return? Commented Oct 8, 2009 at 2:33
  • print k = 0 print i =3 print j = 0 print p = 0 Commented Oct 8, 2009 at 2:36
  • note: even if i directly print the methods i still get only the first one i print returning correctly, the rest return 0. seems like a space problem?but the code is not that large..at all. Commented Oct 8, 2009 at 2:42
  • 1
    It seems like your other methods simply don't calculate the values you expect. What's the implementation of these methods? Are you absolutely sure they work correctly? Commented Oct 8, 2009 at 2:48
  • 1
    i just thought of this, this program reads from a file that is opened in the constructor but never closed..i know this is an issue..but where should it be closed? there is no 'deconstructor' as in other languages that im aware of? Commented Oct 8, 2009 at 3:03

1 Answer 1

5

If local variables were not initialized (impossible given your code!) they wouldn't be 0 -- rather, you'd get a NameError exception when you try to use them. It's 100% certain that those other method calls (except the first one) are returning 0 (or numbers totaling to 0 in the expression).

Hard to guess, not being shown their code, but from your comment my crystal ball tells me you have an iterator as an instance variable: the first method to iterate on it exhausts it, the other methods therefore find it empty.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, your guess was correct. I did not realize the iteration exhausted it since i did have it as instance. Thanks a lot. (very new to python) :)
This sounds about right.. If the functions are iterating over a file handle, each function would need to do self.fh.seek(0). Perhaps more cleanly (but less efficiently) you could do something like self.lines = open('myfile').readlines() in the classes __init__ method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.