Python keeps refering to outdated variables - python

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()

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.

Related

I have 2 functions that does the same thing, but while calling both, only one returns while other doesn't [duplicate]

This question already has answers here:
Iterating on a file doesn't work the second time [duplicate]
(4 answers)
Closed 2 years ago.
This is actually a very basic issue i'm facing
# create list using append & idiom method to test process time
fln=open('CROSSWD.TXT')
def check_1(fln):
res=[]
for line in fln:
word=line.strip()
res.append(word) # just create a new list
return res
def check_2(fln):
res2=[]
for line in fln:
word2=line.strip()
res2+=[word2] # using another way
return res2
n=check_2(fln) # now this where the problem occurs. n returns the value
m=check_1(fln) # m return a void list
# it should call both m,n & print same length. They work separately but calling at once does'nt work why?
print (len(n))
print(len(m))
But if I run them separately they work as intended. This is a very basic issue, hope somone can clarify me on this basics
the problem is that you read the file in your first function call till the end thus there is nothing left. Moreover, you are never closing the file.
Thats why it is recommended to use a context manager to interact with files like this:
fln='CROSSWD.TXT'
def check_1(fln):
res=[]
with open(fln) as file:
ctx = file.read()
for line in ctx:
word=line.strip()
res.append(word) # just create a new list
return res
def check_2(fln):
res2=[]
with open(fln) as file:
ctx = file.read()
for line in fln:
word2=line.strip()
res2+=[word2] # using another way
return res2
if __name__ == "__main__":
n=check_2(fln)
m=check_1(fln)
print(len(n))
print(len(m))
The file is "used up" by reading it in check_2. The call of check_1 is trying to continue stepping through the same file, but the end of that file has been reached by the end of the call to check_2.
To read it twice, call fln=open('CROSSWD.TXT') twice.
Another point: Your code neglects to close the file. In a script which exits right after reading a file, you can leave it to the operating system to close the file on exit. But still, you should get use to opening files with the context manager pattern, using with and indenting the block that uses the file.
with fln=open('CROSSWD.TXT'):
res=[]
for line in fln:
word=line.strip()
res.append(word) # just create a new list
return res
Open the file twice.
def check_1(fln):
res=[]
for line in fln:
word=line.strip()
res.append(word) # just create a new list
return res
def check_2(fln):
res2=[]
for line in fln:
word2=line.strip()
res2+=[word2] # using another way
return res2
n=check_2(open('CROSSWD.TXT', 'r')) # now this where the problem occurs. n returns the value
m=check_1(open('CROSSWD.TXT', 'r')) # m return a void list
# it should call both m,n & print same length. They work separately but calling at once does'nt work why?
print(len(n))
print(len(m))

For loop inside function executing only once

I'm facing a problem that I have never encountered, I do invoke a function that contains a for loop many times from another function, but the latter is only executing once and I don't know what I did wrong.
here is the function that contains the for loop.
def check_neutre(word):
global f4
i = 0
neutre = []
print(word)
for ligne in f4:
neutre.append(ligne.strip())
print(len(neutre))
return "done"
f4 is a file variable opened at the top.
and here the function that calls it
def check_words(words):
polarite = 0
exist = False
for word in words:
print(check_neutre(word))
check_words(words)
words variable is a list of words.
the output above shows that the loop is executed only once
I think you are searching for looping over each line of the file, and in your code you just loop it all at once
you can change to this in the start of the file:
f4_lines = f4.readlines()
and use the global of f4_lines instad of f4
If it is a large file maybe there is another solution cause this will loads the file into the memory

Del variable inside a Loop

I am very new to python and programming. I am learning about loops right now, and tried the following code to see what would happen. What I would like to know is why the following code does not crash or keep repeating "Robert".
Thank you.
name = ["Robert", "Mike", "Garry", "Alex"]
for y in name:
print(y)
del y
print("END")
Each iteration of the for loop creates a "new" y. By deleting this y each time, you are simply deleting the y that belongs to that iteration. It is "recreated" again at the start of the next iteration.
The del won't change the result of this code at all.
The code works because after you delete the name y, you create it again in the next iteration of the loop.
If you try to print y after the loop, you'll see that it won't work with the del statement in.

Python print statement not executing

I have a function that I'm calling from my main function.
def generate_new(tokens, outfile):
print('NO')
new_sents = []
for i in range(0, len(tokens)):
first = tokens[i]
second = tokens[i]
print('YES')
This is working fine. However, when I'm adding one more statement, only the first print gets executed.
def generate_new(tokens, outfile):
print('NO')
new_sents = []
for i in range(0, len(tokens)):
first = tokens[i]
second = tokens[i+1]
first_found = first
print('YES')
I've already tried flushing the buffer. I suspect it's an indentation issue but this code was running fine previously. I added some statements to the end of the function and since then it never executes the statements outside the loop. What could be the issue? Thank you.
The issue is that you are accessing the list tokens out of bounds,
range(0, len(tokens)) goes from 0 to len(tokens)-1
Now when you access tokens[i+1], it throws an index out of bound exception and execution stops. As a result nothing after the loop gets executed.
You should be able to see the Exception on the console.
Anyway, the fix -
Either change the logic or iterate only till len(tokens)-1
I hope that explains the issue.

Handling dependency of functions in python

I want to write a script for automation of sequence of events, where the execution of the next sequence depends upon the success of the previous step. There are basically 8 functions which I want to call onne by one and if one fails, I want to exit at that point. So how can i handle this in python?
Basic if, and elif statements can overcome your needs.
Say you had a function that returned a variable.
def f(z):
data = z
return data
You can analyse the result with a if. Assign a new variable to the function f:
x = f(0)
if x == 0:
#do something
So if x is equal to 0, continue with code. But what is c = 1?
import os
x = f(1)
if c != 0:
os._exit(0)
os._exit(0) quits the program.
I highly recommend taking a look at pytest (or one of the other Python testing frameworks).
This guide should get you up and running quickly:
http://pytest.org/latest/getting-started.html

Categories

Resources