Yet another reason to use Python Flake8

Rakesh Kumar
StackMyBiz
Published in
2 min readJul 13, 2018

Flake8 is a Python linter that ensures a consistent code format. It is generally integrated with Continuous Integration so that developers do not check-in the badly formatted code. It offers a variety of plugins which focuses on different aspects of code style or formatting issues. One of the plugins is Flake8-tidy-imports, it makes sure that deprecated or banned modules are not used in the code. Here is a scenario where it is useful.

Your service is dependent on other libraries. The team who owns the library, decides to split the library into multiple sub-libraries with logically isolated module because it was getting bigger and harder to manage.The team sends out a notification that the library has been banned and all the bug fixes will be available in the new libraries. Since you are a proactive developer who takes care of these things seriously, you update your service by replacing the old modules with the new ones. However, some developers in your team are busy with a high priority task and are oblivious to these changes. They add the older library while implementing a new feature without realizing that it has been deprecated. You notice this code creep and wonder how you could have prevented it. There must be an automated way of preventing something like this.

Well, there is Flake8-tidy-imports comes to your rescue. This is a Flake8 plugin that checks for banned modules and raises an error if the banned modules are used. You don’t even need any special command to invoke this plugin. It automatically gets invoked with flake8 command. You just need to make sure that flake8-tidy-imports is part of your linter environment.

You can also customize the error message by suggesting the right module that should be used instead. The customization can be done using the setup.cfg file. Example:

[flake8]banned-modules =
py.test = Use `pytest` instead
flask.ext.restful = Use `flask_restful` instead
flask.ext.script = Use `flask_script` instead
python-s3file = Use `boto3` instead

The banned-modules should come under the Flake8 section. The following error is logged when the Flake8 command is executed. This way, the developer immediately knows that he has used the deprecated or banned module has been used and the error should be fixed immediately before moving forward.

./pricing/web/__init__.py:3: [I201] Banned import 'flask.ext.restful' used - Use `flask_restful`.

Ideally, the Flake8 lint should be part of the Continuous Integration and should block the build if it notices any lint issues. This ensures the code quality in automated fashion.

--

--

Rakesh Kumar
StackMyBiz

Hi, I am an engineer with extensive experience in highly distributed & scalable systems.