1

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?

1
  • 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.. Commented Mar 25, 2015 at 19:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.