I have some Python 3.4 code I have written that does execute correctly but when using different IDE's to help me find errors I get a variable referenced before assignment error in this code snippet:
if os.path.isfile(o.options_file): # Make sure this really is a file.
options = (csv.reader(open(o.options_file), delimiter='\t'))
else:
exit("Options_File Not Found. Check File Name and Path.")
count = 0
for line in options:
count += 1
It is the options variable that is throwing the error. Can this be ignored or should I assign a Null value to options?
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
asked Mar 25, 2015 at 17:14
Dennis Simpson
851 silver badge11 bronze badges
-
A code checker should give you an ignorable warning here, not an error. A false error claim is an error. On the other hand, Martijn's 'bail first on error' solution is a pretty good practice in general..Terry Jan Reedy– Terry Jan Reedy2015年03月25日 19:10:21 +00:00Commented Mar 25, 2015 at 19:10
1 Answer 1
You could just invert the test:
if not os.path.isfile(o.options_file): # Make sure this really is a file.
exit("Options_File Not Found. Check File Name and Path.")
options = (csv.reader(open(o.options_file), delimiter='\t'))
count = 0
for line in options:
count += 1
This makes it far clearer, both to code linting tools and other developers, that the rest of the code won't run if the file doesn't exist.
answered Mar 25, 2015 at 17:15
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py