Linters are code writing tools that analyse the source code and detect programming errors, style flaws, bugs and suspicious code. Fixers, as the name suggests, are code writing tools that simply format or ‘fix’ the code. This article gives a brief introduction to both.
In real life, when one works on a project as a team member, one often faces difficulties when going through code written by other members of the team. Due to the different formatting followed by different developers, it can often become very difficult to go through the code. Besides that, there are small tab and space issues that are rather annoying during code execution, especially when the errors are scattered. Linters and fixers are tools that help to mitigate this problem.
Linters are programs that analyse code and report issues like:
- Structural error
- Syntax error
- Best practice and code style guideline (PEP8 for Python)
Fixers are programs that format the Python code as per the PEP8 standards. Integrating them with the IDEs helps developers a lot, as they take care of formatting issues automatically.
Popular linters in the market include:
- Flake8
- Pylint
- Pyflakes
- Pychecker
- Mypy
- Pep8
PyLama
Popular fixers in the market are:
- Black
- YAPF
- autopep8
How to install Flake8
Flake8 is one of the most popular linters for Python. To install it to your default Python location, type:
$ Python –m pip install flake8
Now that you have installed it, it’s time to test it out. All you need to do is to execute the code, as follows:
$ flake8 hello.py
The above execution will provide a list of all the issues with the code. This linter has another cool feature. If you want to ignore some issue the program has made a note of, you can do so with the code given below:
$ flake8 –ignore W54 hello.py
How to install Black
Black is the most popular formatter or fixer for Python code. It is also very simple to install and use. To install it in the default Python environment, run:
$ Python –m pip install black
To use the fixer, execute the code given below:
$ black hello.py
The file hello.py will be formatted.
How to configure VS Code to use a linter and fixer
To setup Flake8 in VS Code, go to Settings and search for Flake8. The output will be as shown in Figure 1.
Paste the path of Flake8 from your system as follows: Python > Linting: Flake8 Path.
Now, to set up Black, again go to Settings and search for Black. The output is shown in Figure 2.
Now select Python under the Extension menu on the left. Add the path of the Black installation in the system as follows: Python > Formatting: Black Path.
Next, from the drop down menu, select Black as the option.
Linters and fixers can be great friends of developers as they make it easier to address errors in coding. This article only gives a brief introduction to them. There is a lot more that can be learnt about them.