I get "UnboundLocalError: local variable 's' referenced before assign" in python script on one machine but not on another where the script runs OK. Both machines are on Windows 7 and use Python 2.7.3. Any suggestions what could be the reason for this behaviour? Thank you.
Here's the code that causes the error:
with open(self.temp_dir + test + ".log",'r') as log:
for line in log:
if "INPUT_SENTENCE" in line:
match = patternInput.match(line)
inputSentence = match.group(1).lower()
if inputSentence in self.testToDiagDict[test]:
continue
self.testToDiagDict[test][inputSentence] = []
if "STATS" in line:
if "Input Sentences" in line:
inputSentences = patternValue.findall(line)
self.testToDiagDict[test][inputSentence].append(inputSentences[0])
And the trace:
File "C:\X\Y\X\script.py", line 90, in extract_data
if "Input Sentences" in line:
UnboundLocalError: local variable 'inputSentence' referenced before assignment
The problem is on this line:
self.testToDiagDict[test][inputSentence].append(inputSentences[0])
There is no inputSentence in that scope
So the code might have worked on one machine because this if statement
if "INPUT_SENTENCE" in line:
evaluated to true, but in the case that it doesn't, that is when you get that error. I can't suggest a fix because I don't know what the rest of your code looks like or what you are trying to accomplish, but the much I have pointed out should allow you to reevaluate your design
Perhaps as #inspectorG4dget says - you have a different codepath somewhere. Here is a simple example that could cause your error
def f():
if machine1:
s = 1
else
S = 2
print s
If you would show the code, it would probably take just a few seconds to find
Related
I was faced with a very strange problem.
With print() this code works.
def max_pairwise_product(numbers):
max_1 = max(numbers)
numbers.remove(max_1)
max_2 = max(numbers)
return max_1 * max_2
if __name__ == '__main__':
input_n = int(input())
print() # <- comment of this line breaks the code
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers))
If I comment or delete the 10-th line with print() I got an error:
Traceback (most recent call last):
File "C:\Users\...\maximum_pairwise_product_fast.py", line 12, in <module>
print(max_pairwise_product(input_numbers))
File "C:\Users\...\maximum_pairwise_product_fast.py", line 2, in max_pairwise_product
max_1 = max(numbers)
ValueError: max() arg is an empty sequence*
Process finished with exit code 1
I use Python 3.9. PyCharm.
I tried to launch with different virtual environments with Python 3.8 and 3.10 – the same error.
When I launch in Jupyter and Colab – it is fane – no error.
There are no issues with any other Python script. I used the installation for several months and there was nothing strange.
It is so strange that I have no idea. Could you please help me?
Try checking if your python interpreter is working correctly and is the latest python
It might fix it or there's probably a problem with your ide.
Thank you all for helping to refer me in the right direction.
The reason for the error was a bug in PyCharm. It sent not was typed. The issue disappeared after the PyCharm update from version 2022.1.1 to 2022.1.2.
Back in 2018 or so, I found a similar strange issue in a Python program I downloaded that solved Rubik's cubes. Basically, the program ran just fine under Linux, but under Windows it was erroring out at a certain line that looked fine.
I ran "pyflakes" on that program, but pyflakes reported that nothing was wrong. Odd.
The line that supposedly contained the error was a list comprehension, much like your line here:
input_numbers = [int(x) for x in input().split()]
I replaced the list comprehension with a normal for-loop, and then the code ran fine with no errors. Basically, if I were to rewrite your line, I would replace it with the following four lines:
input_numbers = []
for x in input().split():
input_numbers.append(int(x))
assert input_numbers, "input_numbers is empty!"
I have no idea why the error was happening in the first place, and only on Windows. (The version of Python3 I was using certainly supported list comprehensions; I checked.) But once I replaced the list comprehensions with a for-loop, the code worked.
So my advice is to replace your list-comprehension with a for-loop and see if that solves anything.
I don't know if that will work, but it's worth a shot, as it seems that your input_numbers list is not actually being populated before it's passed to max_pairwise_product().
You might even try putting the assert statement:
assert input_numbers, "input_numbers is empty!"
after the list comprehension to verify that input_numbers is truly being populated. If it's not, then you at least have narrowed down your problem, and will now have to figure out why it's not being populated.
P.S. I'm curious: Which operating system(s) does the error happen on?
P.P.S. I recommend adding input text to your input() calls (such as input("Type some space-separated numbers: "), even if just for posting here. Otherwise, when stackoverflow users run your code, it looks like your code is hanging.
Excuse the debugging question, new to coding in general. Cannot understand why my code suddenly wont run.
I have checked for typos which seems to not be my problem.
filepath = '/proper_noun.txt'
def pluralize(word):
proper_nouns = [line.strip() for line in open (filepath)]
for item in proper_nouns: ### print out the list once.
if (item==[-1]):
break;
currently working in google colab.
At this point, I'm just trying to return the items from 'proper_nouns' into a list to get the ball rolling. Any ideas?
print (proper_nouns)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-29-c6832e0493e8> in <module>()
----> 1 print (proper_nouns)
NameError: name 'proper_nouns' is not define
Thanks guys. I hope this question follows SOF etiquette
Since you are working on Google Colab, my guesss is that you accidentally don't run the code from the beginning (from example if you selected the code starting from for item in proper_nouns: and only run the selected part, or if you split your program in different cells), and therefore proper_nouns is not defined yet.
Please make sure you run everything and tell us if that was it.
EDIT: I just thought of another option: is the line print(proper_nouns) in the pluralize function? If not, the scope of proper_nouns being the function, it's normal that it is not defined outside of the function. To access it from the outside, you must either declare it outside the function, or return it.
I am getting a strange error when defining variables in Python 4.1.5 (IDE:Spyder). However, even with the error, the code runs without any issues!
As you can see, the variable social_cost_of_carbon is stored as a variable, but I keep getting that error as show in picture 1 (the error writes: Undefined name 'social_cost_of_carbon' (Pyflakes E)
I feel that the way that i declare those variables might be the reason:
def convert_to_var(df):
desc = []
val = []
for i,row in df.iterrows():
desc.append(i)
val.append(row)
return dict(val)
val_dict = convert_to_var(IA)
locals().update(val_dict)
Since the code runs without any problems, I am not doing anything to resolve this. Do I need to worry and fix this, or do I just let it be and continue without dealing with the error since the code runs smoothly?
Thanking you in advance.
(Spyder maintainer here) As you guessed, the problem is that you're creating your variable dynamically with this line in your code:
locals().update(val_dict)
Since our linter can't find where that variable is properly declared, it reports that it's undefined. But it's safe for you to ignore that message.
Note: For now it's not possible to hide linter warnings. However, in a future version we'll provide a way to do that by adding a comment at the end of a line of the form # noqa.
I just run this following code and hope to get the font_size outside the with command but get this error:
def text_image(text_path, font_path = None):
with open(text_path, 'r+', encoding='utf-8') as text_file:
for num, data in enumerate(text_file, 1):
lookup4font_size = 'Font-size:'
if lookup4font_size in data:
font_size = next(text_file)
print(font_size)
and I get this error:
UnboundLocalError: local variable 'font_size' referenced before assignment
Does anyone can help me fix this problem. Thank you very much.
If your loop doesn't find what it's looking for, it ends and tries to print(font_size). But it only sets font_size if it does find what it's looking for (and then returns, so the print is never reached in the cases where font_size exists). Remove the print; it's definitionally never going to be possible for it to succeed.
I hope this is an easy one for you guys.
This is my script, for Nuke.
selNodes = nuke.selectedNodes()
for list in selNodes:
if list.Class() == 'Read':
layerArray = []
# Get the list of layers and make unique using set
for chanList in list.channels():
channelLayer = chanList.split('.')
layerArray.append(channelLayer[0])
print list(set(layerArray))
It gives an error:
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'Node' object is not callable
So I tried a simpler code of the same nature:
a = [1, 1]
print list(set(a))
And it didn't work. Same error message. Now here's the strange thing: I opened up a new Nuke and ran the simpler codes again, it worked. I couldn't understand why, but I was happy. So I put in my original codes and ran it, error message. I deleted them, the editor is now clean. And ran the simpler code again, error message!!
Which means that a working code can be rendered failure after I pasted and deleted something else!
Can anyone shed some light on this issue? Nuke is a very established software I don't know if it's a software bug.
It is because, you are using list as the loop variable, which hides the builtin function list. You are using that function in
print list(set(layerArray))
The loop variables are leaked even when the loop is over, check this program to understand better
for i in range(10):
pass
print(i)
This will print 9. It means that, i is still available in the program even after the loop is over. The case in your program, after iterating over the selNodes, list variable has the last variable. And you are trying to call that like a function when you say
print list(set(layerArray))
That's why it fails. There are two ways to fix this.
Just change the loop variable to something else.
Use del list when the loop is over. Just pretend that I didn't suggest this. This is NOT recommended. Just change the loop variable to something else.