Dennis Simpson
Dennis Simpson

Reputation: 85

Python Code Structure

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?

Upvotes: 1

Views: 155

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121962

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.

Upvotes: 2

Related Questions