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.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • What does print k, i, j, p return? – Billy Herren Oct 08 '09 at 02:33
  • print k = 0 print i =3 print j = 0 print p = 0 –  Oct 08 '09 at 02: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. –  Oct 08 '09 at 02: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? – sth Oct 08 '09 at 02:48
  • im sure they work correctly, i have a test driver set up to test these methods extensively. they have worked for quite some time. The basically implementation for each is a while loop that adds a string to a list and then returns the length of the list. –  Oct 08 '09 at 02:51
  • Well, something's wrong, and it's not in the part of code you posted. – sth Oct 08 '09 at 03:01
  • 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? –  Oct 08 '09 at 03:03

1 Answers1

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.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 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) :) –  Oct 08 '09 at 03:09
  • 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 – dbr Oct 08 '09 at 03:12