Flake8 Not Recognizing built-in exception

Nate Mara picture Nate Mara · Aug 14, 2014 · Viewed 6.9k times · Source

I have a strict pre-commit hook set up with flake8, so I can't commit until its happy. This is normally a good thing, but it is causing some problems with what seems like no problem at all.

I can't get Flake8 to recognize a FileNotFoundError.

example.py

try:
    pass
except FileNotFoundError:
    pass

This is enough code to get Flake8 to generate the error

$ flake8 example.py
example.py:3:8: F821 undefined name 'FileNotFoundError'
$ python example.py # no error
$ python3 example.py # no error

I checked the python docs, and FileNotFoundError is a 'built-in' exception, so I don't think I should have to import it from anywhere, and my python interpreters have not complained about it, just seems like an issue with flake8.

Answer

b-jazz picture b-jazz · Dec 21, 2015

I found a couple of mentions of this issue on the Python Code Quality tools repo. Specifically Issue #75.

Two workarounds were listed. You can use the --builtins flag to specify a comma separated list of known builtins that flake8 is flagging.

$ flake8 example.py
example.py:3:8: F821 undefined name 'FileNotFoundError'
$ flake8 --builtins=FileNotFoundError,... example.py
$ 

The other workaround is running flake8 under python3 instead of python2.

$ /usr/bin/python3.5 -m pyflakes example.py 
$ 

Hopefully one of these two solutions will work out for you, as twisting your code up to work around a syntax check tool is counterproductive.