Invoke flake8 in Python Project

Invoke flake8 in Python Project

·

2 min read

Flake8 is a popular lint wrapper for python. In this article, we will understand the uses of flake8 against our python projects.

  • What is flake8?

  • Install flake8 in your project

  • Run flake8 against your project

  • Configure flake8 in config.cfg

What is flake8?

Flake8 is a wrapper around these tools:

  • PyFlakes

  • pycodestyle

  • Ned Batchelder’s McCabe script

Flake8 runs all the tools by launching the single flake8 command. It displays the warnings in a per-file, merged output.

Install flake8

First, we need to create a project.

mkdir simple_calculator

Let's create a virtual environment inside the project and activate the virtual-env.

cd simple_calculator
python3 -m venv venv
source venv/bin/activatte

Now let's install flake8 in your project

pip install flake8

Let's add a file called calculator.py in your project and add the following content to it.



class calculator(object):
    def __init__(self, *args):
        super(calculator, self).__init__(*args)

    def addition(self, a, b):

        return a + b

    def Substraction(self, a, b ): 
        return a - b

    def multiplication(self, a, b):
        return a * b


    def Division(self,a, b):
        return a / b

Run flake8 against your project

Now let's run flake8 against your project

flake8 --exclude=venv --count

In the above command --exclude providing a comma-separated list of glob patterns to exclude from checks and --count printing the total number of errors.

You can see the following in your terminal.

The error will come in this format by default - '%(path)s:%(row)d:%(col)d: %(code)s %(text)s' .

To know more about the options available with flake8, please visit the official documentation - https://flake8.pycqa.org/en/latest/user/options.html.

Configure flake8 in config.cfg

You can pass flake8's configuration parameters using a setup.cfg file. You can add the following configuration in your config.cfg file.

[flake8]
exclude =
    .git,
    __pycache__,
    venv
max-complexity = 10
count = True

Now you can just run flake8 in your terminal and able to see the same result.

You can resolve the errors in your code one by one. It's quite clear from the warning we're getting in flake8-generated logs. Then you should be able to get the count as 0.

We have reached the end of this short article. I hope you understand the purpose of flake8 in python and you'll be using flake8 in your next project.

Happy Learning!!