Answer the question
In order to leave comments, you need to log in
Why am I getting 'referenced before assignment'?
Greetings,
I’ll immediately clarify that I am aware that this error occurs if you try to use a variable before it is defined.
Here is a simplified code that only works if I 'remove the line' #start_id = f.readline():
#!/usr/bin/env python3
import os
start_id = 1
def main():
print('start_id: ', start_id)
if os.path.exists('./start_id.txt'):
f = open('./start_id.txt', 'r')
#start_id = f.readline()
f.close()
if __name__ == "__main__":
main()
Answer the question
In order to leave comments, you need to log in
Python sees that you are assigning start_id to something and assumes it is a local variable. And then he realizes that you are reading it above, and swears. This is intentional behavior, because otherwise either:
a) the value of the global start_id would be read before the assignment, and after the local one,
b) the global variable would always change instead of the local one, and the appearance of a new global variable with the same name as the local one somewhere then in the function would lead to its unexpected change.
Both are not obvious and could lead to "silent" (without exceptions) but incorrect behavior of the program.
If not assigned, then the local variable start_id does not exist, and reading is performed from the global one.
If you need to change a global variable in this way, then explicitly write it at the beginning of the function as global start_id.
Better yet, don't use global variables unnecessarily. If there is more than one, it's worth redoing it into a class.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question