0

I have a kinda weird problem, here is my attempt at an explanation:

I'm currently making a program which opens a txt file and then reads a line for that file, using the following command linecache.getline(path,number), after the function is done I then use commmand linecache.clearcache.

If I then change something in the text file it keeps returning the pre-changed line.

Following is the code I'm using (I know it aint really pretty)

def SR(Path,LineNumber):    
    returns = lc.getline(Path,LineNumber)      
    x = np.array([])
    y = np.array([])
    words = returns.split()
    for word in words:
        x = np.append([x],[word])

    for i in range(len(x)):
        t = float(x[i])
        y = np.append([y],[t])
    return y
    del x
    del y
    del t
    del words
    lc.clearcache()
  • 4
    `lc.clearcache()` is never invoked, because you placed it after `return`. – Konstantin Mar 31 '14 at 14:26
  • 1
    What is the point of using `linecache` if you clear the cache after every line read? Why not just use a regular `open(filename)`/`file.read()` operation? – Joel Cornett Mar 31 '14 at 15:33

1 Answers1

5

Nothing after the return statement will ever be executed. If you want to call clearcache, you need to call it before the return statement.

Also, as a side note, your del statements aren't really going to do anything either, even if they were placed before the return. del effectively just decrements the reference counter in the gc, which will happen when the interpreter exits the function scope anyway.

Silas Ray
  • 25,682
  • 5
  • 48
  • 63
  • That did the trick, thanks for the comment about the del statements as well! –  Mar 31 '14 at 14:32
  • 1
    "call it before the return statement" -- or in a `finally` block whose `try` block contains the return statement, in the case where you want to execute `clearcache()` even if something throws. Which in this case is probably only going to happen due to lack of memory, but in general if you're doing cleanup think `try ... finally` or context managers. – Steve Jessop Mar 31 '14 at 15:15
  • @SteveJessop Good point, though if wrapping in a `try`/`except`, it would probably be prudent to wrap all or almost all of the body of the function. – Silas Ray Mar 31 '14 at 16:05
  • 1
    @SilasRay: indeed. I'm thinking of something like `returns = lc.getline(Path,LineNumber)` `try:` ... rest of the function up to return ... `finally:` `lc.clearcache()`. Hope that's clear enough given lack of formatting in comments :-) Although as Joel Cornett points out above, there's something odd about clearing the cache so often. – Steve Jessop Mar 31 '14 at 16:19
  • Ah now it makes more sense, I'll try it out, thanks! –  Mar 31 '14 at 16:30